vmp完整源码分析-8-核心引擎实现

# VMProtect 核心引擎实现详解

20260402111256268-image

 

## 1. 水印系统实现

### Watermark 类实现

水印用于在受保护程序中嵌入特定标识,用于追踪泄露源头。

“`cpp
// 水印数据结构
class Watermark : public IObject {
WatermarkManager *owner_; // 所属管理器
size_t id_; // 水印ID
std::string name_; // 水印名称
std::string value_; // 水印值(十六进制字符串)
size_t use_count_; // 使用次数
bool enabled_; // 是否启用
std::vector<uint8_t> dump_; // 编译后的字节码
std::vector<uint8_t> mask_; // 掩码(?表示通配符)
std::vector<size_t> pos_; // 搜索位置
};
“`

### 水印编译过程

“`cpp
void Watermark::Compile() {
dump_.clear();
mask_.clear();

if (value_.size() == 0) return;

// 将十六进制字符串转换为字节码
for (size_t i = 0; i < value_.size(); i++) {
size_t p = i / 2;
if (p >= dump_.size()) {
dump_.push_back(0);
mask_.push_back(0);
}

uint8_t m = 0xff; // 默认掩码为全匹配
uint8_t b;
char c = value_[i];

// 解析十六进制字符
if ((c >= ‘0’) && (c <= ‘9’)) {
b = c – ‘0’;
} else if ((c >= ‘A’) && (c <= ‘F’)) {
b = c – ‘A’ + 0x0a;
} else if ((c >= ‘a’) && (c <= ‘f’)) {
b = c – ‘a’ + 0x0a;
} else {
// 通配符 ?
m = 0;
b = rand();
}

// 组合高低位
if ((i & 1) == 0) {
dump_[p] = (dump_[p] & 0x0f) | (b << 4);
mask_[p] = (mask_[p] & 0x0f) | (m << 4);
} else {
dump_[p] = (dump_[p] & 0xf0) | (b & 0x0f);
mask_[p] = (mask_[p] & 0xf0) | (m & 0x0f);
}
}
}
“`

### 水印搜索算法

“`cpp
bool Watermark::SearchByte(uint8_t value) {
if (dump_.size() == 0) return false;

bool res = false;
// 从后向前遍历所有可能的匹配位置
for (int i = (int)(pos_.size() – 1); i >= -1; i–) {
size_t p = (i == -1) ? 0 : pos_[i];

// 检查当前字节是否匹配(考虑掩码)
if ((dump_[p] & mask_[p]) == (value & mask_[p])) {
p++;
if (p == dump_.size()) {
// 完整匹配
res = true;
if (i > -1) pos_.erase(pos_.begin() + i);
} else if (i == -1) {
// 新匹配开始
pos_.push_back(p);
} else {
// 继续匹配
pos_[i] = p;
}
} else if (i > -1) {
// 匹配失败,移除该位置
pos_.erase(pos_.begin() + i);
}
}
return res;
}
“`

## 2. Base64 编解码实现

### Base64 编码

“`cpp
std::string VectorToBase64(const std::vector<uint8_t> &src) {
std::string dst;

if (!src.empty()) {
// 计算输出缓冲区大小
size_t dst_len = Base64EncodeGetRequiredLength(src.size());
dst.resize(dst_len);

// 执行编码
Base64Encode(&src[0], src.size(), &dst[0], dst_len);

// 调整实际大小
if (dst_len != dst.size())
dst.resize(dst_len);
}
return dst;
}
“`

### Base64 解码

“`cpp
void Base64ToVector(const char *src, size_t src_len, std::vector<uint8_t> &dst) {
if (!src || !src_len) {
dst.clear();
return;
}

size_t dst_len = src_len;
dst.resize(dst_len, 0);

Base64Decode(src, src_len, &dst[0], dst_len);

if (dst_len != dst.size())
dst.resize(dst_len);
}
“`

## 3. RSA 加密实现

### RSA 类结构

“`cpp
class RSA {
public:
RSA();
RSA(const std::vector<uint8_t> &public_exp,
const std::vector<uint8_t> &private_exp,
const std::vector<uint8_t> &modulus);
~RSA();

bool Encrypt(Data &data);
bool Decrypt(Data &data);
bool CreateKeyPair(size_t key_length);

std::vector<uint8_t> public_exp() const;
std::vector<uint8_t> private_exp() const;
std::vector<uint8_t> modulus() const;

private:
BigNumber *private_exp_;
BigNumber *public_exp_;
BigNumber *modulus_;
};
“`

### 密钥生成

“`cpp
bool RSA::CreateKeyPair(size_t key_length) {
// 使用 OpenSSL 或原生实现生成 RSA 密钥对
// 1. 选择两个大素数 p 和 q
// 2. 计算 n = p * q
// 3. 计算 φ(n) = (p-1) * (q-1)
// 4. 选择公钥指数 e(通常为 65537)
// 5. 计算私钥指数 d,使得 (d * e) % φ(n) = 1
// 6. 公钥为 (e, n),私钥为 (d, n)
}
“`

### 加密解密

“`cpp
bool RSA::Encrypt(Data &data) {
// 使用公钥加密
// ciphertext = plaintext^e mod n
}

bool RSA::Decrypt(Data &data) {
// 使用私钥解密
// plaintext = ciphertext^d mod n
}
“`

## 4. 许可证日期处理

### LicenseDate 类

“`cpp
struct LicenseDate {
uint16_t Year;
uint8_t Month;
uint8_t Day;

// 从整数构造
LicenseDate(uint32_t value = 0) {
Day = value & 0xff;
Month = (value >> 8) & 0xff;
Year = (value >> 16) & 0xffff;
}

// 从年月日构造
LicenseDate(uint16_t year, uint8_t month, uint8_t day)
: Year(year), Month(month), Day(day) {}

// 转换为整数
uint32_t value() const {
return (Year << 16) | (Month << 8) | Day;
}
};
“`

## 5. 项目选项处理

### 选项检查

“`cpp
// 检查是否启用特定保护选项
bool Core::IsOptionEnabled(ProjectOption option) {
return (options_ & option) != 0;
}

// 设置保护选项
void Core::SetOption(ProjectOption option, bool enabled) {
if (enabled)
options_ |= option;
else
options_ &= ~option;
}

// 获取最大保护选项
uint32_t GetMaximumProtection() {
return cpCryptValues | cpRunnerCRC | cpEncryptRegs |
cpPack | cpImportProtection | cpMemoryProtection |
cpResourceProtection | cpStripDebugInfo;
}
“`

## 6. 核心编译流程

### 编译步骤

“`cpp
bool Core::Compile() {
// 1. 准备阶段
if (!Prepare()) return false;

// 2. 分析目标文件
if (!Analyze()) return false;

// 3. 处理每个需要保护的函数
for (auto &func : functions_to_protect_) {
// 3.1 反汇编函数
if (!DisassembleFunction(func)) return false;

// 3.2 分析控制流
if (!AnalyzeControlFlow(func)) return false;

// 3.3 转换为虚拟指令
if (!ConvertToVM(func)) return false;

// 3.4 生成保护代码
if (!GenerateProtectedCode(func)) return false;
}

// 4. 处理导入表
if (IsOptionEnabled(cpImportProtection)) {
if (!ProtectImports()) return false;
}

// 5. 处理资源
if (IsOptionEnabled(cpResourceProtection)) {
if (!ProtectResources()) return false;
}

// 6. 压缩
if (IsOptionEnabled(cpPack)) {
if (!Pack()) return false;
}

// 7. 生成输出文件
if (!GenerateOutput()) return false;

return true;
}
“`

## 7. 文件格式检测

### 自动检测文件类型

“`cpp
IFile *Core::DetectFileType(const char *filename) {
FILE *file = fopen(filename, “rb”);
if (!file) return nullptr;

// 读取魔数
uint8_t magic[4];
fread(magic, 1, 4, file);
fclose(file);

// 检测 PE (MZ)
if (magic[0] == ‘M’ && magic[1] == ‘Z’) {
return new PEFile(filename);
}

// 检测 ELF (0x7f ELF)
if (magic[0] == 0x7f && magic[1] == ‘E’ &&
magic[2] == ‘L’ && magic[3] == ‘F’) {
return new ELFFile(filename);
}

// 检测 Mach-O
uint32_t macho_magic = *(uint32_t*)magic;
if (macho_magic == MH_MAGIC || macho_magic == MH_MAGIC_64 ||
macho_magic == MH_CIGAM || macho_magic == MH_CIGAM_64) {
return new MacFile(filename);
}

// 检测 .NET
// 需要进一步检查 PE 头中的 COM 描述符

return nullptr;
}
“`

## 8. 内存管理

### 内存分配器

“`cpp
class MemoryManager {
public:
// 分配内存
uint64_t Allocate(size_t size, uint32_t memory_type);

// 释放内存
void Free(uint64_t address, size_t size);

// 查找空闲块
MemoryBlock *FindFreeBlock(size_t size);

// 合并相邻空闲块
void MergeFreeBlocks();

private:
std::vector<MemoryBlock> allocated_blocks_;
std::vector<MemoryBlock> free_blocks_;
uint64_t base_address_;
uint64_t current_address_;
};
“`

### 内存块结构

“`cpp
struct MemoryBlock {
uint64_t address;
size_t size;
uint32_t memory_type; // mtReadable | mtWritable | mtExecutable
bool is_free;
};
“`

## 9. 重定位处理

### 重定位类型

“`cpp
enum RelocationType {
rtAbsolute, // 绝对地址
rtHighLow, // 高/低 16位
rtDir64, // 64位直接地址
rtRel32, // 32位相对地址
rtThumbBranch, // Thumb 分支
rtArmBranch, // ARM 分支
};
“`

### 重定位应用

“`cpp
bool ApplyRelocation(IRelocation *reloc, uint64_t delta_base) {
uint64_t target_address = reloc->target_address();
uint64_t new_address = target_address + delta_base;

switch (reloc->type()) {
case rtAbsolute:
WriteAddress(reloc->address(), new_address, reloc->size());
break;
case rtRel32:
// 相对地址需要重新计算偏移
{
int32_t new_offset = (int32_t)(new_address – reloc->address() – reloc->size());
WriteDWord(reloc->address(), new_offset);
}
break;
// … 其他类型
}
return true;
}
“`

## 10. 进度报告

### 进度回调

“`cpp
class IProgress {
public:
virtual void BeginTask(const char *name, uint64_t total) = 0;
virtual void SetProgress(uint64_t current) = 0;
virtual void EndTask() = 0;
virtual bool IsCancelled() = 0;
};

// 使用示例
void Core::StepProgress(uint64_t step) {
if (progress_) {
progress_->SetProgress(current_progress_ + step);
if (progress_->IsCancelled()) {
throw std::runtime_error(“Operation cancelled”);
}
}
}
“`

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容