通过挂钩NtCreateSection监控可执行模块

通过挂钩 NtCreateSection 监控可执行模块

在 Win32 中,我们使用 CreateFileMapping 来创建映射文件对象,函数原型如下: 

HANDLE CreateFileMapping(

    HANDLE hFile,  // handle to file to map

    LPSECURITY_ATTRIBUTES lpFileMappingAttributes, // optional security attributes

    DWORD flProtect,   // protection for mapping object

    DWORD dwMaximumSizeHigh,     // high-order 32 bits of object size 

    DWORD dwMaximumSizeLow, // low-order 32 bits of object size 

    LPCTSTR lpName     // name of file-mapping object

   );

这个函数会调用 Native Api(Ntdll.dll) 中的 ZwCreateSection ( NtCreateSection )函数,而后者又通过系统调用 Ntoskrnl.exe 中的 NtCreateSection 函数,其函数原型如下:  

NTSTATUS

  NtCreateSection(

    OUT PHANDLE  SectionHandle ,

    IN ACCESS_MASK  DesiredAccess ,

    IN POBJECT_ATTRIBUTES  ObjectAttributes OPTIONAL,

    IN PLARGE_INTEGER  MaximumSize OPTIONAL,

    IN ULONG  SectionPageProtection ,

    IN ULONG  AllocationAttributes ,

    IN HANDLE  FileHandle OPTIONAL

    );

不仅是用户创建的映射文件, Windows 加载所有的可执行模块,包括 EXE 文件、 DLL 文件等都使用了此函数(博文《使用 Native Api 创建进程》就曾调用),只是在参数 SectionPageProtection 和 AllocationAttributes 与普通的映射文件有所区别:

 

根据这个特点,我们可以通过挂钩 NtCreateSection 函数来截获所有将要加载的可执行模块的文件名称(关于如何获取文件名称,可以参看博文《获取文件对象的名称》)反馈给用户。用户根据文件路径、文件的 MD5 或其他信息来判断是否允许该模块的加载。

(AllocationAttributes == 0X1000000) && (SectionPageProtection & PAGE_EXECUTE)

  参考文章:

1. Hooking the native API and controlling process creation on a system-wide basis

( http://www.codeproject.com/KB/system/soviet_protector.aspx )

2. 天书夜读

原文地址:https://www.cnblogs.com/vcerror/p/4289176.html