驅動開發:核心監控FileObject檔案回撥

2022-10-28 12:03:05

本篇文章與上一篇文章《驅動開發:核心註冊並監控物件回撥》所使用的方式是一樣的都是使用ObRegisterCallbacks註冊回撥事件,只不過上一篇博文中LyShark將回撥結構體OB_OPERATION_REGISTRATION中的ObjectType填充為了PsProcessTypePsThreadType格式從而實現監控程序與執行緒,本章我們需要將該結構填充為IoFileObjectType以此來實現對檔案的監控,檔案過濾驅動不僅僅可以用來監控檔案的開啟,還可以用它實現對檔案的保護,一旦驅動載入則檔案是不可被刪除和改動的。

與程序執行緒回撥有少許的不同,檔案回撥需要開啟驅動的TypeInfo.SupportsObjectCallbacks開關,並定義一些微軟結構,如下是我們所需要的公開結構體,可在微軟官方或WinDBG中獲取到最新的,將其儲存為lyshark.h方便後期參照。

// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]
#include <ntddk.h>
#include <ntstrsafe.h>

typedef struct _CALLBACK_ENTRY
{
	LIST_ENTRY CallbackList;
	OB_OPERATION  Operations;
	ULONG Active;
	PVOID Handle;
	POBJECT_TYPE ObjectType;
	POB_PRE_OPERATION_CALLBACK  PreOperation;
	POB_POST_OPERATION_CALLBACK PostOperation;
	ULONG unknown;
} CALLBACK_ENTRY, *PCALLBACK_ENTRY;

typedef struct _LDR_DATA                         // 24 elements, 0xE0 bytes (sizeof)
{
	/*0x000*/     struct _LIST_ENTRY InLoadOrderLinks;                     // 2 elements, 0x10 bytes (sizeof)
	/*0x010*/     struct _LIST_ENTRY InMemoryOrderLinks;                   // 2 elements, 0x10 bytes (sizeof)
	/*0x020*/     struct _LIST_ENTRY InInitializationOrderLinks;           // 2 elements, 0x10 bytes (sizeof)
	/*0x030*/     VOID*        DllBase;
	/*0x038*/     VOID*        EntryPoint;
	/*0x040*/     ULONG32      SizeOfImage;
	/*0x044*/     UINT8        _PADDING0_[0x4];
	/*0x048*/     struct _UNICODE_STRING FullDllName;                      // 3 elements, 0x10 bytes (sizeof)
	/*0x058*/     struct _UNICODE_STRING BaseDllName;                      // 3 elements, 0x10 bytes (sizeof)
	/*0x068*/     ULONG32      Flags;
	/*0x06C*/     UINT16       LoadCount;
	/*0x06E*/     UINT16       TlsIndex;
	union                                                    // 2 elements, 0x10 bytes (sizeof)
	{
		/*0x070*/         struct _LIST_ENTRY HashLinks;                        // 2 elements, 0x10 bytes (sizeof)
		struct                                               // 2 elements, 0x10 bytes (sizeof)
		{
			/*0x070*/             VOID*        SectionPointer;
			/*0x078*/             ULONG32      CheckSum;
			/*0x07C*/             UINT8        _PADDING1_[0x4];
		};
	};
	union                                                    // 2 elements, 0x8 bytes (sizeof)
	{
		/*0x080*/         ULONG32      TimeDateStamp;
		/*0x080*/         VOID*        LoadedImports;
	};
	/*0x088*/     struct _ACTIVATION_CONTEXT* EntryPointActivationContext;
	/*0x090*/     VOID*        PatchInformation;
	/*0x098*/     struct _LIST_ENTRY ForwarderLinks;                       // 2 elements, 0x10 bytes (sizeof)
	/*0x0A8*/     struct _LIST_ENTRY ServiceTagLinks;                      // 2 elements, 0x10 bytes (sizeof)
	/*0x0B8*/     struct _LIST_ENTRY StaticLinks;                          // 2 elements, 0x10 bytes (sizeof)
	/*0x0C8*/     VOID*        ContextInformation;
	/*0x0D0*/     UINT64       OriginalBase;
	/*0x0D8*/     union _LARGE_INTEGER LoadTime;                           // 4 elements, 0x8 bytes (sizeof)
}LDR_DATA, *PLDR_DATA;

typedef struct _OBJECT_TYPE_INITIALIZER                                                                                                                                         // 25 elements, 0x70 bytes (sizeof)
{
	/*0x000*/     UINT16       Length;
	union                                                                                                                                                                       // 2 elements, 0x1 bytes (sizeof)
	{
		/*0x002*/         UINT8        ObjectTypeFlags;
		struct                                                                                                                                                                  // 7 elements, 0x1 bytes (sizeof)
		{
			/*0x002*/             UINT8        CaseInsensitive : 1;                                                                                                                                   // 0 BitPosition
			/*0x002*/             UINT8        UnnamedObjectsOnly : 1;                                                                                                                                // 1 BitPosition
			/*0x002*/             UINT8        UseDefaultObject : 1;                                                                                                                                  // 2 BitPosition
			/*0x002*/             UINT8        SecurityRequired : 1;                                                                                                                                  // 3 BitPosition
			/*0x002*/             UINT8        MaintainHandleCount : 1;                                                                                                                               // 4 BitPosition
			/*0x002*/             UINT8        MaintainTypeList : 1;                                                                                                                                  // 5 BitPosition
			/*0x002*/             UINT8        SupportsObjectCallbacks : 1;                                                                                                                           // 6 BitPosition
		};
	};
	/*0x004*/     ULONG32      ObjectTypeCode;
	/*0x008*/     ULONG32      InvalidAttributes;
	/*0x00C*/     struct _GENERIC_MAPPING GenericMapping;                                                                                                                                     // 4 elements, 0x10 bytes (sizeof)
	/*0x01C*/     ULONG32      ValidAccessMask;
	/*0x020*/     ULONG32      RetainAccess;
	/*0x024*/     enum _POOL_TYPE PoolType;
	/*0x028*/     ULONG32      DefaultPagedPoolCharge;
	/*0x02C*/     ULONG32      DefaultNonPagedPoolCharge;
	/*0x030*/     PVOID DumpProcedure;
	/*0x038*/     PVOID OpenProcedure;
	/*0x040*/     PVOID CloseProcedure;
	/*0x048*/     PVOID DeleteProcedure;
	/*0x050*/     PVOID ParseProcedure;
	/*0x058*/     PVOID SecurityProcedure;
	/*0x060*/     PVOID QueryNameProcedure;
	/*0x068*/     PVOID OkayToCloseProcedure;
}OBJECT_TYPE_INITIALIZER, *POBJECT_TYPE_INITIALIZER;

typedef struct _EX_PUSH_LOCK                 // 7 elements, 0x8 bytes (sizeof)
{
	union                                    // 3 elements, 0x8 bytes (sizeof)
	{
		struct                               // 5 elements, 0x8 bytes (sizeof)
		{
			/*0x000*/             UINT64       Locked : 1;         // 0 BitPosition
			/*0x000*/             UINT64       Waiting : 1;        // 1 BitPosition
			/*0x000*/             UINT64       Waking : 1;         // 2 BitPosition
			/*0x000*/             UINT64       MultipleShared : 1; // 3 BitPosition
			/*0x000*/             UINT64       Shared : 60;        // 4 BitPosition
		};
		/*0x000*/         UINT64       Value;
		/*0x000*/         VOID*        Ptr;
	};
}EX_PUSH_LOCK, *PEX_PUSH_LOCK;

typedef struct _MY_OBJECT_TYPE                   // 12 elements, 0xD0 bytes (sizeof)
{
	/*0x000*/     struct _LIST_ENTRY TypeList;              // 2 elements, 0x10 bytes (sizeof)
	/*0x010*/     struct _UNICODE_STRING Name;              // 3 elements, 0x10 bytes (sizeof)
	/*0x020*/     VOID*        DefaultObject;
	/*0x028*/     UINT8        Index;
	/*0x029*/     UINT8        _PADDING0_[0x3];
	/*0x02C*/     ULONG32      TotalNumberOfObjects;
	/*0x030*/     ULONG32      TotalNumberOfHandles;
	/*0x034*/     ULONG32      HighWaterNumberOfObjects;
	/*0x038*/     ULONG32      HighWaterNumberOfHandles;
	/*0x03C*/     UINT8        _PADDING1_[0x4];
	/*0x040*/     struct _OBJECT_TYPE_INITIALIZER TypeInfo; // 25 elements, 0x70 bytes (sizeof)
	/*0x0B0*/     struct _EX_PUSH_LOCK TypeLock;            // 7 elements, 0x8 bytes (sizeof)
	/*0x0B8*/     ULONG32      Key;
	/*0x0BC*/     UINT8        _PADDING2_[0x4];
	/*0x0C0*/     struct _LIST_ENTRY CallbackList;          // 2 elements, 0x10 bytes (sizeof)
}MY_OBJECT_TYPE, *PMY_OBJECT_TYPE;

對於開啟了TypeInfo.SupportsObjectCallbacks屬性的驅動來說自然就支援檔案路徑轉換,當系統中有檔案被載入則自動執行LySharkFileObjectpreCall回撥事件,過濾掉無效路徑後即可直接輸出,完整程式碼如下所示;

// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include "lyshark.h"

PVOID obHandle;
DRIVER_INITIALIZE DriverEntry;

// 檔案回撥
OB_PREOP_CALLBACK_STATUS LySharkFileObjectpreCall(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION OperationInformation)
{
	UNICODE_STRING DosName;
	PFILE_OBJECT fileo = OperationInformation->Object;
	HANDLE CurrentProcessId = PsGetCurrentProcessId();
	UNREFERENCED_PARAMETER(RegistrationContext);

	if (OperationInformation->ObjectType != *IoFileObjectType)
	{
		return OB_PREOP_SUCCESS;
	}

	// 過濾無效指標
	if (fileo->FileName.Buffer == NULL || 
		!MmIsAddressValid(fileo->FileName.Buffer) || 
		fileo->DeviceObject == NULL || 
		!MmIsAddressValid(fileo->DeviceObject))
	{
		return OB_PREOP_SUCCESS;
	}

	// 過濾無效路徑
	if (!_wcsicmp(fileo->FileName.Buffer, L"\\Endpoint") || 
		!_wcsicmp(fileo->FileName.Buffer, L"?") || 
		!_wcsicmp(fileo->FileName.Buffer, L"\\.\\.") || 
		!_wcsicmp(fileo->FileName.Buffer, L"\\"))
	{
		return OB_PREOP_SUCCESS;
	}

	// 將物件轉為DOS路徑
	RtlVolumeDeviceToDosName(fileo->DeviceObject, &DosName);
	DbgPrint("[LyShark] 程序PID = %ld | 檔案路徑 = %wZ%wZ \n", (ULONG64)CurrentProcessId, &DosName, &fileo->FileName);

	return OB_PREOP_SUCCESS;
}

VOID EnableObType(POBJECT_TYPE ObjectType)
{
	PMY_OBJECT_TYPE myobtype = (PMY_OBJECT_TYPE)ObjectType;
	myobtype->TypeInfo.SupportsObjectCallbacks = 1;
}

VOID UnDriver(PDRIVER_OBJECT driver)
{
	UNREFERENCED_PARAMETER(driver);
	ObUnRegisterCallbacks(obHandle);
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
	NTSTATUS status = STATUS_SUCCESS;
	PLDR_DATA ldr;

	DbgPrint("hello lyshark.com \n");

	OB_CALLBACK_REGISTRATION obRegFileCallBack;
	OB_OPERATION_REGISTRATION opRegFileCallBack;

	// enable IoFileObjectType
	EnableObType(*IoFileObjectType);

	// bypass MmVerifyCallbackFunction
	ldr = (PLDR_DATA)Driver->DriverSection;
	ldr->Flags |= 0x20;

	// 初始化回撥
	memset(&obRegFileCallBack, 0, sizeof(obRegFileCallBack));
	obRegFileCallBack.Version = ObGetFilterVersion();
	obRegFileCallBack.OperationRegistrationCount = 1;
	obRegFileCallBack.RegistrationContext = NULL;
	RtlInitUnicodeString(&obRegFileCallBack.Altitude, L"321000");
	obRegFileCallBack.OperationRegistration = &opRegFileCallBack;

	memset(&opRegFileCallBack, 0, sizeof(opRegFileCallBack));
	opRegFileCallBack.ObjectType = IoFileObjectType;
	opRegFileCallBack.Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
	opRegFileCallBack.PreOperation = (POB_PRE_OPERATION_CALLBACK)&LySharkFileObjectpreCall;

	status = ObRegisterCallbacks(&obRegFileCallBack, &obHandle);
	if (!NT_SUCCESS(status))
	{
		DbgPrint("註冊回撥錯誤 \n");
		status = STATUS_UNSUCCESSFUL;
	}

	UNREFERENCED_PARAMETER(RegistryPath);
	Driver->DriverUnload = &UnDriver;
	return status;
}

執行這個驅動程式,當系統中有新檔案被載入時則自動輸出該檔案所屬程序PID以及該檔案的詳細路徑。

至於如何阻止開啟一個檔案其實與《驅動開發:核心註冊並監控物件回撥》文章中使用的方法是一致的,首先判斷OperationInformation->Operation是不是OB_OPERATION_HANDLE_CREATEOB_OPERATION_HANDLE_DUPLICATE如果是,則直接設定Parameters->CreateHandleInformation.DesiredAccess為0直接拒絕載入。

// 檔案回撥
OB_PREOP_CALLBACK_STATUS LySharkFileObjectpreCall(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION OperationInformation)
{
	UNICODE_STRING DosName;
	PFILE_OBJECT fileo = OperationInformation->Object;
	HANDLE CurrentProcessId = PsGetCurrentProcessId();
	UNREFERENCED_PARAMETER(RegistrationContext);

	if (OperationInformation->ObjectType != *IoFileObjectType)
	{
		return OB_PREOP_SUCCESS;
	}

	// 過濾無效指標
	if (fileo->FileName.Buffer == NULL || 
		!MmIsAddressValid(fileo->FileName.Buffer) || 
		fileo->DeviceObject == NULL || 
		!MmIsAddressValid(fileo->DeviceObject))
	{
		return OB_PREOP_SUCCESS;
	}

	// 過濾無效路徑
	if (!_wcsicmp(fileo->FileName.Buffer, L"\\Endpoint") || 
		!_wcsicmp(fileo->FileName.Buffer, L"?") || 
		!_wcsicmp(fileo->FileName.Buffer, L"\\.\\.") || 
		!_wcsicmp(fileo->FileName.Buffer, L"\\"))
	{
		return OB_PREOP_SUCCESS;
	}

	// 阻止開啟lyshark_com.txt文字
	if (wcsstr(_wcslwr(fileo->FileName.Buffer), L"lyshark_com.txt"))
	{
		if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE)
		{
			OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = 0;
		}
		if (OperationInformation->Operation == OB_OPERATION_HANDLE_DUPLICATE)
		{
			OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = 0;
		}
		DbgPrint("[LyShark] 已攔截 lyshark_com 檔案開啟 \n");
	}

	return OB_PREOP_SUCCESS;
}

執行修改後的驅動程式,然後嘗試開啟lyshark_com.txt則會提示系統找不到指定檔案。