MmCopyVirtualMemory读写进程内存
2023-11-16
229
0
csdn《微软技术分享》原文转载分享:https://lyshark.blog.csdn.net/
内核中读写内存的方式有很多,典型的读写方式有
- CR3读写
- MDL读写,
- 内存拷贝实现读写
拷贝读写的核心是使用MmCopyVirtualMemory这个内核API函数实现,通过调用该函数即可很容易的实现内存的拷贝读写。
MmCopyVirtualMemory是Windows内核中一个非常有用的函数,它可以在用户空间和内核空间之间实现内存数据的拷贝。这个函数通过复制内存页表并更新它们来实现拷贝,从而实现了高效的内存拷贝操作。使用MmCopyVirtualMemory可以省去手动复制内存所需的许多繁琐工作,提高代码效率和稳定性。
我们对MmCopyVirtualMemory进行二次封装可以得到如下:
#include <ntifs.h>
#include <windef.h>
#include <stdlib.h>
NTKERNELAPI NTSTATUS PsLookupProcessByProcessId(HANDLE ProcessId, PEPROCESS *Process);
NTKERNELAPI CHAR* PsGetProcessImageFileName(PEPROCESS Process);
NTSTATUS NTAPI MmCopyVirtualMemory(PEPROCESS SourceProcess, PVOID SourceAddress, PEPROCESS TargetProcess, PVOID TargetAddress, SIZE_T BufferSize, KPROCESSOR_MODE PreviousMode, PSIZE_T ReturnSize);
// 定义全局EProcess结构
PEPROCESS Global_Peprocess = NULL;
// 普通Ke内存读取
NTSTATUS KeReadProcessMemory(PVOID SourceAddress, PVOID TargetAddress, SIZE_T Size)
{
__try
{
PEPROCESS TargetProcess = PsGetCurrentProcess();
SIZE_T Result;
if (NT_SUCCESS(MmCopyVirtualMemory(Global_Peprocess, SourceAddress, TargetProcess, TargetAddress, Size, KernelMode, &Result)))
return STATUS_SUCCESS;
else
return STATUS_ACCESS_DENIED;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return STATUS_ACCESS_DENIED;
}
return STATUS_ACCESS_DENIED;
}
// 普通Ke内存写入
NTSTATUS KeWriteProcessMemory(PVOID SourceAddress, PVOID TargetAddress, SIZE_T Size)
{
PEPROCESS SourceProcess = PsGetCurrentProcess();
PEPROCESS TargetProcess = Global_Peprocess;
SIZE_T Result;
if (NT_SUCCESS(MmCopyVirtualMemory(SourceProcess, SourceAddress, TargetProcess, TargetAddress, Size, KernelMode, &Result)))
return STATUS_SUCCESS;
else
return STATUS_ACCESS_DENIED;
}
VOID UnDriver(PDRIVER_OBJECT driver)
{
DbgPrint("Uninstall Driver Is OK \n");
}
NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
DbgPrint("hello lyshark \n");
// 根据PID打开进程
DWORD PID = 6672;
NTSTATUS nt = PsLookupProcessByProcessId((HANDLE)PID, &Global_Peprocess);
DWORD ref_value = 0;
// 将地址处读取4字节到ref_value中
NTSTATUS read_nt = KeReadProcessMemory((PVOID)0x0009EDC8, &ref_value, 4);
DbgPrint("读出数据: %d \n", ref_value);
{
// 根据PID打开进程
DWORD PID = 6672;
NTSTATUS nt = PsLookupProcessByProcessId((HANDLE)PID, &Global_Peprocess);
DWORD ref_value = 10;
// 将地址处写出4字节
NTSTATUS read_nt = KeWriteProcessMemory((PVOID)0x0009EDC8, &ref_value, 4);
DbgPrint("写入数据: %d \n", ref_value);
}
Driver->DriverUnload = UnDriver;
return STATUS_SUCCESS;
}