首页
社区
课程
招聘
[原创] C/C++ 特征码 Sunday、SSE2、AVX 搜索
发表于: 12小时前 162

[原创] C/C++ 特征码 Sunday、SSE2、AVX 搜索

12小时前
162

自己使用的,Sunday、SSE2、AVX 搜索单独写在一个方法里,只使用一个方法,复制出来即可使用
也可下载附件使用,代码一样的

调用:

/// <summary>
/// 开发者:ご听雨づ
/// TyHijack 特征码搜索
/// </summary>
#include <windows.h>
#include <intrin.h>
#include <string>
#include <vector>
#include <Psapi.h>

/*************************************************************************************
函数名称: PatternFindEx
函数功能: 通用特征码搜索 根据CPU自动选择Sunday、SSE2、AVX2进行搜索
输入参数: resultList   保存搜索结果的集合
		  hProcess   进程句柄 HANDLE hProcess = GetCurrentProcess();
		  module     0或者NULL全进程搜索(支持堆内存),否则搜索模块 HMODULE hModule = GetModuleHandle(L"模块名称");
		  pattern    搜索特征码,支持通配符??或8?或?8 格式为:std::string pattern = "?5 ?? 77 ?8 ?? AA BB";
		  searchNum  搜索个数,0为搜索整个模块
返    回: 找到地址的集合
调    用: std::vector<ULONG_PTR> resultList; PatternFindEx(resultList,hProcess, hModule, pattern, 0);
调    用: std::vector<ULONG_PTR> resultList; SundayPatternFind(resultList,hProcess, 0x1000, 0x2000, pattern, 0);
*************************************************************************************/

// Sunday特征码搜索
inline bool SundayPatternFind(std::vector<ULONG_PTR>& resultList, HANDLE hProcess, ULONG_PTR startAddress, ULONG_PTR endAddress, std::string& pattern, int searchNum)
{
	// 进程句柄不能为空,起始地址必须小于结束地址,特征码不能为空
	if (!hProcess || startAddress > endAddress || pattern.empty())
	{
		MessageBoxA(NULL, "The input parameters are incorrect.", "Error", MB_OK);
		return false;
	}
	int index = 0;
	while ((index = pattern.find(' ', index)) >= 0) pattern.erase(index, 1); // 去除特征码所有空格
	if (pattern.length() & 1)	 // 特征码长度不能为单数
	{
		MessageBoxA(NULL, "The feature code is singular.", "Error", MB_OK);
		return false;
	}
	ULONG_PTR len = pattern.length() / 2; // 计算特征码长度
	ULONG_PTR nSundayLen = len;			  // 记录首次出现半?和??的位置
	ULONG_PTR nFirstMatch = len;		  // 跳过头部??,记录首次全码或半码位置
	BYTE* pMarkCode = new BYTE[len];	  // 存储转换后的特征码字节
	BYTE* pWildcard = new BYTE[len];	  // 存储特征字符串中??、?(??=FF、?=F、非?=0) 通配符
	BYTE* pMemBuffer = NULL;			  // 存放内存数据

	// 处理特征码字符串,转换成字节数组
	for (ULONG_PTR i = 0; i < len; i++)
	{
		std::string tmpStr = pattern.substr(i * 2, 2);
		if ("??" == tmpStr) // 是"??"的特征字符
		{
			tmpStr = "FF";
			pWildcard[i] = 0xFF;
			if (nSundayLen == len) nSundayLen = i;
		}
		else // 不是"??"的特征字符
		{
			if ('?' == tmpStr[0]) // 左半字节为'?'
			{
				tmpStr[0] = 'F';
				pWildcard[i] = (0xF << 4);
				if (nSundayLen == len) nSundayLen = i;
			}
			else if ('?' == tmpStr[1]) // 右半字节为'?'
			{
				tmpStr[1] = 'F';
				pWildcard[i] = 0xF;
				if (nSundayLen == len) nSundayLen = i;
			}
			else
			{
				pWildcard[i] = 0x0;
			}
			if (nFirstMatch == len) nFirstMatch = i;
		}
		pMarkCode[i] = strtoul(tmpStr.c_str(), nullptr, 16);
	}
	// 初始Sunday模板0x00-0xFF数组
	int Shift[0xFF + 1] = { 0 };
	for (int i = 0; i < nSundayLen; ++i)
	{
		Shift[pMarkCode[i]] = i + 1; // 记录特征码首次出现半?和??前的值
	}
	// 内存信息
	MEMORY_BASIC_INFORMATION mbi;
	while (startAddress < endAddress) // 遍历内存
	{
		// 查询内存信息失败,结束搜索
		if (VirtualQueryEx(hProcess, (void*)startAddress, &mbi, sizeof(mbi)) == 0) goto endSearchMemory;
		// 锁定范围时,对开始地址和结束地址进行修正并重新计算搜索大小
		startAddress = startAddress > (ULONG_PTR)mbi.BaseAddress ? startAddress : (ULONG_PTR)mbi.BaseAddress;
		ULONG_PTR tempEndAddress = endAddress < ((ULONG_PTR)mbi.BaseAddress + mbi.RegionSize) ? endAddress : ((ULONG_PTR)mbi.BaseAddress + mbi.RegionSize);
		ULONG_PTR endSize = mbi.RegionSize < (tempEndAddress - startAddress) ? mbi.RegionSize : (tempEndAddress - startAddress);
		// 先按内存信息判断区域是否可搜索:已提交 + 可读保护 + 非保护页/禁止访问
		// 必须在分配之前判断:全进程搜索会扫到 MEM_FREE 空洞,其 RegionSize 可达 TB 级,先分配必然 bad_alloc
		if (MEM_COMMIT != mbi.State ||
			(mbi.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_WRITECOPY)) == 0 ||
			(mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)))
		{
			startAddress = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; // 整段跳过,不申请缓冲区
			continue;
		}
		// 申请内存,存放内存数据
		if (pMemBuffer) { delete[] pMemBuffer; pMemBuffer = NULL; }
		pMemBuffer = new BYTE[endSize]();
		// 读取失败(区域被并发改保护/释放等)时缓冲区里是补的 0,不能拿去匹配
		if (ReadProcessMemory(hProcess, (void*)startAddress, pMemBuffer, endSize, nullptr))
		{
			// 区域比特征码还小,无需搜索(同时避免下面 endSize - len 无符号下溢)
			if (endSize < len) { startAddress += endSize; continue; }
			ULONG_PTR nOffset = 0; // 记录偏移量

			// Sunday模板和暴力匹配算法搜索内存
			for (ULONG_PTR m = nFirstMatch, n = nFirstMatch; m < endSize; ++m, ++n)
			{
				// 字节是"??"的通配符,不相同,跳过
				if ((pWildcard[n] != 0xFF) && ((pMemBuffer[m] | pWildcard[n]) != pMarkCode[n]))
				{
					nOffset = m - n + nSundayLen;
					if (nOffset >= endSize) break;
					// 这里将暴力匹配算法和Sunday算法结合,判断是否使用Sunday算法
					// 当头部是??、半字节时,使用暴力匹配算法,否则使用Sunday算法
					// 判断Sunday模板数组 里有没有 内存偏移后的值,有则回溯
					if (nSundayLen && Shift[pMemBuffer[nOffset]])
						m = nOffset - Shift[pMemBuffer[nOffset]] + nFirstMatch;
					else m = nOffset + nFirstMatch;
					n = nFirstMatch - 1;
				}

				if (n + 1 == len)
				{
					if ((ULONG_PTR)pMarkCode != startAddress + m - n) // 排除特征码本身
						resultList.push_back(startAddress + m - n);
					if (resultList.size() >= searchNum && searchNum != 0) goto endSearchMemory; // 限制搜索数量
					m = m - n + nFirstMatch;
					n = nFirstMatch - 1;
				}
			}
			startAddress += endSize;
		}
		else
			startAddress = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; // 读取失败,整段跳过(按区域末尾推进,避免起始地址在区域中间时漏掉下一区域开头)
	}
endSearchMemory:
	if (pMarkCode) { delete[] pMarkCode; pMarkCode = NULL; }
	if (pWildcard) { delete[] pWildcard; pWildcard = NULL; }
	if (pMemBuffer) { delete[] pMemBuffer; pMemBuffer = NULL; }
	return true;
}
// SSE2特征码搜索
inline bool SSE2PatternFind(std::vector<ULONG_PTR>& resultList, HANDLE hProcess, ULONG_PTR startAddress, ULONG_PTR endAddress, std::string& pattern, int searchNum)
{
	// 进程句柄不能为空,起始地址必须小于结束地址,特征码不能为空
	if (!hProcess || startAddress > endAddress || pattern.empty())
	{
		MessageBoxA(NULL, "The input parameters are incorrect.", "Error", MB_OK);
		return false;
	}
	int index = 0;
	while ((index = pattern.find(' ', index)) >= 0) pattern.erase(index, 1); // 去除特征码所有空格
	if (pattern.length() & 1)	 // 特征码长度不能为单数
	{
		MessageBoxA(NULL, "The feature code is singular.", "Error", MB_OK);
		return false;
	}
	ULONG_PTR len = pattern.length() / 2; // 计算特征码长度
	ULONG_PTR nSundayLen = len;			  // 记录首次出现半?和??的位置
	ULONG_PTR nFirstMatch = len;		  // 跳过头部??,记录首次全码或半码位置
	BYTE* pMarkCode = new BYTE[len];	  // 存储转换后的特征码字节
	BYTE* pWildcard = new BYTE[len];	  // 存储特征字符串中??、?(??=FF、?=F、非?=0) 通配符
	BYTE* pMemBuffer = NULL;			  // 存放内存数据

	// 处理特征码字符串,转换成字节数组
	for (ULONG_PTR i = 0; i < len; i++)
	{
		std::string tmpStr = pattern.substr(i * 2, 2);
		if ("??" == tmpStr) // 是"??"的特征字符
		{
			tmpStr = "FF";
			pWildcard[i] = 0xFF;
			if (nSundayLen == len) nSundayLen = i;
		}
		else // 不是"??"的特征字符
		{
			if ('?' == tmpStr[0]) // 左半字节为'?'
			{
				tmpStr[0] = 'F';
				pWildcard[i] = (0xF << 4);
				if (nSundayLen == len) nSundayLen = i;
			}
			else if ('?' == tmpStr[1]) // 右半字节为'?'
			{
				tmpStr[1] = 'F';
				pWildcard[i] = 0xF;
				if (nSundayLen == len) nSundayLen = i;
			}
			else
			{
				pWildcard[i] = 0x0;
			}
			if (nFirstMatch == len) nFirstMatch = i;
		}
		pMarkCode[i] = strtoul(tmpStr.c_str(), nullptr, 16);
	}
	// SSE2加速相关变量
	__m128i curHead, curCmp;
	register ULONG bitComp, idxComp;
	//  内存信息
	MEMORY_BASIC_INFORMATION mbi;
	while (startAddress < endAddress)
	{
		//  查询地址空间中内存地址的信息
		//  避免内存不连续,映射不完整发生错误
		if (VirtualQueryEx(hProcess, (void*)startAddress, &mbi, sizeof(mbi)) == 0) goto endSearchMemory;
		// 锁定范围时,对开始地址和结束地址进行修正并重新计算搜索大小
		startAddress = startAddress > (ULONG_PTR)mbi.BaseAddress ? startAddress : (ULONG_PTR)mbi.BaseAddress;
		ULONG_PTR tempEndAddress = endAddress < ((ULONG_PTR)mbi.BaseAddress + mbi.RegionSize) ? endAddress : ((ULONG_PTR)mbi.BaseAddress + mbi.RegionSize);
		ULONG_PTR endSize = mbi.RegionSize < (tempEndAddress - startAddress) ? mbi.RegionSize : (tempEndAddress - startAddress);

		// 先按内存信息判断区域是否可搜索:已提交 + 可读保护 + 非保护页/禁止访问
		// 必须在分配之前判断:全进程搜索会扫到 MEM_FREE 空洞,其 RegionSize 可达 TB 级,先分配必然 bad_alloc
		if (MEM_COMMIT != mbi.State ||
			(mbi.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_WRITECOPY)) == 0 ||
			(mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)))
		{
			startAddress = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; // 整段跳过,不申请缓冲区
			continue;
		}
		// 申请内存,存放内存数据
		if (pMemBuffer) { delete[] pMemBuffer; pMemBuffer = NULL; }
		pMemBuffer = new BYTE[endSize + 16](); // 多申请16字节,防止最后不满16,搜索不完整
		// 读取失败(区域被并发改保护/释放等)时缓冲区里是补的 0,不能拿去匹配
		if (ReadProcessMemory(hProcess, (void*)startAddress, pMemBuffer, endSize, nullptr))
		{
			// 区域比特征码还小,无需搜索(同时避免下面 endSize - len 无符号下溢)
			if (endSize < len) { startAddress += endSize; continue; }
			ULONG_PTR nOffset = 0; // 记录偏移量

			// SSE2算法搜索加速搜索
			for (ULONG_PTR i = 0; i <= endSize - len; i += 16)
			{
				ULONG cmpBit = 0xFFFFFFFF;
				for (ULONG_PTR j = 0; j < len; ++j)
				{
					if (i + j >= endSize) break;
					if (pWildcard[j] == 0xFF) continue;							   // 跳过"??"通配符
					curHead = _mm_loadu_si128((__m128i*) & pMemBuffer[i + j]);	   // 取出16字节
					curHead = _mm_or_si128(curHead, _mm_set1_epi8(pWildcard[j]));  // 将对应特征码中'?'位置替换为F
					curCmp = _mm_cmpeq_epi8(curHead, _mm_set1_epi8(pMarkCode[j])); // 比较特征码
					bitComp = _mm_movemask_epi8(curCmp);						   // 得到比对结果
					bitComp = bitComp & cmpBit;									   // 与上次比对结果取交集
					if (bitComp == 0) break;                                       // 没有匹配上
					cmpBit = bitComp;
					if (j + 1 == len) // 匹配正确
					{
						ULONG tempBitComp = bitComp;
						while (_BitScanForward(&idxComp, tempBitComp))
						{
							// 清除已处理的位不会改变其余位的下标,所以 idxComp 本身就是相对 i 的偏移
							nOffset = i + idxComp; // 内存偏移位置
							if (nOffset + len > endSize)
								break; // 特征码必须完整落在本区域内,排除尾部补 0 凑出的假匹配
							// 排除特征码本身
							if ((ULONG_PTR)pMarkCode != startAddress + nOffset)
								resultList.push_back(startAddress + nOffset);
							//  限制个数,不全部搜索
							if (resultList.size() >= searchNum && searchNum != 0) goto endSearchMemory;

							tempBitComp &= ~(1UL << idxComp); // 清除已处理的位
						}
					}
				}
			}
			startAddress += endSize;
		}
		else
			startAddress = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; // 读取失败,整段跳过(按区域末尾推进,避免起始地址在区域中间时漏掉下一区域开头)
	}
endSearchMemory:
	//  释放内存
	if (pMarkCode) { delete[] pMarkCode; pMarkCode = NULL; }
	if (pWildcard) { delete[] pWildcard; pWildcard = NULL; }
	if (pMemBuffer) { delete[] pMemBuffer; pMemBuffer = NULL; }
	return true;
}

// AVX2特征码搜索
// GCC/Clang 必须给函数加 target("avx2") 才能使用 __m256i 内建函数;
// MSVC 没有 target 属性,__m256i 内建函数本身可直接使用(/arch:AVX2 只影响自动向量化),故不添加。
#if defined(__GNUC__) || defined(__clang__)
__attribute__((target("avx2")))
#endif
inline bool AVX2PatternFind(std::vector<ULONG_PTR>& resultList, HANDLE hProcess, ULONG_PTR startAddress, ULONG_PTR endAddress, std::string& pattern, int searchNum)
{
	// 进程句柄不能为空,起始地址必须小于结束地址,特征码不能为空
	if (!hProcess || startAddress > endAddress || pattern.empty())
	{
		MessageBoxA(NULL, "The input parameters are incorrect.", "Error", MB_OK);
		return false;
	}
	int index = 0;
	while ((index = pattern.find(' ', index)) >= 0) pattern.erase(index, 1); // 去除特征码所有空格
	if (pattern.length() & 1)	 // 特征码长度不能为单数
	{
		MessageBoxA(NULL, "The feature code is singular.", "Error", MB_OK);
		return false;
	}
	ULONG_PTR len = pattern.length() / 2; // 计算特征码长度
	ULONG_PTR nSundayLen = len;			  // 记录首次出现半?和??的位置
	ULONG_PTR nFirstMatch = len;		  // 跳过头部??,记录首次全码或半码位置
	BYTE* pMarkCode = new BYTE[len];	  // 存储转换后的特征码字节
	BYTE* pWildcard = new BYTE[len];	  // 存储特征字符串中??、?(??=FF、?=F、非?=0) 通配符
	BYTE* pMemBuffer = NULL;			  // 存放内存数据

	// 处理特征码字符串,转换成字节数组
	for (ULONG_PTR i = 0; i < len; i++)
	{
		std::string tmpStr = pattern.substr(i * 2, 2);
		if ("??" == tmpStr) // 是"??"的特征字符
		{
			tmpStr = "FF";
			pWildcard[i] = 0xFF;
			if (nSundayLen == len) nSundayLen = i;
		}
		else // 不是"??"的特征字符
		{
			if ('?' == tmpStr[0]) // 左半字节为'?'
			{
				tmpStr[0] = 'F';
				pWildcard[i] = (0xF << 4);
				if (nSundayLen == len) nSundayLen = i;
			}
			else if ('?' == tmpStr[1]) // 右半字节为'?'
			{
				tmpStr[1] = 'F';
				pWildcard[i] = 0xF;
				if (nSundayLen == len) nSundayLen = i;
			}
			else
			{
				pWildcard[i] = 0x0;
			}
			if (nFirstMatch == len) nFirstMatch = i;
		}
		pMarkCode[i] = strtoul(tmpStr.c_str(), nullptr, 16);
	}
	// AVX2加速相关变量
	__m256i curHead, curCmp;
	register ULONG bitComp, idxComp;
	//  内存信息
	MEMORY_BASIC_INFORMATION mbi;
	while (startAddress < endAddress)
	{
		//  查询地址空间中内存地址的信息
		//  避免内存不连续,映射不完整发生错误
		if (VirtualQueryEx(hProcess, (void*)startAddress, &mbi, sizeof(mbi)) == 0) goto endSearchMemory;
		// 锁定范围时,对开始地址和结束地址进行修正并重新计算搜索大小
		startAddress = startAddress > (ULONG_PTR)mbi.BaseAddress ? startAddress : (ULONG_PTR)mbi.BaseAddress;
		ULONG_PTR tempEndAddress = endAddress < ((ULONG_PTR)mbi.BaseAddress + mbi.RegionSize) ? endAddress : ((ULONG_PTR)mbi.BaseAddress + mbi.RegionSize);
		ULONG_PTR endSize = mbi.RegionSize < (tempEndAddress - startAddress) ? mbi.RegionSize : (tempEndAddress - startAddress);

		// 先按内存信息判断区域是否可搜索:已提交 + 可读保护 + 非保护页/禁止访问
		// 必须在分配之前判断:全进程搜索会扫到 MEM_FREE 空洞,其 RegionSize 可达 TB 级,先分配必然 bad_alloc
		if (MEM_COMMIT != mbi.State ||
			(mbi.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_WRITECOPY)) == 0 ||
			(mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)))
		{
			startAddress = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; // 整段跳过,不申请缓冲区
			continue;
		}
		// 申请内存,存放内存数据
		if (pMemBuffer) { delete[] pMemBuffer; pMemBuffer = NULL; }
		pMemBuffer = new BYTE[endSize + 32](); // 多申请32字节,防止最后不满32,搜索不完整
		// 读取失败(区域被并发改保护/释放等)时缓冲区里是补的 0,不能拿去匹配
		if (ReadProcessMemory(hProcess, (void*)startAddress, pMemBuffer, endSize, nullptr))
		{
			// 区域比特征码还小,无需搜索(同时避免下面 endSize - len 无符号下溢)
			if (endSize < len) { startAddress += endSize; continue; }
			ULONG_PTR nOffset = 0; // 记录偏移量

			// AVX2算法搜索
			for (ULONG_PTR i = 0; i <= endSize - len; i += 32)
			{
				ULONG cmpBit = 0xFFFFFFFF;
				for (ULONG_PTR j = 0; j < len; ++j)
				{
					if (i + j >= endSize) break;
					if (pWildcard[j] == 0xFF) continue;									 // 跳过"??"通配符
					curHead = _mm256_loadu_si256((__m256i*) & pMemBuffer[i + j]);		 // 取出32字节
					curHead = _mm256_or_si256(curHead, _mm256_set1_epi8(pWildcard[j]));	 // 将对应特征码中'?'位置替换为F
					curCmp = _mm256_cmpeq_epi8(curHead, _mm256_set1_epi8(pMarkCode[j])); // 比较特征码
					bitComp = _mm256_movemask_epi8(curCmp);								 // 得到比对结果
					cmpBit = cmpBit & bitComp;											 // 与上次比对结果取交集
					if (cmpBit == 0) break;                                              // 没有匹配上

					if (j + 1 == len) // 匹配正确
					{
						ULONG tempBitComp = cmpBit;
						while (_BitScanForward(&idxComp, tempBitComp))
						{
							// 清除已处理的位不会改变其余位的下标,所以 idxComp 本身就是相对 i 的偏移,不能再累加
							nOffset = i + idxComp; // 内存偏移位置
							if (nOffset + len > endSize)
								break; // 特征码必须完整落在本区域内,排除尾部补 0 凑出的假匹配
							// 排除特征码本身
							if ((ULONG_PTR)pMarkCode != startAddress + nOffset)
								resultList.push_back(startAddress + nOffset);
							//  限制个数,不全部搜索
							if (resultList.size() >= searchNum && searchNum != 0) goto endSearchMemory;

							// 修复32位系统位操作问题:用清位代替移位,避免移位数等于32时的未定义行为(x86 上移位计数按 mod 32 生效会死循环)
							tempBitComp &= ~(1UL << idxComp); // 清除已处理的位
						}
					}
				}
			}
			startAddress += endSize;
		}
		else
			startAddress = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; // 读取失败,整段跳过(按区域末尾推进,避免起始地址在区域中间时漏掉下一区域开头)
	}
endSearchMemory:
	//  释放内存
	if (pMarkCode) { delete[] pMarkCode; pMarkCode = NULL; }
	if (pWildcard) { delete[] pWildcard; pWildcard = NULL; }
	if (pMemBuffer) { delete[] pMemBuffer; pMemBuffer = NULL; } 
	return true;
}

inline bool avx2Supported()
{
	int cpuInfo[4] = { 0 };

	// 第一步:检查 OSXSAVE (bit 27) 和 AVX (bit 28)
	__cpuid(cpuInfo, 1);
	if ((cpuInfo[2] & (1 << 27)) == 0 || (cpuInfo[2] & (1 << 28)) == 0)
		return false; // 没有 OSXSAVE 就不能调 _xgetbv

	// 第二步:检查 XCR0 的 bit1 和 bit2(OSXSAVE=1 时 _xgetbv 不会触发 #UD,无需 SEH 兜底)
	if ((_xgetbv(0) & 0x6) != 0x6) return false; // 操作系统未启用 XMM/YMM 状态保存

	// 第三步:检查 AVX2 硬件位(leaf 7 的子叶必须显式给 0,用 __cpuidex)
	__cpuid(cpuInfo, 0);
	if (cpuInfo[0] < 7) return false; // CPU 最大 basic leaf 不到 7,不可能有 AVX2
	__cpuidex(cpuInfo, 7, 0);
	return (cpuInfo[1] & (1 << 5)) != 0; // 三步全过才安全
}

// 通用特征码搜索
inline bool PatternFindEx(std::vector<ULONG_PTR>& resultList, HANDLE hProcess, HMODULE module, std::string& pattern, ULONG_PTR searchNum)
{
	int cpuInfo[4] = { 0 };
	__cpuid(cpuInfo, 1);
	bool sse2Supported = (cpuInfo[3] & (1 << 26)) != 0;

	ULONG_PTR startAddress = 0; // 起始地址
	ULONG_PTR endAddress = 0;	// 结束地址
	if (module)
	{
		MODULEINFO moduleInfo = { 0 };
		if (GetModuleInformation(hProcess, module, &moduleInfo, sizeof(moduleInfo)) == 0) return false;
		startAddress = (ULONG_PTR)moduleInfo.lpBaseOfDll;
		endAddress = startAddress + moduleInfo.SizeOfImage;
	}
	else
	{
		// 全地址搜索
		SYSTEM_INFO sysInfo = { 0 };
		GetSystemInfo(&sysInfo);
		startAddress = (ULONG_PTR)sysInfo.lpMinimumApplicationAddress;
		endAddress = (ULONG_PTR)sysInfo.lpMaximumApplicationAddress;
	}
	if (avx2Supported())
		return AVX2PatternFind(resultList, hProcess, startAddress, endAddress, pattern, searchNum);
	else if (sse2Supported)
		return SSE2PatternFind(resultList, hProcess, startAddress, endAddress, pattern, searchNum);
	else
		return SundayPatternFind(resultList, hProcess, startAddress, endAddress, pattern, searchNum);
}


调用:

#include <iostream>
#include "TyHijack.h"
int main()
{	BYTE pMemBuffer[] = { 0xD5, 0xB4, 0x67, 0x92, 0x77, 0x67, 0x92, 0x77, 0x67 , 0x67, 0x92, 0x77, 0x67,0x58, 0x58,0x67, 0x92, 0x77, 0x67 , };
	std::string pattern = "67 92 77 67";	ULONG_PTR startAddress = (ULONG_PTR)pMemBuffer; //起始地址
	ULONG_PTR endAddress = startAddress + sizeof(pMemBuffer); //结束地址

	printf("startAddress:%IX--endSize:%d\n", startAddress, sizeof(pMemBuffer));	// 调用内存搜索算法
	std::vector<ULONG_PTR> resultList;	clock_t nBeginTime = clock();	//PatternFindEx(resultList, (HANDLE)-1, 0, pattern, 0);
	//SundayPatternFind(resultList, (HANDLE)-1, startAddress, endAddress, pattern, 0);
	//SSE2PatternFind(resultList, (HANDLE)-1, startAddress, endAddress, pattern, 0);
	AVX2PatternFind(resultList, (HANDLE)-1, startAddress, endAddress, pattern, 0);
	
	printf("共搜到:%d个地址-->搜索时间:%d ms\n", resultList.size(), clock() - nBeginTime);	for (ULONG_PTR i = 0; i < resultList.size(); ++i)
	{
		printf("第%d个:%IX\n", i + 1, resultList[i]);
	}
	system("pause");	return 0;
}



冰与火的战歌:Windows内核攻防实战高级班!从零到实战,融合AI与Windows内核攻防全技术栈,打造具备自动化能力的内核开发高手。

最后于 9小时前 被wtujoxk编辑 ,原因:
上传的附件:
收藏
点赞 ・1
打赏
分享
最新回复 (2)
雪    币: 9320
活跃值: (13814)
能力值: (RANK:396 )
在线值:
发帖
回帖
粉丝
2 楼

✻ AI 导读 | 感谢楼主分享特征码搜索的三种实现和调用方式

讲了什么:在内存里按一段字节特征找位置,是外挂、调试、安全分析里常见的活。楼主把三种找法写进同一个函数:普通逐字节比对、用 CPU 一次比 16 字节的指令加速、以及更宽的指令加速,并让程序按 CPU 自动挑一种。特征码支持问号通配,可以只搜某个模块,也可以搜整个进程。

怎么看:最该看的是它怎么处理内存:先查每一段内存能不能读,能读才复制出来比对,不能读就整段跳过。这样全进程搜索时不会因为碰到巨大的空闲区域而申请内存失败。另外特征码开头是问号时,会退回逐字节比对,因为加速的前提是开头有确定的字节。

关键细节:

  • 特征码里的问号分两种:整个字节不确定,或只有半个字节不确定,两种都支持
  • 搜索前先看内存段是否已提交、是否可读,不可读的整段跳过,不申请缓冲区
  • 复制内存失败时缓冲区里是补的零,不能拿去比对,要整段跳过
  • 找到的结果会排除特征码自身所在的位置,还能限制最多返回几个

适合谁:适合做外挂、逆向或安全分析,需要在内存里定位一段字节的人;会写普通 C++、懂一点 Windows 内存概念就能看懂。

一句话:找特征码先筛可读内存再比对,能避免全进程搜索时的内存申请失败;开头有问号时别指望加速指令。

请大家认真回复,灌水回复会被删除并扣信用分,严重的会封号,详情请看版规。

AI 导读,细节以原帖为准。

最后于 8小时前 被TkBinary编辑 ,原因:
12小时前
0
游客
登录 | 注册 方可回帖
返回