SFilter框架理解
控制设备(接受我们自己的客服端)----过滤设备(接受别的进程的IRP) IRP栈每层对应的设备不同
绑定后返回的:最顶层的设备 看图 为什么返回最顶层,当我们的设备处理好后要发给下面的 而下面的第一个就是最顶层的设备 看图理解
过滤
分层驱动中再加一层而不影响它的上下层,以过滤它们之间的数据,对数据或行为进行安全控制。过滤是通过设备绑定实现的。
图:
绑定
设备栈绑定的形式。驱动自己生成一个设备(过滤设备),调用系统提供的绑定API,绑定到目标设备上。并返回一个在未绑定之前目标设备所在设备栈的最顶层设备。这样发往下层的IRP或者发往上层的数据都会被过滤设备截获。
PDEVICE_OBJECT
IoAttachDeviceToDeviceStack(
IN PDEVICE_OBJECT SourceDevice,
IN PDEVICE_OBJECT TargetDevice );
AttachedDevice需要记录,以便调用IoCallDriver()继续下发IRP
为什么要返回一个DEVICE_OBJECT呢?
"并返回一个在未绑定之前目标设备所在设备栈的最顶层设备"
一个系统中可能存在多个过滤设备
------------
SourceDevice
------------<-----AttachedDevice
Filter2Device
------------
Filter1Device
------------
TargetDevice
此时最顶层的对象为Filter2Device 返回这个以便IRP下发 比如放行
图:
绑定API:
IoAttachDevice()
IoAttachDeviceToDeviceStackSafe(2000 SP4以及XP以上)
IoAttachDeviceToDeviceStack()
windbg 查看相关信息:
!devobj 查看设备对象信息
!drvobj 查看驱动对象信息
!devstack 查看设备栈
!devnode 0 1 系统设备树
文件系统过滤框架
Filemon //不常见 不能动态监控移动设备
Sfilter //走在被淘汰的路上
Minifilter //未来主流
Filespy //不常见
Sfilter总体流程:
创建控制设备
创建控制设备符号链接
过滤分发函数
Fastio
过滤与绑定
生成一个过滤设备
IoRegisterFsRegistrationChange(
DriverObject,
SfFsNotification ); (文件系统设备绑定)
SfFsControl (卷设备绑定)
一个驱动,看见几个文件系统设备,看见几个卷设备,对应每一个设备就生成相应设备附载上去,然后进行相应处理。
绑定文件系统是在回调中(也就是上面的SfFsNotification),绑定卷设备在分发函数中 在绑定文件系统后 在FILR_SYSTEM_COMTEL中就会收到卷设备创建的信息 就可以绑定卷设备了 在分发函数中创建过滤设备对象
比如一个U盘插入电脑 ,它第一步需要创建一个文件对象,然后再创建一个卷设备
我们要动态Attach到这上面,我们需要Hook这个过程,而这个HOOK过程,我们用回调的方法
这个回调的作用是监视创建文件设备行为和绑定文件设备,绑定文件设备后,当这个U盘要创建卷设备的时候就会被我拦截到,这个时候我们就可以生成过滤设备绑定上去了
动态监控卷的挂载(VolumeMounting)概述: 一个新的存储介质被系统发现并在文件系统中创建一个新的卷Volume的过程被称为Mounting。其过程是: 文件系统的控制设备对象(FSCDO)将得到一个IRP,其主功能码(MajorFunctionCode)为IRP_MJ_FILE_SYSTEM_CONTRO。副功能码(MinorFunctionCode)为IRP_MN_MOUNT,呵呵,仔细想一下,不要死板,如果我们创建一个设备对象,并将其绑定到文件系统控制设备对象的设备对象栈上,那么我们的设备对象不就能接受到这个IRP了吗!这样,我们就能时刻的知道新卷的产生了。解决了上面的问题。
这里说说FileMon过滤
FileMon里的方法:
枚举26个盘符,打开文件,获得FileObjectDeviceObject.
然后通过自己驱动生成一个过滤设备,Attach过滤设备到DeviceObject上
无法监控类似U盘等动态加载上去的
而IoRegisterFsRegistrationChange是动态获取的
Fastio
文件系统除了处理正常的IRP之外,还要处理所谓的FastIo.
FastIo是Cache Manager调用所引发的一种没有irp的请求。换句话说,除了正常的Dispatch Functions之外,你还得为DriverObject撰写另一组Fast Io Functions.
这组函数的指针在driver->FastIoDispatch
代码:
fastIoDispatch = ExAllocatePoolWithTag( NonPagedPool,
sizeof( FAST_IO_DISPATCH ),
SFLT_POOL_TAG_FASTIO );
if (!fastIoDispatch) {
IoDeleteDevice( gSFilterControlDeviceObject );
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory( fastIoDispatch, sizeof( FAST_IO_DISPATCH ) );
fastIoDispatch->SizeOfFastIoDispatch = sizeof( FAST_IO_DISPATCH );
fastIoDispatch->FastIoCheckIfPossible = SfFastIoCheckIfPossible;
fastIoDispatch->FastIoRead = SfFastIoRead;
fastIoDispatch->FastIoWrite = SfFastIoWrite;
fastIoDispatch->FastIoQueryBasicInfo = SfFastIoQueryBasicInfo;
fastIoDispatch->FastIoQueryStandardInfo = SfFastIoQueryStandardInfo;
fastIoDispatch->FastIoLock = SfFastIoLock;
fastIoDispatch->FastIoUnlockSingle = SfFastIoUnlockSingle;
fastIoDispatch->FastIoUnlockAll = SfFastIoUnlockAll;
fastIoDispatch->FastIoUnlockAllByKey = SfFastIoUnlockAllByKey;
fastIoDispatch->FastIoDeviceControl = SfFastIoDeviceControl;
fastIoDispatch->FastIoDetachDevice = SfFastIoDetachDevice;
fastIoDispatch->FastIoQueryNetworkOpenInfo = SfFastIoQueryNetworkOpenInfo;
fastIoDispatch->MdlRead = SfFastIoMdlRead;
fastIoDispatch->MdlReadComplete = SfFastIoMdlReadComplete;
fastIoDispatch->PrepareMdlWrite = SfFastIoPrepareMdlWrite;
fastIoDispatch->MdlWriteComplete = SfFastIoMdlWriteComplete;
fastIoDispatch->FastIoReadCompressed = SfFastIoReadCompressed;
fastIoDispatch->FastIoWriteCompressed = SfFastIoWriteCompressed;
fastIoDispatch->MdlReadCompleteCompressed = SfFastIoMdlReadCompleteCompressed;
fastIoDispatch->MdlWriteCompleteCompressed = SfFastIoMdlWriteCompleteCompressed;
fastIoDispatch->FastIoQueryOpen = SfFastIoQueryOpen;
DriverObject->FastIoDispatch = fastIoDispatch;
看看我们的分发函数:
for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) {
DriverObject->MajorFunction[i] = SfPassThrough;//通用分发函数 下发IRP 私用IoSkip 和 IoCallDriver
}
//
// We will use SfCreate for all the create operations
//
DriverObject->MajorFunction[IRP_MJ_CREATE] = SfCreate;
//DriverObject->MajorFunction[IRP_MJ_CREATE_NAMED_PIPE] = SfCreate;
//DriverObject->MajorFunction[IRP_MJ_CREATE_MAILSLOT] = SfCreate;
DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = SfFsControl;//注意这个 当我们下面绑定了文件系统设备,我们就会收到这个IRP 在这个IRP处理函数中 我们就可以//绑定了卷设备对象了
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = SfCleanupClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = SfCleanupClose;
Sfilter代码通读分析
将我们驱动的对象保存起来---等会绑定文件系统设备的时候要用到
gSFilterDriverObject = DriverObject;
首先我们初始化一个链表,这个链表用来内存管理,防止碎片,等会再SfCreate中有很多数据,可能需要频繁的申请内存,这样不便于管理
我们在开头就初始化这个一个链表,当需要用到内存的时候就到这面来拿
ExInitializeFastMutex( &gSfilterAttachLock );
//
// Initialize the lookaside list for name buffering. This is used in
// several places to avoid having a large name buffer on the stack. It is
// also needed by the name lookup routines (NLxxx).
//
ExInitializePagedLookasideList( &gSfNameBufferLookasideList,
NULL,
NULL,
0,
SFILTER_LOOKASIDE_SIZE,
SFLT_POOL_TAG_NAME_BUFFER,
0 );
接下来就是创建设备对象
首先在
"\\FileSystem\\Filters\\SFilterDrv"
中创建,如果创建失败就在
"\\FileSystem\\SFilterDrv"
中创建
与NTMod不同的是 NTmodel中我们创建对象的时候对象是UNKNOW_DEVICE 这里我们创建的是磁盘文件系统设备
RtlInitUnicodeString( &nameString, L"\\FileSystem\\Filters\\SFilterDrv" );
status = IoCreateDevice( DriverObject,
0, //has no device extension
&nameString,
FILE_DEVICE_DISK_FILE_SYSTEM,
FILE_DEVICE_SECURE_OPEN,
FALSE,
&gSFilterControlDeviceObject );//保存下来 后面判断是发给我们的驱动的还是发给文件系统的
if (status == STATUS_OBJECT_PATH_NOT_FOUND) {
//
// This must be a version of the OS that doesn't have the Filters
// path in its namespace. This was added in Windows XP.
//
// We will try just putting our control device object in the
// \FileSystem portion of the object name space.
//
RtlInitUnicodeString( &nameString, L"\\FileSystem\\SFilterDrv" );
status = IoCreateDevice( DriverObject,
0, //has no device extension
&nameString,
FILE_DEVICE_DISK_FILE_SYSTEM,
FILE_DEVICE_SECURE_OPEN,
FALSE,
&gSFilterControlDeviceObject );
if (!NT_SUCCESS( status )) {
KdPrint( ("SFilter!DriverEntry: Error creating control device object \"%wZ\", status=%08x\n",
&nameString,
status ));
return status;
}
} else if (!NT_SUCCESS( status )) {
KdPrint(( "SFilter!DriverEntry: Error creating control device object \"%wZ\", status=%08x\n",
&nameString, status ));
return status;
}
然后就是设置我们的通信模式了
默认是BUFFIO
gSFilterControlDeviceObject->Flags |= DO_BUFFERED_IO; //gSFilterControlDeviceObject是我们保存的我们驱动的对象
接下去就是初始化分发函数了
for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) {
DriverObject->MajorFunction[i] = SfPassThrough;
}
//
// We will use SfCreate for all the create operations
//
//还有其他的 比如读写 改 删
/*
FilterCreate(创建)
FilterRead(一般不拦,加解密处理)
FilterWrite(修改,加解密处理)
FilterSetInfo(删,重命名)
FilterClose(一般不拦)
FilterClean(写关闭等)
等
*/
DriverObject->MajorFunction[IRP_MJ_CREATE] = SfCreate;
//DriverObject->MajorFunction[IRP_MJ_CREATE_NAMED_PIPE] = SfCreate;
//DriverObject->MajorFunction[IRP_MJ_CREATE_MAILSLOT] = SfCreate;
注意这个 当我们下面绑定了文件系统设备,我们就会收到这个IRP 在这个IRP处理函数中 我们就可以//绑定了卷设备对象了
DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = SfFsControl;//卷设备绑定
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = SfCleanupClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = SfCleanupClose;
前面说过了,不但有Dispatch分发函数 也有 fastIoDispatch
fastIoDispatch = ExAllocatePoolWithTag( NonPagedPool,
sizeof( FAST_IO_DISPATCH ),
SFLT_POOL_TAG_FASTIO );
if (!fastIoDispatch) {
IoDeleteDevice( gSFilterControlDeviceObject );
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory( fastIoDispatch, sizeof( FAST_IO_DISPATCH ) );
fastIoDispatch->SizeOfFastIoDispatch = sizeof( FAST_IO_DISPATCH );
fastIoDispatch->FastIoCheckIfPossible = SfFastIoCheckIfPossible;
fastIoDispatch->FastIoRead = SfFastIoRead;
fastIoDispatch->FastIoWrite = SfFastIoWrite;
fastIoDispatch->FastIoQueryBasicInfo = SfFastIoQueryBasicInfo;
fastIoDispatch->FastIoQueryStandardInfo = SfFastIoQueryStandardInfo;
fastIoDispatch->FastIoLock = SfFastIoLock;
fastIoDispatch->FastIoUnlockSingle = SfFastIoUnlockSingle;
fastIoDispatch->FastIoUnlockAll = SfFastIoUnlockAll;
fastIoDispatch->FastIoUnlockAllByKey = SfFastIoUnlockAllByKey;
fastIoDispatch->FastIoDeviceControl = SfFastIoDeviceControl;
fastIoDispatch->FastIoDetachDevice = SfFastIoDetachDevice;
fastIoDispatch->FastIoQueryNetworkOpenInfo = SfFastIoQueryNetworkOpenInfo;
fastIoDispatch->MdlRead = SfFastIoMdlRead;
fastIoDispatch->MdlReadComplete = SfFastIoMdlReadComplete;
fastIoDispatch->PrepareMdlWrite = SfFastIoPrepareMdlWrite;
fastIoDispatch->MdlWriteComplete = SfFastIoMdlWriteComplete;
fastIoDispatch->FastIoReadCompressed = SfFastIoReadCompressed;
fastIoDispatch->FastIoWriteCompressed = SfFastIoWriteCompressed;
fastIoDispatch->MdlReadCompleteCompressed = SfFastIoMdlReadCompleteCompressed;
fastIoDispatch->MdlWriteCompleteCompressed = SfFastIoMdlWriteCompleteCompressed;
fastIoDispatch->FastIoQueryOpen = SfFastIoQueryOpen;
DriverObject->FastIoDispatch = fastIoDispatch;
然后就是初始化一些回调函数被设置在我们的驱动对象上 也就是注册回调函数
FS_FILTER_CALLBACKS fsFilterCallbacks;
if (NULL != gSfDynamicFunctions.RegisterFileSystemFilterCallbacks) {
//
// Setup the callbacks for the operations we receive through
// the FsFilter interface.
//
// NOTE: You only need to register for those routines you really
// need to handle. SFilter is registering for all routines
// simply to give an example of how it is done.
//
fsFilterCallbacks.SizeOfFsFilterCallbacks = sizeof( FS_FILTER_CALLBACKS );
fsFilterCallbacks.PreAcquireForSectionSynchronization = SfPreFsFilterPassThrough;
fsFilterCallbacks.PostAcquireForSectionSynchronization = SfPostFsFilterPassThrough;
fsFilterCallbacks.PreReleaseForSectionSynchronization = SfPreFsFilterPassThrough;
fsFilterCallbacks.PostReleaseForSectionSynchronization = SfPostFsFilterPassThrough;
fsFilterCallbacks.PreAcquireForCcFlush = SfPreFsFilterPassThrough;
fsFilterCallbacks.PostAcquireForCcFlush = SfPostFsFilterPassThrough;
fsFilterCallbacks.PreReleaseForCcFlush = SfPreFsFilterPassThrough;
fsFilterCallbacks.PostReleaseForCcFlush = SfPostFsFilterPassThrough;
fsFilterCallbacks.PreAcquireForModifiedPageWriter = SfPreFsFilterPassThrough;
fsFilterCallbacks.PostAcquireForModifiedPageWriter = SfPostFsFilterPassThrough;
fsFilterCallbacks.PreReleaseForModifiedPageWriter = SfPreFsFilterPassThrough;
fsFilterCallbacks.PostReleaseForModifiedPageWriter = SfPostFsFilterPassThrough;
status = (gSfDynamicFunctions.RegisterFileSystemFilterCallbacks)( DriverObject,
&fsFilterCallbacks );
if (!NT_SUCCESS( status )) {
DriverObject->FastIoDispatch = NULL;
ExFreePoolWithTag( fastIoDispatch, SFLT_POOL_TAG_FASTIO );
IoDeleteDevice( gSFilterControlDeviceObject );
return status;
}
}
接下去就是创建一个回调,监视文件系统设备创建,在这个回调中,我们可以监控文件系统创建和绑定文件系统设备
status = IoRegisterFsRegistrationChange( DriverObject, SfFsNotification );//在里面绑定文件系统设备,也是卷设备绑定的前提条件
if (!NT_SUCCESS( status )) {
KdPrint(( "SFilter!DriverEntry: Error registering FS change notification, status=%08x\n",
status ));
DriverObject->FastIoDispatch = NULL;
ExFreePoolWithTag( fastIoDispatch, SFLT_POOL_TAG_FASTIO );
IoDeleteDevice( gSFilterControlDeviceObject );
return status;
}
然后就是对文件计数引用
/*
IoGetDeviceObjectPointer函数的功能是:
它从下层的设备对象名称来获得下层设备指针。该函数造成了对下层设备对象以及下层设备对象所对应的文件对象的引用。
如果本层驱动在卸载之前对下层的设备对象的引用还没有消除,则下层驱动的卸载会被停止。因此必须要消除对下层设备对象的引用。
但是程序一般不会直接对下层设备对象的引用减少。因此只要减少对文件对象的引用就可以减少文件对象和设备对象两个对象的引用。
事实上,IoGetDeviceObjectPointer返回的并不是下层设备对象的指针,而是该设备堆栈中顶层的设备对象的指针。
IoGetDeviceObjectPointer函数的调用必须在 IRQL=PASSIVE_LEVEL的级别上运行。
*/
{
PDEVICE_OBJECT rawDeviceObject;
PFILE_OBJECT fileObject;
//
// Attach to RawDisk device
//
RtlInitUnicodeString( &nameString, L"\\Device\\RawDisk" );
status = IoGetDeviceObjectPointer(
&nameString,
FILE_READ_ATTRIBUTES,
&fileObject,
&rawDeviceObject );
if (NT_SUCCESS( status )) {
SfFsNotification( rawDeviceObject, TRUE );//绑定RawDisk 激活这个设备 然后被我们捕捉到,绑定过滤设备
ObDereferenceObject( fileObject );
}
//
// Attach to the RawCdRom device
//
RtlInitUnicodeString( &nameString, L"\\Device\\RawCdRom" );
status = IoGetDeviceObjectPointer(
&nameString,
FILE_READ_ATTRIBUTES,
&fileObject,
&rawDeviceObject );
if (NT_SUCCESS( status )) {
SfFsNotification( rawDeviceObject, TRUE );//同上
ObDereferenceObject( fileObject );
}
}
//
// Clear the initializing flag on the control device object since we
// have now successfully initialized everything.
//
ClearFlag( gSFilterControlDeviceObject->Flags, DO_DEVICE_INITIALIZING );
DbgPrint("Sfilter installed\n");
return STATUS_SUCCESS;
}
去看看SfFsNotification
//回调例程,当文件系统被激活或者撤销时调用//在该例程中,完成对文件系统控制设备对象的绑定.
绑定文件系统: 首先,我们需要知道当前系统中都有那些文件系统,例如:NTFS,FAT32,CDFS。因为,卷设备对象是由文件系统创建的。 其次,我们要知道什么时候去绑定文件系统。当一个卷设备对象动态产生的时候,其对应的文件系统就被激活。例如,如果一个FAT32的U盘被插入到电脑上,则对应的FAT32文件系统就会被激活,并创建一个“J:”的卷设备对象。 IoRegisterFsRegistrationChange是一个非常有用的系统调用。这个调用注册一个回调函数,当系统中有文件系统被激活或者撤销时,该回调函数就被调用。OhGood,那么我们就可以在这个回调函数中去绑定文件系统的控制设备对象。 这里要注意:文件系统的加载和卷的挂载是两码事,卷的挂载是建立在文件系统被激活的基础上。当一个文件系统被激活后,才能创建卷设备对象
SfFsNotification是我们要注册的回调函数,它调用SfAttachToFileSystemDevice完成真正的设备绑定。当然,它还有其他功能,代码说明问题。 SfAttachToFileSystemDevice创建过滤设备对象,并调用我们设备绑定外包函数:SfAttachDeviceToDeviceStack来将过滤设备对象绑定到文件系统控制设备对象的设备栈上。 这样,我们的过滤设备对象就能接受到发送到FSCDO的IRP_MJ_FILE_SYSTEM_CONTRO的请求,动态监控卷的挂载。那么以后的工作就是完成对卷的监控绑定了。
回调例程,当文件系统被激活或者撤销时调用
//在该例程中,完成对文件系统控制设备对象的绑定.//
//例程描述:
这个例程在文件系统激活或者销毁的时被调用
这个例程创建一个设备对象将它附加到指定的文件系统控制设备对象
//的对象栈上,这就允许这个设备对象过滤所有发送给文件系统的请求.
//这样,我们就能获得一个挂载卷的请求,就可以附加到这个新的卷设备对象
//的设备对象栈上//
//参数:
DeviceObject:指向被激活或者撤销的文件系统的控制设备对象
FsActive:激活或者撤销标志
{
PNAME_CONTROL devName;
PAGED_CODE();
//
// Display the names of all the file system we are notified of
//
devName = NLGetAndAllocateObjectName( DeviceObject,
&gSfNameBufferLookasideList );
if (devName == NULL) {
SF_LOG_PRINT( SFDEBUG_DISPLAY_ATTACHMENT_NAMES,
("SFilter!SfFsNotification: Not attaching to %p, insufficient resources.\n",
DeviceObject) );
return;
}
SF_LOG_PRINT( SFDEBUG_DISPLAY_ATTACHMENT_NAMES,
("SFilter!SfFsNotification: %s %p \"%wZ\" (%s)\n",
(FsActive) ? "Activating file system " : "Deactivating file system",
DeviceObject,
&devName->Name,
GET_DEVICE_TYPE_NAME(DeviceObject->DeviceType)) );
//
// Handle attaching/detaching from the given file system.
//
if (FsActive) {
SfAttachToFileSystemDevice( DeviceObject, devName );
} else {
SfDetachFromFileSystemDevice( DeviceObject );
}
//
// We're done with name (SfAttachToFileSystemDevice copies the name to
// the device extension) so free it.
//
NLFreeNameControl( devName, &gSfNameBufferLookasideList );
}
这个绑定了文件设备对象,这时我们就可以收到IRP_MJ_FILE_SYSTEM_CONTROL IRP 在这个例程里我们就可以实现对卷的绑定
(注意 这里必须绑定了文件设备后才能收到哦)
看下IRP_MJ_FILE_SYSTEM_CONTROL的例程
switch (irpSp->MinorFunction) {
case IRP_MN_MOUNT_VOLUME://设备在Mount的时候,我们就要进行绑定了
return SfFsControlMountVolume( DeviceObject, Irp );
case IRP_MN_LOAD_FILE_SYSTEM:
return SfFsControlLoadFileSystem( DeviceObject, Irp );
case IRP_MN_USER_FS_REQUEST:
{
switch (irpSp->Parameters.FileSystemControl.FsControlCode) {
case FSCTL_DISMOUNT_VOLUME:
{
PSFILTER_DEVICE_EXTENSION devExt = DeviceObject->DeviceExtension;
SF_LOG_PRINT( SFDEBUG_DISPLAY_ATTACHMENT_NAMES,
("SFilter!SfFsControl: Dismounting volume %p \"%wZ\"\n",
devExt->NLExtHeader.AttachedToDeviceObject,
&devExt->NLExtHeader.DeviceName) );
break;
}
}
break;
}
}
//
// Pass all other file system control requests through.
//
IoSkipCurrentIrpStackLocation( Irp );
return IoCallDriver( ((PSFILTER_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->NLExtHeader.AttachedToDeviceObject,
Irp );
}
差不多就是这样,我们来看看其它分发函数
比如SfCreate
我们要做的工作就是在分发函数里写代码
NTSTATUS
SfCreate (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
/*++
Routine Description:
This function filters create/open operations. It simply establishes an
I/O completion routine to be invoked if the operation was successful.
Arguments:
DeviceObject - Pointer to the target device object of the create/open.
Irp - Pointer to the I/O Request Packet that represents the operation.
Return Value:
The function value is the status of the call to the file system's entry
point.
--*/
{
NTSTATUS status;
PNAME_CONTROL fileName = NULL;
PSFILTER_DEVICE_EXTENSION devExt = (PSFILTER_DEVICE_EXTENSION)(DeviceObject->DeviceExtension);
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation( Irp );
BOOLEAN cacheName;
PAGED_CODE();
//
// If this is for our control device object, don't allow it to be opened.
//
//如果是我们的设备 返回成功 这个宏判断设备对象是不是我们保存那个和是不是我们的驱动对象
if (IS_MY_CONTROL_DEVICE_OBJECT(DeviceObject)) {
//
// Sfilter doesn't allow for any communication through its control
// device object, therefore it fails all requests to open a handle
// to its control device object.
//
// See the FileSpy sample for an example of how to allow creates to
// the filter's control device object and manage communication via
// that handle.
//
//Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return STATUS_INVALID_DEVICE_REQUEST;
//return STATUS_SUCCESS;
}
ASSERT(IS_MY_DEVICE_OBJECT( DeviceObject ));
//
// If debugging is enabled, do the processing required to see the packet
// upon its completion. Otherwise, let the request go with no further
// processing.
//
if (!FlagOn( SfDebug, SFDEBUG_DO_CREATE_COMPLETION |
SFDEBUG_GET_CREATE_NAMES|
SFDEBUG_DISPLAY_CREATE_NAMES )) {
//
// We don't want to get filenames, display filenames, or
// call our completion routine. Don't put us on the stack
// and call the next driver.
//
//如果是Deug 就不显示 直接下发
IoSkipCurrentIrpStackLocation( Irp );
return IoCallDriver( ((PSFILTER_DEVICE_EXTENSION) DeviceObject->DeviceExtension)->NLExtHeader.AttachedToDeviceObject,
Irp );
}
//如果要显示一下信息
if (FlagOn( SfDebug, SFDEBUG_GET_CREATE_NAMES |
SFDEBUG_DISPLAY_CREATE_NAMES ) &&
!FlagOn(devExt->Flags,SFDEVFL_DISABLE_VOLUME)) {
//
// Debugging specifies that we need to get the filename
//
NAME_LOOKUP_FLAGS LookupFlags = 0x00000000;
//
// If DosName has been set, indicate via flags that we
// want to use it when getting the full file name.
//
if (devExt->NLExtHeader.DosName.Length != 0) {
SetFlag( LookupFlags, NLFL_USE_DOS_DEVICE_NAME );
}
//
// Indicate we are in pre-create
//
SetFlag( LookupFlags, NLFL_IN_CREATE );
if (FlagOn( irpSp->Parameters.Create.Options, FILE_OPEN_BY_FILE_ID )) {
//
// The file is being opened by ID, not file name.
//
SetFlag( LookupFlags, NLFL_OPEN_BY_ID );
}
if (FlagOn( irpSp->Flags, SL_OPEN_TARGET_DIRECTORY )) {
//
// The file's parent directory should be opened
//
SetFlag( LookupFlags, NLFL_OPEN_TARGET_DIR );
}
//
// Retrieve the file name. Note that in SFilter we don't do any name
// caching.
//
//申请存储数据的空间
status = NLAllocateNameControl( &fileName, &gSfNameBufferLookasideList );
if (NT_SUCCESS( status )) {
//
// We are okay not checking the return value here because
// the GetFullPathName function will set the Unicode String
// length to 0. So either way, in an error it will print an empty string
//
//拿到文件的全路径
status = NLGetFullPathName( irpSp->FileObject,
fileName,
&devExt->NLExtHeader,
LookupFlags,
&gSfNameBufferLookasideList,
&cacheName );
}
}
//往下发
if (FlagOn( SfDebug, SFDEBUG_DISPLAY_CREATE_NAMES |
SFDEBUG_DO_CREATE_COMPLETION ) &&
!FlagOn(devExt->Flags,SFDEVFL_DISABLE_VOLUME)) {
//
// Debugging flags indicate we must do completion.
// Note that to display file names we must do completion
// because we don't know IoStatus.Status and IoStatus.Information
// until post-create.
//
KEVENT waitEvent;
//
// Initialize an event to wait for the completion routine to occur
//
KeInitializeEvent( &waitEvent, NotificationEvent, FALSE );
//
// Copy the stack and set our Completion routine
//
设置完成例程
IoCopyCurrentIrpStackLocationToNext( Irp );
IoSetCompletionRoutine(
Irp,
SfCreateCompletion,
&waitEvent,
TRUE,
TRUE,
TRUE );
//
// Call the next driver in the stack.
//
status = IoCallDriver( devExt->NLExtHeader.AttachedToDeviceObject, Irp );
//
// Wait for the completion routine to be called
//
if (STATUS_PENDING == status) {
NTSTATUS localStatus = KeWaitForSingleObject( &waitEvent,
Executive,
KernelMode,
FALSE,
NULL );
ASSERT(STATUS_SUCCESS == localStatus);
}
//
// Verify the IoCompleteRequest was called
//
ASSERT(KeReadStateEvent(&waitEvent) ||
!NT_SUCCESS(Irp->IoStatus.Status));
//
// If debugging indicates we should display file names, do it.
//
//打印信息
if (irpSp->Parameters.Create.Options & FILE_OPEN_BY_FILE_ID) {
SF_LOG_PRINT( SFDEBUG_DISPLAY_CREATE_NAMES,
("SFilter!SfCreate: OPENED fo=%p %08x:%08x %wZ (FID)\n",
irpSp->FileObject,
Irp->IoStatus.Status,
Irp->IoStatus.Information,
&fileName->Name) );
} else {
SF_LOG_PRINT( SFDEBUG_DISPLAY_CREATE_NAMES,
("SFilter!SfCreate: OPENED fo=%p st=%08x:%08x %wZ\n",
irpSp->FileObject,
Irp->IoStatus.Status,
Irp->IoStatus.Information,
&fileName->Name) );
}
//
// Release the name control structure if we have
//
if (fileName != NULL) {
NLFreeNameControl( fileName, &gSfNameBufferLookasideList );
}
//
// Save the status and continue processing the IRP
//
status = Irp->IoStatus.Status;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return status;
} else {
//
// Free the name control if we have one
//
if (fileName != NULL) {
NLFreeNameControl( fileName, &gSfNameBufferLookasideList );
}
//
// Debugging flags indicate we did not want to display the file name
// or call completion routine.
// (ie SFDEBUG_GET_CREATE_NAMES && !SFDEBUG_DO_CREATE_COMPLETION)
//
IoSkipCurrentIrpStackLocation( Irp );
return IoCallDriver( ((PSFILTER_DEVICE_EXTENSION) DeviceObject->DeviceExtension)->NLExtHeader.AttachedToDeviceObject,
Irp );
}
}
再来看看分发函数
非过滤驱动中的默CommonDispatch
NTSTATUS CommonDispatch(
PDEVICE_OBJECT DeviceObject,
PIRP Irp)
{
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
过滤驱动中CommonDispatch写法
NTSTATUS SfPassThrough (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PIO_STACK_LOCATION pIrp = IoGetCurrentIrpStackLocation( Irp );
ASSERT(!IS_MY_CONTROL_DEVICE_OBJECT( DeviceObject ));
ASSERT(IS_MY_DEVICE_OBJECT( DeviceObject ));
if (!IS_MY_DEVICE_OBJECT(DeviceObject) ||
IS_MY_CONTROL_DEVICE_OBJECT(DeviceObject))
{
NTSTATUS status = Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return status;
}
IoSkipCurrentIrpStackLocation( Irp );
return IoCallDriver( ((PSFILTER_DEVICE_EXTENSION) DeviceObject->DeviceExtension)->NLExtHeader.AttachedToDeviceObject,
Irp );
}
一个是结束IRP 一个是判断是不是发给我们驱动的 如果是就返回无效的参数,(这里是返回失败,但在拦截的分发函数中是需要放行的这个放行是返回success)
对一个主防来说:
FilterCreate(创建)
FilterRead(一般不拦,加解密处理)
FilterWrite(修改,加解密处理)
FilterSetInfo(删,重命名)
FilterClose(一般不拦)
FilterClean(写关闭等)
等
对于一个主防来说 一般是拦截创建 和 关闭 为什么要拦截关闭呢 一个人现在是好人,但他不一定一辈子都是好人
创建文件 我们放了,然后它写入了一个shellcode 如果我们拦截写的话 一个一个的拦截 效果并不好 在关闭的时候我们就可以一次性知道
深入理解下设备对象
设备对象类别
Sfilter自己的设备
控制设备
过滤设备
其它设备
文件系统设备
卷设备
设备类别
FILE_DEVICE_DISK_FILE_SYSTEM
#define IS_MY_DEVICE_OBJECT(_devObj) \
(((_devObj) != NULL) && \
((_devObj)->DriverObject == gSFilterDriverObject) && \
((_devObj)->DeviceExtension != NULL))
#define IS_MY_CONTROL_DEVICE_OBJECT(_devObj) \
(((_devObj) == gSFilterControlDeviceObject) ? \
(ASSERT(((_devObj)->DriverObject == gSFilterDriverObject) && \
((_devObj)->DeviceExtension == NULL)), TRUE) : \
FALSE)
#define IS_DESIRED_DEVICE_TYPE(_type) \
(((_type) == FILE_DEVICE_DISK_FILE_SYSTEM) || \
((_type) == FILE_DEVICE_CD_ROM_FILE_SYSTEM) || \
((_type) == FILE_DEVICE_NETWORK_FILE_SYSTEM))
三种类型的设备处理
NTSTATUS FilterXXX(PDEVICE_OBJECT DeviceObject, PIRP pIrp)//过滤设备
{
NTSTATUS Status = STATUS_SUCCESS;
ULONG ulInfomation = 0;
IO_STACK_LOCATION* lpIrpStack = IoGetCurrentIrpStackLocation(pIrp);
if (IS_MY_CONTROL_DEVICE_OBJECT(DeviceObject))//控制设备
{
//如果需要与R3交互,这里必须返回成功
pIrp->IoStatus.Status = Status;
pIrp->IoStatus.Information = ulInfomation;
IoCompleteRequest(lpIrp, IO_NO_INCREMENT);
}
else if (!IS_MY_DEVICE_OBJECT(DeviceObject))
{
//非法参数
pIrp->IoStatus.Status = Status = STATUS_INVALID_PARAMETER;
pIrp->IoStatus.Information = 0;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
}
else
{
//这里才是我们要过滤的操作
IoSkipCurrentIrpStackLocation( pIrp );
Status = IoCallDriver(((PSFILTER_DEVICE_EXTENSION)->DeviceExtension)DeviceObject->NLExtHeader.AttachedToDeviceObject, pIrp);
}
return Status;
}
重要问题:文件路径的解析与保存
Namelookup.c(构造IRP,不能用 ObQueryNameString)
NLGetFullPathName()
NLPQueryFileSystemForFileName()IRP查询
在SfCreate里查询名字,通过FILE_OBJECT与Name保存起来。供其它过滤函数中查询使用。
保存在哪里?
List_Entry
HASH
TREE
Sfilter安装测试
原始的Sfilter框架,不支持通信
sfCreate中对自己的控制设备,返回成功
符号链接的创建(框架中没有)
GroupOrder:"FSFilter Activity Monitor“
L\\FileSystem\\SFilterDrv
DeviceObjectFlags |= DO_BUFFERED_IO
不要在release版本使用DriverUnload。BSOD
既然是过滤 那么就有放和禁
FilterCreate:
放:
内核过来的
Irp->RequestorMode == KernelMode
本进程的
FilterDeviceIoctrl中 PsGetCurrentProcessId()
系统进程的
DriverEntry里:PsGetCurrentProcessId()
文件夹
ulOptions = IrpStack->Parameters.Create.Options ;
FlagOn(IrpStack->FileObject->Flags, FO_VOLUME_OPEN) ||
FlagOn(ulOptions, FILE_DIRECTORY_FILE) ||
FlagOn(IrpStack->Flags, SL_OPEN_PAGING_FILE)
分页IO
(Irp->Flags & IRP_PAGING_IO) ||
(Irp->Flags & IRP_SYNCHRONOUS_PAGING_IO)
KeGetCurrentIrql() > APC_LEVEL
如何放?
IoSkipCurrentIrpStackLocation( lpIrp );
IoCallDriver();
禁:自定义啦 比如禁止在driver目录写入sys文件
拿文件名/长短名转化 短文转长名
匹配规则
FsRtlIsNameInExpression
弹框
拦
STATUS_ACCESS_DENIED
放
Pending完成例程
加入表中,供其它Filter函数使用
FilterWrite:
放:
本进程
系统进程
分页IO
从表中根据file_object没有找到的
匹配规则
弹框
拦截
放
效率
多次写?
FilterSetInfo:拦截删除,重命名等
IrpStack->Parameters.SetFile.FileInformationClass
FileRenameInformation//重命名
如何拿重命名之后的文件名?
IrpSp->Parameters.SetFile.FileObject//测试无效
IrpSp->FileObject//测试无效
Irp->AssociatedIrp.SystemBuffer;//有效
//R3UserResult = hipsGetResultFromUser(szOper, lpNameControl->Name.Buffer, ((PFILE_RENAME_INFORMATION)(lpIrp->AssociatedIrp.SystemBuffer))->FileName, User_DefaultNon);
if(R3UserResult == User_Block)
<span style="white-space:pre"></span>goto Ex;
DbgPrint("%ws\n",((PFILE_RENAME_INFORMATION)(lpIrp->AssociatedIrp.SystemBuffer))->FileName);
fileObject->DeviceObject
RtlVolumeDeviceToDosName
ObQueryNameString
IoQueryFileDosDeviceName
FileDispositionInformation//删除
删除
例子: 这个例子中还没拿到重命名后的文件名 和将重命名后的文件名传给R3 (hipsGetResultFromUser的第三个参数)
NTSTATUS
sfSetInformation(PDEVICE_OBJECT lpDevice, PIRP lpIrp)
{
NTSTATUSStatus= STATUS_SUCCESS;
ULONGulInfomation= 0;
UNICODE_STRINGustrRule= {0};
PLIST_ENTRYCurrentList= NULL;
USER_RESULTR3UserResult= User_Pass;
PNAME_CONTROLlpNameControl= NULL;
BOOLEANbSkipped= FALSE;
BOOLEANbNeedPostOp= FALSE;
BOOLEANbRename= FALSE;
IO_STACK_LOCATION*lpIrpStack= IoGetCurrentIrpStackLocation(lpIrp);
PFILE_OBJECTlpFileObject= lpIrpStack->FileObject;
PTWOWAYpTwoWay= NULL;
WCHAR*szOper= NULL;
if (IS_MY_CONTROL_DEVICE_OBJECT(lpDevice))
{
lpIrp->IoStatus.Status = Status;
lpIrp->IoStatus.Information = ulInfomation;
IoCompleteRequest(lpIrp, IO_NO_INCREMENT);
return Status;
}
else if (!IS_MY_DEVICE_OBJECT(lpDevice))
{
lpIrp->IoStatus.Status = Status = STATUS_INVALID_PARAMETER;
lpIrp->IoStatus.Information = 0;
IoCompleteRequest(lpIrp, IO_NO_INCREMENT);
return Status;
}
else
{
PSFILTER_DEVICE_EXTENSION lpDevExt = (PSFILTER_DEVICE_EXTENSION)(lpDevice->DeviceExtension);
if (PsGetCurrentProcessId() == g_hSystemProcID)
{
bSkipped = TRUE;
goto _EXIT;
}
//从HASH表中获得文件名
pTwoWay = Find((DWORD)lpFileObject, g_pHashTable);
if (pTwoWay == NULL)
{
bSkipped = TRUE;
goto _EXIT;
}
lpNameControl = pTwoWay->data.lpNameControl;
if (lpIrpStack->Parameters.SetFile.FileInformationClass == FileRenameInformation ||
lpIrpStack->Parameters.SetFile.FileInformationClass == FileBasicInformation ||
lpIrpStack->Parameters.SetFile.FileInformationClass == FileAllocationInformation ||
lpIrpStack->Parameters.SetFile.FileInformationClass == FileEndOfFileInformation ||
lpIrpStack->Parameters.SetFile.FileInformationClass == FileDispositionInformation)
{
switch (lpIrpStack->Parameters.SetFile.FileInformationClass)
{
case FileAllocationInformation:
case FileEndOfFileInformation:
szOper = L"设置大小";
bSkipped = TRUE;
goto _EXIT;
// break;
case FileRenameInformation:
szOper = L"重命名";
break;
case FileBasicInformation:
szOper = L"设置基础信息";
bSkipped = TRUE;
goto _EXIT;
//break;
case FileDispositionInformation:
bNeedPostOp = TRUE;
szOper = L"删除";
break;
}
}
else
{
// 允许
bSkipped = TRUE;
goto _EXIT;
}
RtlInitUnicodeString(&ustrRule, L"C:\\WINDOWS\\SYSTEM32\\*\\*.SYS");
if (!IsPatternMatch(&ustrRule, &lpNameControl->Name, TRUE))
{
bSkipped = TRUE;
goto _EXIT;
}
if (lpIrpStack->Parameters.SetFile.FileInformationClass == FileRenameInformation)
{
//重命名的目标路径?
}
R3UserResult = hipsGetResultFromUser(szOper, lpNameControl->Name.Buffer, NULL, User_DefaultNon);
if (R3UserResult == User_Block)
{
// 禁止
lpIrp->IoStatus.Information = 0;
lpIrp->IoStatus.Status = STATUS_ACCESS_DENIED;
IoCompleteRequest(lpIrp, IO_NO_INCREMENT);
Status = STATUS_ACCESS_DENIED;
bSkipped = FALSE;
goto _EXIT;
}
bSkipped = TRUE;
}
_EXIT:
if (bSkipped)
{
KEVENT waitEvent;
IoCopyCurrentIrpStackLocationToNext(lpIrp);
KeInitializeEvent(&waitEvent,
NotificationEvent,
FALSE);
IoSetCompletionRoutine(lpIrp,
SetFilterCompletion,
&waitEvent,
TRUE,
TRUE,
TRUE);
Status = IoCallDriver(
((PSFILTER_DEVICE_EXTENSION)lpDevice->DeviceExtension)->NLExtHeader.AttachedToDeviceObject,
lpIrp);
if (Status == STATUS_PENDING)
{
Status = KeWaitForSingleObject(&waitEvent,
Executive,
KernelMode,
FALSE,
NULL);
}
Status = lpIrp->IoStatus.Status;
IoCompleteRequest(lpIrp, IO_NO_INCREMENT);
}
return Status;
}
参考:
http://blog.csdn.net/cosmoslife/article/details/7727688
http://bbs.pediy.com/archive/index.php?t-152338.html