内存进程读写可以让我们访问其他进程的内存空间并读取或修改其中的数据。这种技术通常用于各种调试工具、进程监控工具和反作弊系统等场景。在Windows
系统中,内存进程读写可以通过一些API
函数来实现,如OpenProcess
、ReadProcessMemory
和WriteProcessMemory
等。这些函数提供了一种通用的方式来访问其他进程的内存,并且可以用来读取或写入不同类型的数据,例如整数、字节集、浮点数等。
在开始编写内存读者功能之前我们先来实现一个获取特定进程内特定模块基址的功能,该功能的实现分为两部分首先我们封装一个GetProcessModuleHandle
函数,该函数用户可传入一个进程PID
以及需要获取的进程内的模块名,此时会通过循环的方式找到所需返回的模块并返回该模块的moduleEntry.hModule
基址,由于使用了进程快照函数所以在使用时需要引入TlHelp32.h
库。
HMODULE GetProcessModuleHandle(DWORD pid, CONST TCHAR* moduleName) { MODULEENTRY32 moduleEntry; HANDLE handle = NULL;
handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); if (!handle) { CloseHandle(handle); return NULL; } ZeroMemory(&moduleEntry, sizeof(MODULEENTRY32)); moduleEntry.dwSize = sizeof(MODULEENTRY32); if (!Module32First(handle, &moduleEntry)) { CloseHandle(handle); return NULL; } do { if (_tcscmp(moduleEntry.szModule, moduleName) == 0) { return moduleEntry.hModule; } } while (Module32Next(handle, &moduleEntry));
CloseHandle(handle); return 0; }
|
有了上述读取模块基址的函数,接着就是要封装实现GetProcessModuleBase
函数,该函数接收两个参数,分别是进程名以及模块名,并返回该模块在指定进程中的句柄。如果指定的模块名称不存在于所给进程的模块列表中,函数会返回NULL。
DWORD GetProcessModuleBase(string ExeName, string DllName) { HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 process = { sizeof(PROCESSENTRY32) };
while (Process32Next(hProcessSnap, &process)) { string s_szExeFile = process.szExeFile; if (s_szExeFile == ExeName) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID); if (hProcess != NULL) { return (DWORD)GetProcessModuleHandle(process.th32ProcessID, DllName.c_str()); } } } return 0; }
|
参数说明:
- hProcess:指定进程的句柄,通常可以通过OpenProcess函数获取。
- lpModuleName:要获取的模块名称,可以是一个字符串形式的模块名称或者指向模块名称字符串的指针。
当有了上述两个模块的支持那么实现进程模块基址的读取将变得非常容易实现,如下是一段读取模块句柄的代码示例,在代码中我们分别读取了Tutorial-i386.exe
自身模块基地址,以及该进程内user32.dll
模块基址,需要注意的是运行该程序需要使用管理员身份。
int main(int argc, char *argv[]) { DWORD DllBase = GetProcessModuleBase("Tutorial-i386.exe", "Tutorial-i386.exe"); if (DllBase != 0) { std::cout << "模块基地址: " << hex << DllBase + 0x256650 << std::endl; }
DWORD User32 = GetProcessModuleBase("Tutorial-i386.exe", "user32.dll"); if (User32 != 0) { std::cout << "模块基地址: " << hex << User32 << std::endl; }
system("pause"); return 0; }
|
运行上述代码片段,读者可看到如下输出结果,代码中分别读取了一个进程基址,与系统模块基址。
接着我们讲解一下内存读写的实现方法,此处的读写分为32位与64位实现,在32位进程读写时可以使用微软提供的ReadProcessMemory
读及WriteProcessMemory
写入,这两个函数在参数传递上并没有太大的差异。
ReadProcessMemory 函数用于从指定进程中读取指定内存地址的数据,写入一个缓冲区中。函数接受的参数包括要读取的进程句柄,要读取的内存地址,要读取的数据大小等。如果读取成功,函数会返回非零值。
BOOL WINAPI ReadProcessMemory( HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead );
|
WriteProcessMemory 函数用于向指定进程中写入数据,写入一个缓冲区中的数据到另一个进程指定的内存地址中。函数接受的参数包括要写入的进程句柄,要写入的内存地址,要写入的数据大小等。如果写入成功,函数会返回非零值。
BOOL WINAPI WriteProcessMemory( HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten );
|
在使用 ReadProcessMemory()
和 WriteProcessMemory()
函数时,需要以管理员身份运行程序。此外,为了访问其他进程的内存,还需要指定合适的访问权限,并且需要根据具体情况指定正确的内存地址和数据类型。
BOOL ReadMemory(DWORD dwID, LPCVOID lpAddress, DWORD* pRead) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwID); if (INVALID_HANDLE_VALUE == hProcess) { return FALSE; } DWORD dwTemp = 0; ReadProcessMemory(hProcess, lpAddress, (LPVOID)(pRead), 4, &dwTemp); if (4 != dwTemp) { return FALSE; } return TRUE; }
BOOL WriteMemory(DWORD dwID, LPVOID lpAddress, DWORD dwWrite) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwID); if (INVALID_HANDLE_VALUE == hProcess) { return FALSE; } DWORD dwTemp = 0; WriteProcessMemory(hProcess, lpAddress, (LPVOID)(&dwWrite), 4, &dwTemp); if (4 != dwTemp) { return FALSE; } return TRUE; }
DWORD Read(DWORD dwPID, std::string strAddress) { LPCVOID lpAddress = (LPCVOID)::strtol(strAddress.c_str(), NULL, 16); DWORD dwRead = 0;
BOOL ref = ReadMemory(dwPID, lpAddress, &dwRead); if (ref == TRUE) { return dwRead; } return FALSE; }
BOOL Write(DWORD dwPID, std::string strAddress, std::string write_value) { LPVOID lpAddress = (LPVOID)::strtol(strAddress.c_str(), NULL, 16); DWORD dwWrite = ::strtol(write_value.c_str(), NULL, 16); BOOL bRet = WriteMemory(dwPID, lpAddress, dwWrite); if (bRet == TRUE) { return TRUE; } return FALSE; }
|
而如果读者使用的是64位环境,那么内存读写则需要借助于NtWow64ReadVirtualMemory64
以及NtWow64WriteVirtualMemory64
这两个未公开函数实现。
NtWow64ReadVirtualMemory64
和 NtWow64WriteVirtualMemory64
函数用于在 64
位 Windows
系统中的 32
位进程中读写虚拟内存。这两个函数通常不直接由应用程序调用,而是由系统的函数库和其他底层代码使用。
NtWow64ReadVirtualMemory64 函数的原型为:
NTSTATUS NTAPI NtWow64ReadVirtualMemory64(HANDLE ProcessHandle, PVOID64 BaseAddress, PVOID Buffer, ULONG64 Size, PULONG64 NumberOfBytesRead);
|
该函数接受五个参数:
- ProcessHandle: 进程的句柄。用于指定要读取内存的进程。
- BaseAddress: 要读取的起始地址。
- Buffer: 读取的数据存储在这个缓冲区中。
- Size: 要读取的字节数量。
- NumberOfBytesRead: 实际读取的字节数量。
NtWow64WriteVirtualMemory64 函数的原型为:
NTSTATUS NTAPI NtWow64WriteVirtualMemory64(HANDLE ProcessHandle, PVOID64 BaseAddress, PVOID Buffer, ULONG64 Size, PULONG64 NumberOfBytesWritten);
|
该函数同样接受五个参数:
- ProcessHandle: 进程的句柄。指定要写入内存的进程。
- BaseAddress: 要写入的起始地址。
- Buffer: 要写入的数据存储在这个缓冲区中。
- Size: 要写入的字节数量。
- NumberOfBytesWritten: 实际写入的字节数量。
上述这两个函数都位于ntdll.dll
库中,在使用时需要通过LoadLibrary
函数获取到该动态链接库的模块句柄,并在该内存中使用GetProcAddress
函数动态得到上述两个函数的基地址,有了基址就可以使用函数指针的方式动态的引用内存读写功能,如下则是一个完整的读写使用案例。
BOOL ReadMemory(DWORD dwID, PVOID64 lpAddress, DWORD* pRead) { HANDLE hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwID); if (INVALID_HANDLE_VALUE == hProcess) { return FALSE; }
typedef void* POINTER_64 PVOID64; typedef NTSTATUS(__stdcall* NTWOW64READVIRTUALMEMORY64)(HANDLE ProcessHandle, PVOID64 BaseAddress, PVOID Buffer, DWORD64 BufferSize, PDWORD64 NumberOfBytesRead); NTWOW64READVIRTUALMEMORY64 pNtWow64ReadVirtualMemory64 = NULL;
HMODULE hModule = ::LoadLibrary("ntdll.dll"); if (NULL == hModule) { return FALSE; }
pNtWow64ReadVirtualMemory64 = (NTWOW64READVIRTUALMEMORY64)::GetProcAddress(hModule, "NtWow64ReadVirtualMemory64"); if (NULL == pNtWow64ReadVirtualMemory64) { return FALSE; }
DWORD64 dwTemp = (DWORD64)0;
pNtWow64ReadVirtualMemory64(hProcess, (PVOID64)lpAddress, (LPVOID)(pRead), 4, &dwTemp); FreeLibrary(hModule); if (4 != dwTemp) { return FALSE; } return TRUE; }
BOOL WriteMemory(DWORD dwID, PVOID64 lpAddress, DWORD* pWrite) { HANDLE hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwID); if (INVALID_HANDLE_VALUE == hProcess) { return FALSE; }
typedef void* POINTER_64 PVOID64; typedef NTSTATUS(__stdcall* NTWOW64WRITEVIRTUALMEMORY64)(HANDLE ProcessHandle, PVOID64 BaseAddress, PVOID Buffer, DWORD64 BufferSize, PDWORD64 NumberOfBytesRead); NTWOW64WRITEVIRTUALMEMORY64 pNtWow64WriteVirtualMemory64 = NULL;
HMODULE hModule = ::LoadLibrary("ntdll.dll"); if (NULL == hModule) { return FALSE; }
pNtWow64WriteVirtualMemory64 = (NTWOW64WRITEVIRTUALMEMORY64)::GetProcAddress(hModule, "NtWow64WriteVirtualMemory64"); if (NULL == pNtWow64WriteVirtualMemory64) { return FALSE; }
DWORD64 dwTemp = (DWORD64)0;
pNtWow64WriteVirtualMemory64(hProcess, (PVOID64)lpAddress, (pWrite), 4, &dwTemp); ::FreeLibrary(hModule); if (4 != dwTemp) { return FALSE; } return TRUE; }
DWORD Read(DWORD dwPID, std::string strAddress) { typedef void* POINTER_64 PVOID64; PVOID64 lpAddress = (PVOID64)::_strtoi64_l(strAddress.c_str(), NULL, 16, NULL);
DWORD dwRead = 0; BOOL ref = ReadMemory(dwPID, lpAddress, &dwRead);
if (ref == TRUE) { return dwRead; } return FALSE; }
BOOL Write(DWORD dwPID, std::string strAddress, DWORD write_value) { typedef void* POINTER_64 PVOID64; PVOID64 lpAddress = (PVOID64)::_strtoi64_l(strAddress.c_str(), NULL, 16, NULL); BOOL bRet = WriteMemory(dwPID, lpAddress, &write_value); if (bRet) { return TRUE; } return FALSE; }
|
上述代码的使用非常容易,调用内存写入时只需要传入进程PID,写入的内存地址,和写入的数据长度即可,如下所示则是实现调用的案例。
int main(int argc, char *argv[]) { DWORD Pid = 13564;
BOOL write_flag = Write(Pid, "0x00151F38", "9999"); printf("[内存写入] 状态 = %d \n", write_flag);
DWORD read_byte = Read(Pid, "0x00151F38"); printf("[内存读取] 数据 = %d \n", read_byte);
system("pause"); return 0; }
|
内存读写输出效果如下图所示;
我们以32
位为例对上述函数进行整合封装,实现一个通用的内存读写,通过使用template
模板机制封装ReadMemory
内存读取,WriteMemory
内存写入,这些函数在调用时支持读写,内存整数型,短整数,浮点数,字节,字节集等,同时还封装实现FindPattern
函数用于实现对特定内存的特征匹配,读者在编写进程读写时可以直接使用这些函数案例,完整代码如下所示;
#include <Windows.h> #include <iostream> #include <TlHelp32.h>
HANDLE GetProcessHandle(DWORD pid) { return OpenProcess(PROCESS_ALL_ACCESS, 0, pid); }
DWORD GetProcessIdByHwnd(DWORD hWnd) { DWORD pid; GetWindowThreadProcessId((HWND)hWnd, &pid); return pid; }
DWORD GetProcessIdByName(LPCTSTR name) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hSnapshot) { return NULL; } PROCESSENTRY32 pe = { sizeof(pe) };
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe)) { if (lstrcmpi(pe.szExeFile, name) == 0) { CloseHandle(hSnapshot); return pe.th32ProcessID; } } CloseHandle(hSnapshot); return 0; }
DWORD GetProcessModuleHandle(DWORD pid, CONST TCHAR* moduleName) { MODULEENTRY32 moduleEntry; HANDLE handle = NULL; handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); if (!handle) { CloseHandle(handle); return NULL; }
ZeroMemory(&moduleEntry, sizeof(MODULEENTRY32)); moduleEntry.dwSize = sizeof(MODULEENTRY32); if (!Module32First(handle, &moduleEntry)) { CloseHandle(handle); return NULL; }
do { if (lstrcmpi(moduleEntry.szModule, moduleName) == 0) { return (DWORD)moduleEntry.hModule; } } while (Module32Next(handle, &moduleEntry)); CloseHandle(handle); return 0; }
template<typename T1> T1 ReadMemory(HANDLE processHandle, DWORD pAddr) { T1 result; ReadProcessMemory(processHandle, (LPCVOID)(pAddr), &result, sizeof(T1), NULL); return result; }
template<typename T1> T1* ReadMemory(HANDLE processHandle, DWORD pAddr, DWORD length) { T1* result = new T1[length]; ReadProcessMemory(processHandle, (LPCVOID)(pAddr), result, length, NULL); return result; }
template<typename T1> void WriteMemory(HANDLE processHandle, DWORD pAddr, T1 vaule) { WriteProcessMemory(processHandle, (LPVOID)(pAddr), &vaule, sizeof(T1), NULL); }
template<typename T1> void WriteMemory(HANDLE processHandle, DWORD pAddr, T1 vaule, DWORD length) { WriteProcessMemory(processHandle, (LPVOID)(pAddr), vaule, length, NULL); }
DWORD AllocMemory(HANDLE processHandle, DWORD size) { return (DWORD)VirtualAllocEx(processHandle, NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); }
BOOL FreeMemory(HANDLE processHandle, DWORD addr, DWORD size) { return VirtualFreeEx(processHandle, (LPVOID)addr, size, MEM_RELEASE); }
uintptr_t FindPattern(HANDLE processHandle, uintptr_t start, uintptr_t length, const unsigned char* pattern, const char* mask) { size_t pos = 0; auto maskLength = strlen(mask) - 1;
auto startAdress = start; for (auto it = startAdress; it < startAdress + length; ++it) { if (ReadMemory<unsigned char>(processHandle, (DWORD)it) == pattern[pos] || mask[pos] == '?') { if (mask[pos + 1] == '\0') { return it - maskLength; } pos++; } else { pos = 0; } } return 0; }
|
当我们需要读写整数或浮点数时只需要在调用特定函数时传入模板即可,我们以读取浮点数为例,在调用ReadMemory
函数时传入<FLOAT>
则代表参数传递采用浮点数模式,同理读取整数时同样可以使用<DWORD>
模板,如下代码则是实现读写整数与浮点数的案例演示。
int main(int argc, char *argv[]) { DWORD Pid = GetProcessIdByName(L"Tutorial-i386.exe"); printf("[+] 进程PID = %d \n", Pid);
HANDLE handle = GetProcessHandle(Pid); printf("[+] 进程句柄 = %X \n", handle);
WriteMemory<DWORD>(handle, 0x019C7A18, (DWORD)1000);
WriteMemory<FLOAT>(handle, 0x019CD0E8, (FLOAT)100.234);
DWORD read_dword = ReadMemory<DWORD>(handle, 0x019C7A18); printf("[*] 读内存整数型 = %d \n", read_dword);
FLOAT read_float = ReadMemory<FLOAT>(handle, 0x019CD0E8); printf("[*] 读内存浮点数 = %f \n", read_float);
system("pause"); return 0; }
|
上述代码运行后,首先会调用写入函数对内存0x19C7A18
写入1000
的整数,并对0x19CD0E8
写入100.234
的浮点数,接着会再调用ReadMemory
将这两个数读取并输出到屏幕,如下图所示;
接着我们继续实现读写内存字节集的功能,字节集的读写其原理是通过循环的方式读写字节,每次循环时内存地址递增1,并循环将列表内的参数一次性写出到进程中,在写入字节集之前需要确保该内存空间具有PAGE_EXECUTE_READWRITE
读写执行属性,如果不存在则还需要调用VirtualProtectEx
设置属性,如下所示是读写字节集的完整代码;
int main(int argc, char *argv[]) { DWORD Pid = GetProcessIdByName(L"Tutorial-i386.exe"); printf("[+] 进程PID = %d \n", Pid);
HANDLE handle = GetProcessHandle(Pid); printf("[+] 进程句柄 = %X \n", handle);
DWORD addr = 0x57E000; DWORD length = 10;
BYTE code[10] = { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 };
DWORD old_protect; if (VirtualProtectEx(handle, (LPVOID)addr, length, PAGE_EXECUTE_READWRITE, &old_protect)) { BYTE* temp = (BYTE*)addr; for (int i = 0; i < length; i++) { WriteMemory<BYTE>(handle, DWORD(temp + i), code[i]);
} } VirtualProtectEx(handle, (LPVOID)addr, length, old_protect, NULL);
BYTE read_byte = ReadMemory<BYTE>(handle, 0x57E000); printf("[byte] 读内存字节 = %02X \n", read_byte);
BYTE** read_byte_ptr = ReadMemory<BYTE *>(handle, 0x57E000, 10);
for (int x = 0; x < 10; x++) { printf("[bytes] 读[%d]字节集 = %02X \n", x, read_byte_ptr[x]); }
system("pause"); return 0; }
|
当读者运行上述代码后,会调用WriteMemory<BYTE>
向内存0x57E000
写出一段code
字节集,接着再次调用ReadMemory<BYTE *>
读取字节集并打印输出,如下图所示;
特征码搜索功能可以使用FindPattern
函数,该函数接收匹配进程的句柄,以及内存开始位置及结束位置,变量find_code
则是所需搜索的字节集列表,mask
代表字节集掩码,此处的掩码必须要与字节集列表保持一致,当搜索到特征码之后会返回当前的内存地址,放入param
变量内,如下代码;
int main(int argc, char *argv[]) { DWORD Pid = GetProcessIdByName(L"Tutorial-i386.exe"); printf("[+] 进程PID = %d \n", Pid);
HANDLE handle = GetProcessHandle(Pid); printf("[+] 进程句柄 = %X \n", handle);
DWORD module_base = GetProcessModuleHandle(Pid, L"Tutorial-i386.exe"); printf("[*] 模块句柄 = %X \n", module_base);
IMAGE_DOS_HEADER DOSHeader = ReadMemory<IMAGE_DOS_HEADER>(handle, (DWORD)module_base); printf("[+] DOS Header = %X \n", DOSHeader);
IMAGE_NT_HEADERS NTHeaders = ReadMemory<IMAGE_NT_HEADERS>(handle, DWORD(uintptr_t(module_base) + DOSHeader.e_lfanew)); printf("[+] NT Header = %X \n", NTHeaders);
BYTE find_code[10] = { 0xF0, 0x8B, 0x46, 0x08, 0xE8, 0xCF, 0xD8, 0xFF, 0xFF, 0x8B };
const char* mask = "?? ?? ?? ?? ?? ?? ?? ?? ?? ??";
uintptr_t param = FindPattern(handle, reinterpret_cast<uintptr_t>(handle)+NTHeaders.OptionalHeader.BaseOfCode, reinterpret_cast<uintptr_t>(handle)+NTHeaders.OptionalHeader.SizeOfCode, find_code, mask );
printf("param = 0x%x \n", param);
system("pause"); return 0; }
|
运行后即可搜索到PE文件内,符合条件的内存机器码,输出效果如下图所示;