Files
awesome_anti_virus_engine/ai_anti_malware/sandbox_callbacks.cpp
2025-03-06 18:39:01 +08:00

98 lines
3.4 KiB
C++

#include "sandbox_callbacks.h"
#define LOG_LEVEL 0
namespace sandboxCallbacks {
void handleCodeRun(uc_engine* uc, uint64_t address, uint32_t size,
void* userData) {
uint64_t currentRip = 0;
uint64_t currentRsp = 0;
uint64_t currentRax = 0;
auto* sandbox = static_cast<Sandbox*>(userData);
if (!sandbox) return;
// 读取当前执行的代码
auto codeBuffer = std::make_unique<uint8_t[]>(size);
if (uc_mem_read(uc, address, codeBuffer.get(), size) != UC_ERR_OK) {
return;
}
uc_reg_read(uc,
sandbox->GetPeInfo()->isX64 ? UC_X86_REG_RAX : UC_X86_REG_EAX,
&currentRax);
uc_reg_read(uc,
sandbox->GetPeInfo()->isX64 ? UC_X86_REG_RIP : UC_X86_REG_EIP,
&currentRip);
uc_reg_read(uc,
sandbox->GetPeInfo()->isX64 ? UC_X86_REG_RSP : UC_X86_REG_ESP,
&currentRsp);
for (auto module : sandbox->GetModuleList()) {
for (auto item : module->export_function) {
const auto vmAddress = module->base + item->function_address;
if (vmAddress == currentRip) {
printf("[%s] call function %s at file address: %llx\n",
module->name, item->name, address);
sandbox->EmulateApi(uc, vmAddress, currentRip, item->name);
}
}
}
if (LOG_LEVEL > 0) {
// 使用Capstone反汇编
cs_insn* instruction;
size_t instructionCount =
cs_disasm(sandbox->GetCapstoneHandle(), codeBuffer.get(), size,
address, 0, &instruction);
if (instructionCount > 0) {
// 打印地址和反汇编结果
printf("0x%016" PRIx64 " %-12s %s\n", instruction[0].address,
instruction[0].mnemonic, instruction[0].op_str);
}
cs_free(instruction, instructionCount);
}
}
void handleMemoryRead(uc_engine* uc, uc_mem_type type, uint64_t address,
int size, int64_t value, void* userData) {
auto* sandbox = static_cast<Sandbox*>(userData);
if (!sandbox) return;
uint64_t regRax, regRip;
uc_reg_read(uc,
sandbox->GetPeInfo()->isX64 ? UC_X86_REG_RAX : UC_X86_REG_EAX,
&regRax);
uc_reg_read(uc,
sandbox->GetPeInfo()->isX64 ? UC_X86_REG_RIP : UC_X86_REG_EIP,
&regRip);
uint64_t readAddress;
auto readError =
uc_mem_read(sandbox->GetUnicornHandle(), address, &readAddress, size);
if (LOG_LEVEL > 0) {
printf(
"[handleMemoryRead] Address: %p Size: %p Rax: %p Rip: %p Error: %d "
"ReadData: %p\n",
address, size, regRax, regRip, readError, readAddress);
}
}
void handleMemoryUnmapRead(uc_engine* uc, uc_mem_type type, uint64_t address,
int size, int64_t value, void* userData) {
// 待实现
auto* sandbox = static_cast<Sandbox*>(userData);
uint64_t Rip = 0;
uc_reg_read(uc,
sandbox->GetPeInfo()->isX64 ? UC_X86_REG_RIP : UC_X86_REG_EIP,
&Rip);
printf("[handleMemoryUnmapRead] Address: %p Size: %p Value: %p Rip: %p\n",
address, size, value, Rip);
}
void handleMemoryWrite(uc_engine* uc, uc_mem_type type, uint64_t address,
int size, int64_t value, void* userData) {
// 待实现
}
void handleSyscall(uc_engine* uc, void* userData) {
// 待实现
}
} // namespace sandboxCallbacks