#include <iostream>
#include <vector>
using namespace std;
typedef struct __MemRleace
{
byte souce[256];
int in_len;
byte out[256];
int out_len;
}MemRplace;
//提权
bool EnableDebugPrivilege()
{
HANDLE hToken;
LUID sedebugnameValue;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
return FALSE;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue))
{
CloseHandle(hToken);
return false;
}
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = sedebugnameValue;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL))
{
CloseHandle(hToken);
return false;
}
return true;
}
#include <tlhelp32.h>
DWORD FindProcessByName(char* Name)
{
PROCESSENTRY32 PP;
PP.dwSize = sizeof(PROCESSENTRY32);
HANDLE H_p = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (H_p == INVALID_HANDLE_VALUE)
{
return 0;
// printf("erro");
}
BOOL ret = ::Process32First(H_p, &PP);
while (ret)
{
if (strnicmp(Name, PP.szExeFile, strlen(Name)) == NULL)
{
::CloseHandle(H_p);
return PP.th32ProcessID;
}
ret = Process32Next(H_p, &PP);
}
::CloseHandle(H_p);
return 0;
}
void FindMemory(DWORD pid, vector<MemRplace>& src)
{
int findcount =0;
MEMORY_BASIC_INFORMATION mbi;
DWORD memoryAddress = 0;
BYTE *dataBuffer = NULL;
BOOL readReturn = 0;
HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
while (VirtualQueryEx(pHandle, (LPVOID)memoryAddress, &mbi, sizeof(mbi)))
{
if (mbi.Type == MEM_PRIVATE && mbi.Protect != PAGE_EXECUTE && mbi.Protect != PAGE_NOACCESS && mbi.Protect != 128)
{
dataBuffer = new BYTE[mbi.RegionSize];
memset(dataBuffer, 0, mbi.RegionSize);
readReturn = ReadProcessMemory(pHandle, (LPVOID)memoryAddress, dataBuffer, mbi.RegionSize, 0);
if (readReturn != 0)
{
for (int i = 0; i< mbi.RegionSize; i++)
{
for each (auto var in src)
{
if (i+var.in_len<mbi.RegionSize)
{
if (memcmp(dataBuffer + i, var.souce, var.in_len) == 0)
{
DWORD ol;
//WriteProcessMemory(pHandle, (LPVOID)(memoryAddress+ i), var.out, var.out_len, &ol);
findcount++;
printf("地址:%x 找到:%d %S size:%d\r\n", memoryAddress + i ,findcount, (WCHAR*)(dataBuffer + i),var.in_len);
break;
}
}
}
}
}
else
{
}
delete[]dataBuffer;
}
memoryAddress = memoryAddress + mbi.RegionSize;
}
CloseHandle(pHandle);
}
void add_WCHAR_code(vector<MemRplace>&src, WCHAR* code,WCHAR* writecode)
{
//编译器若是多字节 sizeof wchar的大小不同
WCHAR* ZZ = L"1";
int sizexor = wcslen(ZZ) == 1?sizeof(WCHAR):1;
MemRleace xx;
memcpy(xx.souce, code, wcslen(code));
xx.in_len = wcslen(code)*sizexor;
memcpy(xx.out, writecode, wcslen(writecode));
xx.out_len = wcslen(writecode);
src.push_back(xx);
}
int main()
{
EnableDebugPrivilege();
DWORD pid = FindProcessByName("services");
if (pid !=0)
{
vector<MemRplace> FindArray;
add_WCHAR_code(FindArray, L"VMware 物理磁盘助手服务", L"1");
add_WCHAR_code(FindArray, L"VM", L"1");
FindMemory(pid, FindArray);
getchar();
}
}