使用Minifilter过滤驱动保护文件

代码如下:
可以保护拓展名.com文件不被删除、重命名、读写、可执行。
#include 
#include 
#include 
static UNICODE_STRING ProtectedExtention = RTL_CONSTANT_STRING(L"com");
//卸载回调
PFLT_FILTER gFileterHandle;
NTSTATUS PtUnload(__in FLT_FILTER_UNLOAD_FLAGS Flags) {
	UNREFERENCED_PARAMETER(Flags);
	FltUnregisterFilter(gFileterHandle);
	return STATUS_SUCCESS;
}
//预回调函数用于绑定IRP_MJ_CREATE的IRP
FLT_PREOP_CALLBACK_STATUS NPPreCreate(__inout PFLT_CALLBACK_DATA Data,__in PCFLT_RELATED_OBJECTS FltObjects,__deref_out_opt PVOID *CompletionContext) {
	UNREFERENCED_PARAMETER(CompletionContext);
	PAGED_CODE();
	FLT_PREOP_CALLBACK_STATUS ret = FLT_PREOP_SUCCESS_NO_CALLBACK;
	NTSTATUS status;
	PFLT_FILE_NAME_INFORMATION FileNameInfo = NULL;
	//可以执行
	if (Data->Iopb->MajorFunction == IRP_MJ_CREATE) {
		if (!FlagOn(Data->Iopb->Parameters.Create.Options, FILE_DISALLOW_EXCLUSIVE)) {
			return ret;
		}
	}
	
	if (FltObjects->FileObject != NULL) {
		status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &FileNameInfo);
		if (NT_SUCCESS(status)) {
			FltParseFileNameInformation(FileNameInfo);
			if (RtlCompareUnicodeString(&FileNameInfo->Extension, &ProtectedExtention, TRUE) == 0) {
				Data->IoStatus.Status = STATUS_ACCESS_DENIED;
				Data->IoStatus.Information = 0;
				ret = FLT_PREOP_COMPLETE;
			}
			FltReleaseFileNameInformation(FileNameInfo);
		}
	}
	return ret;
}


CONST FLT_OPERATION_REGISTRATION Callbacks[] = {
	{ IRP_MJ_CREATE, 0, NPPreCreate, NULL },				
	{ IRP_MJ_SET_INFORMATION, 0, NPPreCreate, NULL },		
	{ IRP_MJ_OPERATION_END }
};


CONST FLT_REGISTRATION FilterRegistration = {
	sizeof(FLT_REGISTRATION),
	FLT_REGISTRATION_VERSION,
	0,
	NULL,
	Callbacks,//回调函数
	PtUnload,//卸载回调
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL

};

NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) {
	NTSTATUS status;
	UNREFERENCED_PARAMETER(RegistryPath);
	status = FltRegisterFilter(DriverObject,&FilterRegistration,&gFileterHandle);//注册Minifilter
	//ASSERT(NT_SUCCESS(status));
	//开启过滤
	if (NT_SUCCESS(status)) {
		status = FltStartFiltering(gFileterHandle);
		if (!NT_SUCCESS(status)) {
			//注册失败则退出
			FltUnregisterFilter(gFileterHandle);
		}
	}
	return status;
}
环境说明:
需要在链接器->输入->附加项->添加(fltMgr.lib)

使用Minifilter过滤驱动保护文件_第1张图片

你可能感兴趣的:(驱动开发,安全)