使用ZwMapViewOfSection创建内存映射文件总结

标 题: 【原创】使用ZwMapViewOfSection创建内存映射文件总结
作 者: 小覃
时 间: 2012-06-15,02:28:36
链 接: http://bbs.pediy.com/showthread.php?t=152144

在写驱动搜索内核模块内存时,你是不是也经常会遇到BSOD?
原因是内核模块INIT节调用完成后就取消了映射。
    解决这个问题鄙人的方法是,
自己来映射该内核模块文件内存进行内存操作。
我们使用ZwQuerySystemInformation遍历枚举模块,
得到模块名后使用ZwMapViewOfSection映射内存。

代码:
#define SEC_IMAGE 0x01000000
void* MapFileBaseAddress = NULL;
HANDLE  hFile = NULL;
HANDLE  hSection = NULL; 

/** 内存映射文件,返回基址:
*/
void* CreateMapFileAndGetBaseAddr(
  PUNICODE_STRING pDriverName
  )

{
  //HANDLE  hFile;
  //HANDLE  hSection; 
  NTSTATUS status;
  SIZE_T size = 0;
  IO_STATUS_BLOCK io_status = {0};
  OBJECT_ATTRIBUTES oa = {0};

  InitializeObjectAttributes(
    &oa,
  pDriverName,
    OBJ_CASE_INSENSITIVE,
    0,
    0
    );

status = ZwOpenFile(&hFile, 
       FILE_EXECUTE | SYNCHRONIZE, 
       &oa,
       &io_status, 
       FILE_SHARE_READ, 
       FILE_SYNCHRONOUS_IO_NONALERT);
if(!NT_SUCCESS(status))
        {
                DbgPrint("ZwOpenFile failed
");
                return NULL;
        }
 oa.ObjectName = 0;

status = ZwCreateSection(&hSection,
        SECTION_ALL_ACCESS,
        &oa,
        0,
        PAGE_EXECUTE, 
        SEC_IMAGE, 
        hFile);
if(!NT_SUCCESS(status))
        {
                DbgPrint("ZwCreateSection failed
");
        hFile = NULL;
        ZwClose(hFile);
                return NULL;
        }

status = ZwMapViewOfSection(hSection,
           PsGetCurrentProcessId(),
           &MapFileBaseAddress, 
           0, 
           1024,
           0, 
           &size,
           ViewShare,
           MEM_TOP_DOWN, 
           PAGE_READWRITE); 
if(!NT_SUCCESS(status))
        {
                DbgPrint("ZwMapViewOfSection failed
");
        hSection = NULL;
        ZwClose(hSection);
        hFile = NULL;
        ZwClose(hFile);
                return NULL;
        }
    
return MapFileBaseAddress;
}


调用方法映射文件返回映射后基址,

代码:

PVOID BaseAddress = NULL;
UNICODE_STRING driverName;
......

RtlInitUnicodeString( &driverName, L"\??\C:\Documents and Settings\Administrator\桌面\111.sys" );
BaseAddress = CreateMapFileAndGetBaseAddr(&driverName);
DbgPrint( "MapFile Return Address:%X
", BaseAddress );


释放清理:

if( NULL != hFile )
  ZwClose(hFile);
if( NULL != hSection )
  ZwClose(hSection);
代码仅供参考!
PsGetCurrentProcessId()
也可以用NtCurrentProcess()代替。

以上代码在XPSP3 DDK下测试通过!*转载请注明来自看雪论坛@PEdiy.com
jpg 改 rar
原文地址:https://www.cnblogs.com/kuangke/p/6259371.html