Exemplo n.º 1
0
NTSTATUS FilterUnload ( IN FLT_FILTER_UNLOAD_FLAGS Flags )
{
	PLIST_ENTRY pListHead;
	PFILE_EVENT_PACKET pFileEventPacket;
	FltCloseCommunicationPort( fileManager.pServerPort );

	if(fileManager.bReady == TRUE)
	{
		FltUnregisterFilter( fileManager.pFilter );	
		KeCancelTimer(&fileManager.connectionCheckerTimer);
	}

	// Free the log directory
	if(fileManager.logDirectory.Buffer != NULL)
	{
		ExFreePoolWithTag(fileManager.logDirectory.Buffer, FILE_POOL_TAG);
		fileManager.logDirectory.Buffer = NULL;
	}
	fileManager.bCollectDeletedFiles = FALSE;

	// Free the linked list containing all the left over file events
	FreeQueuedEvents();

	return STATUS_SUCCESS;
}
Exemplo n.º 2
0
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
    DBG_PRINT("SecretStash!DriverEntry: Entered\n");

    secretStashConfig.RegDataLoaded = FALSE;
    NTSTATUS status = STATUS_SUCCESS;
    try
    {
        LeaveOnFail(FltRegisterFilter(DriverObject, &FilterRegistration, &secretStashConfig.Filter)); //  Register with FltMgr to tell it our callback routines
        LeaveOnFail(GetRegistryConfigData(RegistryPath));
        LeaveOnFail(CreateCommunicationPort());
        LeaveOnFail(FltStartFiltering(secretStashConfig.Filter));
    }
    finally
    {
        if (!NT_SUCCESS(status))
        {
            if (secretStashConfig.ComPortConfig.ServerPort != NULL)
                FltCloseCommunicationPort(secretStashConfig.ComPortConfig.ServerPort);

            if (secretStashConfig.Filter != NULL)
                FltUnregisterFilter(secretStashConfig.Filter);
        }
    }

    return status;
}
Exemplo n.º 3
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  Description :
//	Unregisters the minifilter.
//	Parameters :
//	Return value :
//	Process :
//		Closes filter communication port and unregisters the filter.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
NTSTATUS UnregisterFilter(FLT_FILTER_UNLOAD_FLAGS flags)
{
	FltCloseCommunicationPort(serverPort);
	
	if(filter!=NULL)
		FltUnregisterFilter(filter);
	
	return STATUS_FLT_DO_NOT_DETACH;
}
Exemplo n.º 4
0
/*
* 函数说明:
*		卸载通讯模块
*
* 参数:
*		无
*
* 返回值:
*		无
*
* 备注:
*
*/
VOID
	CComm::Unload()
{
	KdPrintKrnl(LOG_PRINTF_LEVEL_INFO, LOG_RECORED_LEVEL_NEED, L"begin");

	if (!ms_CommInfo.pSeverPort)
		KdPrintKrnl(LOG_PRINTF_LEVEL_ERROR, LOG_RECORED_LEVEL_NEED, L"need not unload");
	else
	{
		FltCloseCommunicationPort(ms_CommInfo.pSeverPort);
		ms_CommInfo.pSeverPort = NULL;
	}

	KdPrintKrnl(LOG_PRINTF_LEVEL_INFO, LOG_RECORED_LEVEL_NEED, L"end");
}
Exemplo n.º 5
0
/*
 * LockerUnload
 *
 * This is the unload routine for the Filter driver, which we hooked in when we
 * called FltRegisterFilter.  See PFLT_FILTER_UNLOAD_CALLBACK:
 *
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff551085(v=vs.85).aspx
 *
 * It unregisters the filter from the filter manager, and frees any allocated
 * global data structures.  This means we can stop and delete this service without
 * rebooting, which is made possible by hooking in underneath the FilterManager
 * (by contrast, that manager is a legacy File System Filter Driver...so it cannot
 * itself be safely unloaded without rebooting).
 *
 * Returns the final status of the deallocation routines.
 */
NTSTATUS
LockerUnload(
    __in FLT_FILTER_UNLOAD_FLAGS Flags
   )
{
    UNREFERENCED_PARAMETER(Flags);

    // Close the server port.
    FltCloseCommunicationPort(Globals.ServerPort);

    // Unregister the filter
    FltUnregisterFilter(Globals.Filter);

    return STATUS_SUCCESS;
}
Exemplo n.º 6
0
/*---------------------------------------------------------
函数名称:	Antinvader_Unload
函数描述:	卸载驱动程序,关闭通信端口
输入参数:
			Flags	卸载标志
输出参数:
返回值:
			STATUS_SUCCESS 成功
其他:
更新维护:	2011.3.20    最初版本
---------------------------------------------------------*/
NTSTATUS
Antinvader_Unload (
    __in FLT_FILTER_UNLOAD_FLAGS Flags
)
{
    UNREFERENCED_PARAMETER( Flags );

    PAGED_CODE();

    DebugTrace(DEBUG_TRACE_LOAD_UNLOAD,"Unload",
               ("Entered."));

    //
    //关闭通信端口
    //

    if(pfpGlobalServerPort) {
        DebugTrace(DEBUG_TRACE_LOAD_UNLOAD,"Unload",
                   ("Closing communication port....0x%X",pfpGlobalServerPort));
        FltCloseCommunicationPort( pfpGlobalServerPort );
    }

    //
    //卸载过滤
    //

    if(pfltGlobalFilterHandle) {
        DebugTrace(DEBUG_TRACE_LOAD_UNLOAD,"Unload",
                   ("Unregistering filter....0x%X",pfltGlobalFilterHandle));
        FltUnregisterFilter( pfltGlobalFilterHandle );
    }

    //
    //销毁释放所有表格 资源 旁视链表等
    //
    PctFreeTable();

//	ExDeleteNPagedLookasideList(&nliCallbackContextLookasideList);
//	ExDeleteNPagedLookasideList(&nliFileStreamContextLookasideList);

    ExDeleteNPagedLookasideList(&nliNewFileHeaderLookasideList);

    DebugTrace(DEBUG_TRACE_LOAD_UNLOAD,"Unload",
               ("All succeed.Leave now."));

    return STATUS_SUCCESS;
}
Exemplo n.º 7
0
NTSTATUS SecretStashUnload(FLT_FILTER_UNLOAD_FLAGS Flags)
{
    UNREFERENCED_PARAMETER(Flags);

    PAGED_CODE();

    DBG_PRINT("SecretStash!SecretStashUnload: Entered\n");

    FltCloseCommunicationPort(secretStashConfig.ComPortConfig.ServerPort);

    if (secretStashConfig.RegDataLoaded)
        DestroyFolderVector(&secretStashConfig.FolderVector);

    FltUnregisterFilter(secretStashConfig.Filter);

    return STATUS_SUCCESS;
}
Exemplo n.º 8
0
/* 
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 *
 *
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 */
NTSTATUS
cfsd_Unload( FLT_FILTER_UNLOAD_FLAGS theFlags )

{
 UNREFERENCED_PARAMETER( theFlags );


// *** ENABLE THIS IS YOU DO NOT WANT THE DRIVER TO EVER BE UNLOADED and 
// SET FLTFL_REGISTRATION_DO_NOT_SUPPORT_SERVICE_STOP in FLT_REGISTRATION ALSO ***
//return STATUS_FLT_DO_NOT_DETACH;


#if ENABLE_USER_INTERFACE
 DBG_PRINT( DbgOutput, DBG_USERMODE, (PRINT_TAG_USERMODE "Closing ServerPort 0x%X\n",gUserModeConnection.ServerPort ) );

   FltCloseCommunicationPort( gUserModeConnection.ServerPort );
#endif // End #if ENABLE_USER_INTERFACE


   // DDK : "...Unregister itself so that the Filter Manager no longer calls it to 
   //        process I/O operations. "
   FltUnregisterFilter( gFilterPointer );

   // Release our hidden data memory
   ExFreePoolWithTag( gFileData, 'parC' );

#if FILTER_IRP_MJ_CREATE
   // Release our attach method data memory
   ExFreePoolWithTag( gProtectedData, 'parC' );
#endif

   // Release our attach method data memory
   ExFreePoolWithTag( gAttachRequirements, 'parC' );


 return STATUS_SUCCESS;
}
Exemplo n.º 9
0
NTSTATUS
claimsmanUnload(
_In_ FLT_FILTER_UNLOAD_FLAGS Flags
)
/*++

Routine Description:

This is the unload routine for this miniFilter driver. This is called
when the minifilter is about to be unloaded. We can fail this unload
request if this is not a mandatory unload indicated by the Flags
parameter.

Arguments:

Flags - Indicating if this is a mandatory unload.

Return Value:

Returns STATUS_SUCCESS.

--*/
{
	UNREFERENCED_PARAMETER(Flags);

	PAGED_CODE();

	PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
		("claimsman!claimsmanUnload: Entered\n"));

	FltCloseCommunicationPort(ClaimsmanData.ServerPort);
	FltUnregisterFilter(ClaimsmanData.Filter);
	ClaimsmanFreeExtensions();
	ClaimsmanFreeIgnoredUsers();

	return STATUS_SUCCESS;
}
Exemplo n.º 10
0
/* 
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 *
 *
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 */
NTSTATUS
cfsd_Unload( FLT_FILTER_UNLOAD_FLAGS theFlags )

{
 UNREFERENCED_PARAMETER( theFlags );

#if ENABLE_USER_INTERFACE
 KdPrint( (PRINT_TAG "Closing ServerPort 0x%X\n",gUserModeConnection.ServerPort ) );

   FltCloseCommunicationPort( gUserModeConnection.ServerPort );
#endif

   // DDK : "...Unregister itself so that the Filter Manager no longer calls it to 
   //        process I/O operations. "
   FltUnregisterFilter( gFilterPointer );

   // Release our hidden data memory
   ExFreePoolWithTag( gHiddenData, 'parC' );

   // Release our attach method data memory
   ExFreePoolWithTag( gAttachRequirements, 'parC' );

 return STATUS_SUCCESS;
}
Exemplo n.º 11
0
NTSTATUS
DriverEntry (
    __in PDRIVER_OBJECT DriverObject,
    __in PUNICODE_STRING RegistryPath
    )
{
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING uniString;
    PSECURITY_DESCRIPTOR sd;
    NTSTATUS status;

    UNREFERENCED_PARAMETER( RegistryPath );
	
	//Timeouts hardcoded for now
	FilterConf.ReadTimeout.QuadPart = (LONGLONG) - 30 * 1000 * 1000;  //3 seconds
	FilterConf.WriteTimeout.QuadPart = (LONGLONG) - 1500 * 1000 * 1000;  //150 seconds


#ifdef DBG_PRINT
	DbgPrint("In DriverEntry");
#endif

    status = FltRegisterFilter( DriverObject,
                                &FilterRegistration,
                                &FilterConf.Filter );


    if (!NT_SUCCESS( status )) {

        return status;
    }

    RtlInitUnicodeString( &uniString, MyDLPMFPortName );

    status = FltBuildDefaultSecurityDescriptor( &sd, FLT_PORT_ALL_ACCESS );

    if (NT_SUCCESS( status )) {

        InitializeObjectAttributes( &oa,
                                    &uniString,
                                    OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                    NULL,
                                    sd );

        status = FltCreateCommunicationPort( FilterConf.Filter,
                                             &FilterConf.ServerPort,
                                             &oa,
                                             NULL,
                                             MyDLPMFPortConnect,
                                             MyDLPMFPortDisconnect,
                                             NULL,
                                             1 );
    
        FltFreeSecurityDescriptor( sd );

        if (NT_SUCCESS( status )) {

			writeNotification = ExAllocatePoolWithTag( NonPagedPool,
                                          sizeof( MYDLPMF_WRITE_NOTIFICATION ),
                                          'mdlp' );
			if (writeNotification == NULL)
			{
#ifdef DBG_PRINT
				DbgPrint("ExAllocatePoolWithTag failed for writeNotification!!!");
#endif
				FltCloseCommunicationPort( FilterConf.ServerPort );
				FltUnregisterFilter( FilterConf.Filter );
				return status;
            }
			
			fileNotification = ExAllocatePoolWithTag( NonPagedPool,
                                          sizeof( MYDLPMF_FILE_NOTIFICATION ),
                                          'mdlp' );
			if (fileNotification == NULL)
			{
#ifdef DBG_PRINT
				DbgPrint("ExAllocatePoolWithTag failed for fileNotification!!!");
#endif
				FltCloseCommunicationPort( FilterConf.ServerPort );
				FltUnregisterFilter( FilterConf.Filter );
				return status;
            }

			notification = ExAllocatePoolWithTag( NonPagedPool,
                                          sizeof( MYDLPMF_NOTIFICATION ),
                                          'mdlp' );
			if (notification == NULL)
			{
#ifdef DBG_PRINT
				DbgPrint("ExAllocatePoolWithTag failed for notification!!!");
#endif
				FltCloseCommunicationPort( FilterConf.ServerPort );
				FltUnregisterFilter( FilterConf.Filter );
				return status;
            }

#ifdef DBG_PRINT
				DbgPrint("ExAllocatePoolWithTag success for notification!!!");
#endif
			reply = ExAllocatePoolWithTag( NonPagedPool,
                                          sizeof( MYDLPMF_REPLY ) + sizeof (FILTER_REPLY_HEADER),
                                          'mdlp' );
			if (reply == NULL)
			{
#ifdef DBG_PRINT
				DbgPrint("ExAllocatePoolWithTag failed for reply!!!");
#endif
				FltCloseCommunicationPort( FilterConf.ServerPort );
				FltUnregisterFilter( FilterConf.Filter );
				return status;
            }


			confReply = ExAllocatePoolWithTag( NonPagedPool,
                                          sizeof( MYDLPMF_CONF_REPLY ) + sizeof (FILTER_REPLY_HEADER),
                                          'mdlp' );
			if (confReply == NULL)
			{
#ifdef DBG_PRINT
				DbgPrint("ExAllocatePoolWithTag failed for confReply!!!");
#endif
				FltCloseCommunicationPort( FilterConf.ServerPort );
				FltUnregisterFilter( FilterConf.Filter );
				return status;
            }        
        
            status = FltStartFiltering( FilterConf.Filter );

            if (NT_SUCCESS( status )) {

				return STATUS_SUCCESS;
			}	
			
			FltCloseCommunicationPort( FilterConf.ServerPort );
		}			
    }

    FltUnregisterFilter( FilterConf.Filter );

    return status;
}
Exemplo n.º 12
0
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
/*++

Routine Description:

This is the initialization routine for this miniFilter driver.  This
registers with FltMgr and initializes all global data structures.

Arguments:

DriverObject - Pointer to driver object created by the system to
represent this driver.

RegistryPath - Unicode string identifying where the parameters for this
driver are located in the registry.

Return Value:

Routine can return non success error codes.

--*/
{
	NTSTATUS status;
	OBJECT_ATTRIBUTES oa;
	PSECURITY_DESCRIPTOR sd;
	UNICODE_STRING uniString;

	//UNREFERENCED_PARAMETER(RegistryPath);

	PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
		("claimsman!DriverEntry: Entered\n"));

	//
	//  Default to NonPagedPoolNx for non paged pool allocations where supported.
	//

	ExInitializeDriverRuntime(DrvRtPoolNxOptIn);

	//
	// Obtain the extensions to monitor from the registry
	//

	status = InitializeMonitoredExtensions(RegistryPath);

	if (!NT_SUCCESS(status)) {

		status = STATUS_SUCCESS;

		ClaimsmanData.MonitoredExtensions = &MonitoredExtensionDefault;
		ClaimsmanData.MonitoredExtensionCount = 1;
	}

	//
	// Obtain the ignored users from the registry
	//

	status = InitializeIgnoredUsers(RegistryPath);

	if (!NT_SUCCESS(status)) {

		status = STATUS_SUCCESS;

		ClaimsmanData.IgnoredUsers = &MonitoredExtensionDefault;
		ClaimsmanData.IgnoredUserCount = 1;
	}


	//
	//  Register with FltMgr to tell it our callback routines
	//

	status = FltRegisterFilter(DriverObject,
		&FilterRegistration,
		&ClaimsmanData.Filter);

	if (!NT_SUCCESS(status)) {
		return status;
	}

	//
	// Initialize communication port
	//

	RtlInitUnicodeString(&uniString, ClaimsmanPortName);

	//  Only ADMINs & SYSTEM can access the port

	status = FltBuildDefaultSecurityDescriptor(&sd, FLT_PORT_ALL_ACCESS);

	if (NT_SUCCESS(status)) {
		InitializeObjectAttributes(&oa,
			&uniString,
			OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
			NULL,
			sd);


		status = FltCreateCommunicationPort(ClaimsmanData.Filter,
			&ClaimsmanData.ServerPort,
			&oa,
			NULL,
			ClaimsmanConnect,
			ClaimsmanDisconnect,
			NULL,
			1);

		// Not needed anymore 
		FltFreeSecurityDescriptor(sd);

		if (!NT_SUCCESS(status)) {
			PT_DBG_PRINT(PTDBG_TRACE_ROUTINES,
				("claimsman!DriverEntry: Unable to create communication port: %d\n", status));
		}
		else {
			//
			//  Start filtering I/O.
			//

			status = FltStartFiltering(ClaimsmanData.Filter);

			if (!NT_SUCCESS(status)) {
				FltUnregisterFilter(ClaimsmanData.Filter);
				FltCloseCommunicationPort(ClaimsmanData.ServerPort);
			}
		}
	}

	return status;
}
Exemplo n.º 13
0
/* 
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 *
 *
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 */
NTSTATUS
DriverEntry( IN PDRIVER_OBJECT theDriverObject,
             IN PUNICODE_STRING theRegistryPath )

{
NTSTATUS              Status; 
PSECURITY_DESCRIPTOR  SecurityDescriptor;
OBJECT_ATTRIBUTES     ObjectAttributes;
UNICODE_STRING        uPortName;


    // Open the registry and read in all the setting we will use in kernel mode
    EnumerateRegistryValues( theRegistryPath );

   // DDK : "...Add itself to the global list of registered minifilters and to provide 
   //        the Filter Manager with a list of callback functions and other information 
   //        about the minifilter."
   Status = FltRegisterFilter( theDriverObject,
                               &cfsd_FilterRegistration,
                               &gFilterPointer );

    if ( NT_SUCCESS( Status ) )
    {

#if ENABLE_USER_INTERFACE

     Status  = FltBuildDefaultSecurityDescriptor( &SecurityDescriptor,
                                                  FLT_PORT_ALL_ACCESS );

     if ( NT_SUCCESS( Status ) ) 
     {

      RtlInitUnicodeString( &uPortName, USER_COMMUNICATION_PORT_NAME );

      InitializeObjectAttributes( &ObjectAttributes,
                                  &uPortName,
                                  OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                  NULL,
                                  SecurityDescriptor );

 KdPrint( (PRINT_TAG "Attempting to create Communication Port for user mode access\n") );

        Status = FltCreateCommunicationPort( gFilterPointer,                 // Filter
                                             &gUserModeConnection.ServerPort,// *ServerPort
                                             &ObjectAttributes,              // ObjectAttributes
                                             NULL,                           // ServerPortCookie
                                             cfsd_UserModeConnect,           // ConnectNotifyCallback
                                             cfsd_UserModeDisconnect,        // DisconnectNotifyCallback
                                             cfsd_UserModeCommunication,     // MessageNotifyCallback
                                             1 );                            // MaxConnections

        FltFreeSecurityDescriptor( SecurityDescriptor );

        // If we failed to create a communications port then we are going to fail the driver
        if ( !NT_SUCCESS( Status ) ) 
        {
 KdPrint( (PRINT_TAG "Failed FltCreateCommunicationPort() with NTSTATUS 0x%x\n",Status ) );

         // Release our hidden data memory
         ExFreePoolWithTag( gHiddenData, 'parC' );

         return Status;
        }

 KdPrint( (PRINT_TAG "Created ServerPort 0x%X\n", gUserModeConnection.ServerPort ) );

     }

#endif
     // DDK : "...Notifies the Filter Manager that the minifilter is ready to 
     //        begin attaching to volumes and filtering I/O requests"
     Status = FltStartFiltering( gFilterPointer );

     if ( !NT_SUCCESS( Status )) 
     {

#if ENABLE_USER_INTERFACE
      FltCloseCommunicationPort( gUserModeConnection.ServerPort );
#endif
      // If we failed FltStartFiltering() then we unregister ourself with the Filter Manager 
      // so that we no longer recieve calls to process I/O operations.
      FltUnregisterFilter( gFilterPointer );

      // Release our hidden data memory
      ExFreePoolWithTag( gHiddenData, 'parC' );
     }
    }

 return Status;
}
Exemplo n.º 14
0
NTSTATUS
DriverEntry (
    __in PDRIVER_OBJECT DriverObject,
    __in PUNICODE_STRING RegistryPath
    )
/*++

Routine Description:

    This is the initialization routine for the Filter driver.  This
    registers the Filter with the filter manager and initializes all
    its global data structures.

Arguments:

    DriverObject - Pointer to driver object created by the system to
        represent this driver.

    RegistryPath - Unicode string identifying where the parameters for this
        driver are located in the registry.

Return Value:

    Returns STATUS_SUCCESS.
--*/
{
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING uniString;
    PSECURITY_DESCRIPTOR sd;
    NTSTATUS status;

    UNREFERENCED_PARAMETER( RegistryPath );

    //
    //  向过滤管理器注册过滤器
    //

    status = FltRegisterFilter( DriverObject,
                                &FilterRegistration,
                                &ScannerData.Filter );


    if (!NT_SUCCESS( status )) {

        return status;
    }

    //
	//  创建一个通信端口
    //

    RtlInitUnicodeString( &uniString, ScannerPortName );

    //
    //  We secure the port so only ADMINs & SYSTEM can acecss it.
	//	我们设置只有管理员权限用户与SYSTEM用户权限的程序可以接入这个端口
    //

    status = FltBuildDefaultSecurityDescriptor( &sd, FLT_PORT_ALL_ACCESS );

    if (NT_SUCCESS( status )) {

        InitializeObjectAttributes( &oa,
                                    &uniString,
                                    OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                    NULL,
                                    sd );

        status = FltCreateCommunicationPort( ScannerData.Filter,
                                             &ScannerData.ServerPort,
                                             &oa,
                                             NULL,
                                             ScannerPortConnect,
                                             ScannerPortDisconnect,
                                             NULL,
                                             1 );
        //
		//	当调用FltCreateCommunicationPort()后,安全描述符已经没有需要了,应当释放掉。
        //

        FltFreeSecurityDescriptor( sd );

        if (NT_SUCCESS( status )) {

            //
			//	开始过滤IO
            //

            status = FltStartFiltering( ScannerData.Filter );

            if (NT_SUCCESS( status )) {

                return STATUS_SUCCESS;
            }

            FltCloseCommunicationPort( ScannerData.ServerPort );
        }
    }

    FltUnregisterFilter( ScannerData.Filter );

    return status;
}
Exemplo n.º 15
0
/*
* 函数说明:
*		初始化通讯
*
* 参数:
*		pFlt
*                           
* 返回值:
*		TRUE	成功
*		FALSE	失败
*
* 备注:
*
*/
BOOLEAN
	CComm::Init(
	__in PFLT_FILTER pFlt
	)
{
	BOOLEAN					bRet		= FALSE;

	CKrnlStr				PortName;

	NTSTATUS				ntStatus	= STATUS_UNSUCCESSFUL;
	PSECURITY_DESCRIPTOR	pSd			= NULL;
	OBJECT_ATTRIBUTES		Ob			= {0};

	CLog					Log;


	KdPrintKrnl(LOG_PRINTF_LEVEL_INFO, LOG_RECORED_LEVEL_NEED, L"begin");

	__try
	{
		if (!pFlt)
		{
			KdPrintKrnl(LOG_PRINTF_LEVEL_ERROR, LOG_RECORED_LEVEL_NEED, L"input argument error");
			__leave;
		}

		if (CMinifilter::ms_pMfIns->CheckEnv(MINIFILTER_ENV_TYPE_FLT_FILTER) && ms_CommInfo.pSeverPort)
		{
			KdPrintKrnl(LOG_PRINTF_LEVEL_ERROR, LOG_RECORED_LEVEL_NEED, L"already init");
			__leave;
		}

		if (!PortName.Set(g_lpCommPortName, wcslen(g_lpCommPortName)))
		{
			KdPrintKrnl(LOG_PRINTF_LEVEL_ERROR, LOG_RECORED_LEVEL_NEED, L"PortName.Set failed");
			__leave;
		}

		ntStatus = FltBuildDefaultSecurityDescriptor(&pSd, FLT_PORT_ALL_ACCESS);
		if (!NT_SUCCESS(ntStatus))
		{
			KdPrintKrnl(LOG_PRINTF_LEVEL_ERROR, LOG_RECORED_LEVEL_NEED, L"FltBuildDefaultSecurityDescriptor failed. (%x)",
				ntStatus);

			__leave;
		}

		InitializeObjectAttributes(
			&Ob,
			PortName.Get(),
			OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
			NULL,
			pSd
			);

		ntStatus = FltCreateCommunicationPort(
			pFlt,
			&ms_CommInfo.pSeverPort,
			&Ob,
			NULL,
			(PFLT_CONNECT_NOTIFY)CommKmConnectNotify,
			(PFLT_DISCONNECT_NOTIFY)CommKmDisconnectNotify,
			(PFLT_MESSAGE_NOTIFY)CommKmMessageNotify,
			1
			);
		if (!NT_SUCCESS(ntStatus))
		{
			KdPrintKrnl(LOG_PRINTF_LEVEL_ERROR, LOG_RECORED_LEVEL_NEED, L"FltCreateCommunicationPort failed. (%x)",
				ntStatus);

			__leave;
		}

		bRet = TRUE;
	}
	__finally
	{
		if (pSd)
		{
			FltFreeSecurityDescriptor(pSd);
			pSd = NULL;
		}

		if (!bRet)
		{
			if (ms_CommInfo.pSeverPort)
			{
				FltCloseCommunicationPort(ms_CommInfo.pSeverPort);
				ms_CommInfo.pSeverPort = NULL;
			}
		}
	}
	
	KdPrintKrnl(LOG_PRINTF_LEVEL_INFO, LOG_RECORED_LEVEL_NEED, L"end");

	return bRet;
}
Exemplo n.º 16
0
/*---------------------------------------------------------
函数名称:	DriverEntry
函数描述:	驱动程序入口,注册微过滤驱动,通信端口
输入参数:
			DriverObject 驱动对象
			RegistryPath 驱动路径
输出参数:
			DriverObject 驱动对象
返回值:
			STATUS_SUCCESSFUL 为成功否则返回失败状态值
其他:
更新维护:	2011.3.20    最初版本
---------------------------------------------------------*/
NTSTATUS DriverEntry(
    __inout PDRIVER_OBJECT   DriverObject,
    __in PUNICODE_STRING      RegistryPath
)
{
    DebugTrace(DEBUG_TRACE_LOAD_UNLOAD,"DriverEntry",
               ("[Antinvader]DriverEntry Enter."));

    //返回值
    NTSTATUS status = STATUS_SUCCESS;

    //初始化数据返回值
    BOOLEAN bReturn = 0;

    //安全性叙述子
    PSECURITY_DESCRIPTOR psdSecurityDescriptor;

    //对象权限结构
    OBJECT_ATTRIBUTES	oaObjectAttributes;

    //保存全局驱动对象
    pdoGlobalDrvObj = DriverObject;

    //
    //注册过滤驱动
    //

    if(NT_SUCCESS(status = FltRegisterFilter(
                               DriverObject,//驱动对象
                               &FilterRegistration,//驱动注册信息
                               &pfltGlobalFilterHandle//驱动句柄,保存到全局变量
                           ))) {

        //
        //如果成功了 启动过滤
        //
        DebugTrace(DEBUG_TRACE_NORMAL_INFO,"DriverEntry",
                   ("[Antinvader]Register succeed!"));

        if(!NT_SUCCESS(status = FltStartFiltering(
                                    pfltGlobalFilterHandle
                                ))) {
            //
            //如果启动失败 卸载驱动
            //

            DebugTrace(DEBUG_TRACE_ERROR,"DriverEntry",
                       ("[Antinvader]Starting filter failed."));

            FltUnregisterFilter(pfltGlobalFilterHandle);
            return status;
        }

    } else {
        //
        //如果连注册都没有成功 返回错误码
        //
        DebugTrace(DEBUG_TRACE_ERROR,"DriverEntry",
                   ("[Antinvader]Register failed."));
        return status;
    }

    //
    //建立通信端口
    //

    //
    //初始化安全性叙述子,权限为FLT_PORT_ALL_ACCESS
    //

    status  = FltBuildDefaultSecurityDescriptor(
                  &psdSecurityDescriptor,
                  FLT_PORT_ALL_ACCESS );

    if (!NT_SUCCESS( status )) {
        //
        //如果初始化失败 ,卸载驱动
        //
        DebugTrace(DEBUG_TRACE_ERROR,"DriverEntry",
                   ("[Antinvader]Built security descriptor failed."));

        FltUnregisterFilter( pfltGlobalFilterHandle );

        //
        //返回信息
        //
        return status;
    }

    //初始化对象权限结构
    InitializeObjectAttributes( &oaObjectAttributes,//结构
                                &usCommunicatePortName,//对象名称
                                OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,//内核句柄 大小写不敏感
                                NULL,
                                psdSecurityDescriptor );

    //创建通信端口
    status = FltCreateCommunicationPort( pfltGlobalFilterHandle,//过滤驱动句柄
                                         &pfpGlobalServerPort,//服务端端口
                                         &oaObjectAttributes,//权限
                                         NULL,
                                         Antinvader_Connect,
                                         Antinvader_Disconnect,
                                         Antinvader_Message,
                                         1//最大连接数
                                       );

    //释放安全性叙述子
    FltFreeSecurityDescriptor( psdSecurityDescriptor );

    if (!NT_SUCCESS( status )) {

        //
        //如果最终的操作失败 释放已经申请的资源
        //

        DebugTrace(DEBUG_TRACE_ERROR,"DriverEntry",
                   ("[Antinvader]Creating communication port failed."));

        if (NULL != pfpGlobalServerPort) {
            FltCloseCommunicationPort( pfpGlobalServerPort );
        }

        if (NULL != pfltGlobalFilterHandle) {
            FltUnregisterFilter( pfltGlobalFilterHandle );
        }
    }

    //
    //初始化进程名偏移
    //

    InitProcessNameOffset();

//	FctInitializeHashTable();

    //
    //初始化机密进程表
    //
    PctInitializeHashTable();

    //
    //初始化旁视链表
    //
    ExInitializeNPagedLookasideList(
        &nliNewFileHeaderLookasideList,
        NULL,
        NULL,
        0,
        CONFIDENTIAL_FILE_HEAD_SIZE,
        MEM_FILE_TAG,
        0
    );
    /*
    	ExInitializeNPagedLookasideList(
    		&nliCallbackContextLookasideList,
    		NULL,
    		NULL,
    		0,
    		sizeof(_POST_CALLBACK_CONTEXT),
    		MEM_CALLBACK_TAG,
    		0
    		);

    	ExInitializeNPagedLookasideList(
    		&nliFileStreamContextLookasideList,
    		NULL,
    		NULL,
    		0,
    		FILE_STREAM_CONTEXT_SIZE,
    		MEM_TAG_FILE_TABLE,
    		0
    		);*/

    //
    //结束
    //
    DebugTrace(DEBUG_TRACE_LOAD_UNLOAD,"DriverEntry",
               ("[Antinvader]DriverEntry all succeed leave now."));
    return status;
}
Exemplo n.º 17
0
/*	Main entry point into the driver, is called when the driver is loaded */
NTSTATUS DriverEntry(
	IN PDRIVER_OBJECT DriverObject, 
	IN PUNICODE_STRING RegistryPath
	)
{
	NTSTATUS status;
	OBJECT_ATTRIBUTES objectAttributes;
	PSECURITY_DESCRIPTOR pSecurityDescriptor;
	UNICODE_STRING fileMonitorPortName;
	LARGE_INTEGER fileEventsTimeout;
	busy = FALSE;
	fileManager.bReady = FALSE;
	fileManager.bCollectDeletedFiles = FALSE;
	KeInitializeSpinLock(&fileManager.lQueuedFileEventsSpinLock);
	InitializeListHead(&fileManager.lQueuedFileEvents);
	fileManager.pDriverObject = DriverObject;
	//fileManager.logDirectory.Buffer = NULL;

	/* Register driver with the filter manager */
	status = FltRegisterFilter(DriverObject, &FilterRegistration, &fileManager.pFilter);

	if (!NT_SUCCESS(status))
	{
		DbgPrint("CaptureFileMonitor: ERROR FltRegisterFilter - %08x\n", status); 
		return status;
	}

	status  = FltBuildDefaultSecurityDescriptor( &pSecurityDescriptor, FLT_PORT_ALL_ACCESS );

	if (!NT_SUCCESS(status))
	{
		DbgPrint("CaptureFileMonitor: ERROR FltBuildDefaultSecurityDescriptor - %08x\n", status);
		return status;
	}

	RtlInitUnicodeString( &fileMonitorPortName, CAPTURE_FILEMON_PORT_NAME );
	InitializeObjectAttributes( &objectAttributes,
								&fileMonitorPortName,
								OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
								NULL,
								pSecurityDescriptor);

	/* Create the communications port to communicate with the user space process (pipe) */
	status = FltCreateCommunicationPort( fileManager.pFilter,
                                             &fileManager.pServerPort,
                                             &objectAttributes,
                                             NULL,
                                             ConnectCallback,
                                             DisconnectCallback,
                                             MessageCallback,
                                             1 );

	FltFreeSecurityDescriptor(pSecurityDescriptor);

	/* Start the filtering */
	if(NT_SUCCESS(status))
	{
		status = FltStartFiltering(fileManager.pFilter);
		if(!NT_SUCCESS(status))
		{
			DbgPrint("CaptureFileMonitor: ERROR FltStartFiltering - %08x\n", status);
		}
	} else {
		DbgPrint("CaptureFileMonitor: ERROR FltCreateCommunicationPort - %08x\n", status);
	}

	/* If there was a problem during initialisation of the filter then uninstall everything */
	if(!NT_SUCCESS(status))
	{
		if (fileManager.pServerPort != NULL)
			FltCloseCommunicationPort(fileManager.pServerPort);
		if (fileManager.pFilter != NULL)
			FltUnregisterFilter(fileManager.pFilter);
		return status;
	}

	UpdateLastContactTime();

	/* Create a DPC routine so that it can be called periodically */
	KeInitializeDpc(&fileManager.connectionCheckerFunction, 
		(PKDEFERRED_ROUTINE)ConnectionChecker, &fileManager);
	KeInitializeTimer(&fileManager.connectionCheckerTimer);
	fileEventsTimeout.QuadPart = 0;

	/* Set the ConnectionChecker routine to be called every so often */
	KeSetTimerEx(&fileManager.connectionCheckerTimer, 
		fileEventsTimeout, 
		(USERSPACE_CONNECTION_TIMEOUT+(USERSPACE_CONNECTION_TIMEOUT/2))*1000, 
		&fileManager.connectionCheckerFunction);

	fileManager.bReady = TRUE;
	fileManager.logDirectory.Length = 0;
	fileManager.logDirectory.Buffer = NULL;
	DbgPrint("CaptureFileMonitor: Successfully Loaded\n");

	return STATUS_SUCCESS;
}
Exemplo n.º 18
0
NTSTATUS
DriverEntry (
			 __in PDRIVER_OBJECT DriverObject,
			 __in PUNICODE_STRING RegistryPath
			 )
			 /*++

			 Routine Description:

			 This is the initialization routine for this miniFilter driver.  This
			 registers with FltMgr and initializes all global data structures.

			 Arguments:

			 DriverObject - Pointer to driver object created by the system to
			 represent this driver.

			 RegistryPath - Unicode string identifying where the parameters for this
			 driver are located in the registry.

			 Return Value:

			 Returns STATUS_SUCCESS.

			 --*/
{
	NTSTATUS status;
	BOOLEAN bInit = FALSE;

	PSECURITY_DESCRIPTOR sd;
	OBJECT_ATTRIBUTES oa;
	UNICODE_STRING uniString;

	UNREFERENCED_PARAMETER( RegistryPath );

	PT_DBG_PRINT( PTDBG_TRACE_ROUTINES,
		("PassThrough!DriverEntry: Entered\n") );
	try
	{
		status = FltRegisterFilter( DriverObject,
			&FilterRegistration,
			&gFilterHandle );

		if (!NT_SUCCESS( status ))
		{
			leave;
		}

#ifdef CV
		VirtualizerStart();
#endif
		status = InitDriverEntry( DriverObject,RegistryPath);
#ifdef CV
		VirtualizerEnd();
#endif
		if (!NT_SUCCESS( status ))
		{
			bInit = FALSE;
			leave;
		}
		
		bInit = TRUE;

		status  = FltBuildDefaultSecurityDescriptor( &sd,
			FLT_PORT_ALL_ACCESS );

		if (!NT_SUCCESS( status )) 
		{
			leave;
		}

		RtlInitUnicodeString( &uniString, X70FSD_PORT_NAME );

		InitializeObjectAttributes( &oa,
			&uniString,
			OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
			NULL,
			sd );

		status = FltCreateCommunicationPort( gFilterHandle,
			&gServerPort,
			&oa,
			NULL,
			PtMiniConnect,
			PtMiniDisconnect,
			PtMiniMessage,
			1 );

		FltFreeSecurityDescriptor( sd );

		if (!NT_SUCCESS( status )) 
		{
			leave;
		}

		status = FltStartFiltering( gFilterHandle );

	}
	finally
	{
		if (!NT_SUCCESS( status ) ) 
		{

			if (NULL != gServerPort) 
			{
				FltCloseCommunicationPort( gServerPort);
			}

			if (NULL != gFilterHandle) 
			{
				FltUnregisterFilter( gFilterHandle );
			}
			if(bInit)
			{
				UnloadDriver();
			}
		}
	}
	DbgPrint("status = %x ",status);
	return status;
}
Exemplo n.º 19
0
NTSTATUS
DriverEntry (
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    )
/*++

Routine Description:

    This routine is called when a driver first loads.  Its purpose is to
    initialize global state and then register with FltMgr to start filtering.

Arguments:

    DriverObject - Pointer to driver object created by the system to
        represent this driver.
    RegistryPath - Unicode string identifying where the parameters for this
        driver are located in the registry.

Return Value:

    Status of the operation.

--*/
{
    PSECURITY_DESCRIPTOR sd;
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING uniString;
    NTSTATUS status = STATUS_SUCCESS;

    try {

        //
        // Initialize global data structures.
        //

        MiniSpyData.LogSequenceNumber = 0;
        MiniSpyData.MaxRecordsToAllocate = DEFAULT_MAX_RECORDS_TO_ALLOCATE;
        MiniSpyData.RecordsAllocated = 0;
        MiniSpyData.NameQueryMethod = DEFAULT_NAME_QUERY_METHOD;

        MiniSpyData.DriverObject = DriverObject;

        InitializeListHead( &MiniSpyData.OutputBufferList );
        KeInitializeSpinLock( &MiniSpyData.OutputBufferLock );

        ExInitializeNPagedLookasideList( &MiniSpyData.FreeBufferList,
                                         NULL,
                                         NULL,
                                         0,
                                         RECORD_SIZE,
                                         SPY_TAG,
                                         0 );

#if MINISPY_VISTA

        //
        //  Dynamically import FilterMgr APIs for transaction support
        //

#pragma warning(push)
#pragma warning(disable:4055) // type cast from data pointer to function pointer
        MiniSpyData.PFltSetTransactionContext = (PFLT_SET_TRANSACTION_CONTEXT) FltGetRoutineAddress( "FltSetTransactionContext" );
        MiniSpyData.PFltGetTransactionContext = (PFLT_GET_TRANSACTION_CONTEXT) FltGetRoutineAddress( "FltGetTransactionContext" );
        MiniSpyData.PFltEnlistInTransaction = (PFLT_ENLIST_IN_TRANSACTION) FltGetRoutineAddress( "FltEnlistInTransaction" );
#pragma warning(pop)

#endif

        //
        // Read the custom parameters for MiniSpy from the registry
        //

        SpyReadDriverParameters(RegistryPath);

        //
        //  Now that our global configuration is complete, register with FltMgr.
        //

        status = FltRegisterFilter( DriverObject,
                                    &FilterRegistration,
                                    &MiniSpyData.Filter );

        if (!NT_SUCCESS( status )) {

           leave;
        }


        status  = FltBuildDefaultSecurityDescriptor( &sd,
                                                     FLT_PORT_ALL_ACCESS );

        if (!NT_SUCCESS( status )) {
            leave;
        }

        RtlInitUnicodeString( &uniString, MINISPY_PORT_NAME );

        InitializeObjectAttributes( &oa,
                                    &uniString,
                                    OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
                                    NULL,
                                    sd );

        status = FltCreateCommunicationPort( MiniSpyData.Filter,
                                             &MiniSpyData.ServerPort,
                                             &oa,
                                             NULL,
                                             SpyConnect,
                                             SpyDisconnect,
                                             SpyMessage,
                                             1 );

        FltFreeSecurityDescriptor( sd );

        if (!NT_SUCCESS( status )) {
            leave;
        }

        //
        //  We are now ready to start filtering
        //

        status = FltStartFiltering( MiniSpyData.Filter );


		//If all went ok, register a process creation notification cb.
		if (NT_SUCCESS(status))
		{
			status = PsSetCreateProcessNotifyRoutine(ProcessCreationCB, FALSE);
		}

		//If all went ok, register also a register filter.
		if (NT_SUCCESS(status))
		{
			status = CmRegisterCallback(RegistryCallback, NULL, &g_CmCookie);
		}

    } finally {

        if (!NT_SUCCESS( status ) ) {

             if (NULL != MiniSpyData.ServerPort) {
                 FltCloseCommunicationPort( MiniSpyData.ServerPort );
             }

             if (NULL != MiniSpyData.Filter) {
                 FltUnregisterFilter( MiniSpyData.Filter );
             }

             ExDeleteNPagedLookasideList( &MiniSpyData.FreeBufferList );
        }
    }

    return status;
}
Exemplo n.º 20
0
/*
 * DriverEntry
 *
 * Main device driver entry point (the driver equivalent of "WinMain", 'cept for
 * drivers).  This is the first routine called:
 * 
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff557309(v=vs.85).aspx
 *
 * In this specific initialization, we register with something called the
 * "Filter Manager"...which gives us something like an "Application Framework"
 * where much of the boilerplate work is taken care of for us.  Except this is
 * a "Driver Framework", and it allows us to provide only the parts we are
 * interested in writing and accept most of the defaults.  By stylizing our code
 * in this way we are creating something known as a miniFilter:
 *
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff538896(v=vs.85).aspx
 */
NTSTATUS
DriverEntry(
    __in PDRIVER_OBJECT DriverObject,
    __in PUNICODE_STRING RegistryPath
   )
{
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING uniString;
    PSECURITY_DESCRIPTOR sd;
    NTSTATUS status;

    UNREFERENCED_PARAMETER(RegistryPath);

    /*  Register with filter manager. */
    status = FltRegisterFilter(
		DriverObject,
		&FilterRegistration,
		&Globals.Filter
	);


    if (!NT_SUCCESS(status)) {
        return status;
    }

     
    /*  Create a communication port. */
    RtlInitUnicodeString(&uniString, LockerPortName);

    
    /* We secure the port so only ADMINs & SYSTEM can access it. */
    status = FltBuildDefaultSecurityDescriptor(&sd, FLT_PORT_ALL_ACCESS);

    if (NT_SUCCESS(status)) {
        InitializeObjectAttributes(
			&oa,
			&uniString,
			OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
			NULL,
			sd
		);

        status = FltCreateCommunicationPort(
			Globals.Filter,
			&Globals.ServerPort,
			&oa,
			NULL,
			LockerPortConnect,
			LockerPortDisconnect,
			LockerMessage,
			1 /* MaxConnections: Only accept one connection! */
		);

        /*
         * Free the security descriptor in all cases. It is not needed once
         * the call to FltCreateCommunicationPort() is made.
         */
        FltFreeSecurityDescriptor(sd);

        if (NT_SUCCESS(status)) {

            /*
             * Start filtering I/O.  This is blocking, and the minifilter
			 * will keep running until the service is stopped, e.g. with
			 * "SC STOP CloneLocker" at the command line or using a GUI
			 * service manager.
             */
            status = FltStartFiltering(Globals.Filter);

            if (NT_SUCCESS(status)) {
                return STATUS_SUCCESS;
            }

            FltCloseCommunicationPort(Globals.ServerPort);
        }
    }

    FltUnregisterFilter(Globals.Filter);

    return status;
}