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; }
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; }
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; }
/* * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ** * * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ** */ 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; }
NTSTATUS DriverEntry ( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath ) { NTSTATUS status; PSECURITY_DESCRIPTOR sd; OBJECT_ATTRIBUTES oa; UNICODE_STRING uniString; //for communication port name UNREFERENCED_PARAMETER( RegistryPath ); PT_DBG_PRINT( PTDBG_TRACE_ROUTINES, ("NPminifilter!DriverEntry: Entered\n") ); // // Register with FltMgr to tell it our callback routines // status = FltRegisterFilter( DriverObject, &FilterRegistration, &gFilterHandle ); ASSERT( NT_SUCCESS( status ) ); if (NT_SUCCESS( status )) { // // Start filtering i/o // status = FltStartFiltering( gFilterHandle ); if (!NT_SUCCESS( status )) { FltUnregisterFilter( gFilterHandle ); } } //Communication Port status = FltBuildDefaultSecurityDescriptor( &sd, FLT_PORT_ALL_ACCESS ); if (!NT_SUCCESS( status )) { goto final; } status = FltBuildDefaultSecurityDescriptor( &sd, FLT_PORT_ALL_ACCESS ); if (!NT_SUCCESS( status )) { goto final; } RtlInitUnicodeString( &uniString, MINISPY_PORT_NAME ); InitializeObjectAttributes( &oa, &uniString, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, sd ); status = FltCreateCommunicationPort( gFilterHandle, &gServerPort, &oa, NULL, NPMiniConnect, NPMiniDisconnect, NPMiniMessage, 1 ); FltFreeSecurityDescriptor( sd ); if (!NT_SUCCESS( status )) { goto final; } final :
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; }
/*--------------------------------------------------------- 函数名称: 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; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Description : initializes the driver and the filter port, registers driver and registry callbacks. // // Parameters : // _in_ PDRIVER_OBJECT pDriverObject : Data structure used to represent the driver. // _in_ PUNICODE_STRING pRegistryPath : Registry location where the information for the driver // was stored. // Return value : // NTSTATUS : STATUS_SUCCESS if the driver initialization has been well completed // Process : // Defines hidden / blocked processes names. // Creates the device driver and its symbolic link. // Sets IRP callbacks. // Creates filter communication port to send logs from the driver to the userland process. // Creates logs mutex. // Register image load and registry callbacks. ////////////////////////////////////////////////////////////////////////////////////////////////////////////// NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath) { PVOID adrFunc; PDEVICE_OBJECT pDeviceObject; UNICODE_STRING usDriverName; UNICODE_STRING filterPortName; UNICODE_STRING function; OBJECT_ATTRIBUTES objAttr; RTL_OSVERSIONINFOW osInfo; PSECURITY_DESCRIPTOR securityDescriptor; NTSTATUS status; ULONG i; // import some functions we will need RtlInitUnicodeString(&function, L"ZwQueryInformationThread"); ZwQueryInformationThread = MmGetSystemRoutineAddress(&function); RtlInitUnicodeString(&function, L"ZwQueryInformationProcess"); ZwQueryInformationProcess = MmGetSystemRoutineAddress(&function); RtlInitUnicodeString(&function, L"ZwQuerySystemInformation"); ZwQuerySystemInformation = MmGetSystemRoutineAddress(&function); RtlInitUnicodeString(&usDriverName, L"\\Device\\DriverSSDT"); RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\DriverSSDT"); status = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if(!NT_SUCCESS(status)) return status; status = IoCreateSymbolicLink(&usDosDeviceName, &usDriverName); if(!NT_SUCCESS(status)) return status; pDeviceObject->Flags |= DO_BUFFERED_IO; pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING); for(i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++) pDriverObject->MajorFunction[i] = ioctl_NotSupported; pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = ioctl_DeviceControl; monitored_process_list = NULL; hidden_process_list = NULL; monitored_handle_list = NULL; // initialize every function pointers to null oldNtMapViewOfSection = NULL; oldNtSetContextThread = NULL; oldNtCreateThread = NULL; oldNtQueueApcThread = NULL; oldNtCreateProcess = NULL; oldNtSystemDebugControl = NULL; oldNtCreateProcessEx = NULL; oldNtWriteVirtualMemory = NULL; oldNtDebugActiveProcess = NULL; oldNtOpenProcess = NULL; oldNtOpenThread = NULL; oldNtQuerySystemInformation = NULL; oldNtCreateFile = NULL; oldNtReadFile = NULL; oldNtWriteFile = NULL; oldNtDeleteFile = NULL; oldNtSetInformationFile = NULL; oldNtQueryInformationFile = NULL; oldNtCreateMutant = NULL; oldNtDeviceIoControlFile = NULL; oldNtTerminateProcess = NULL; oldNtDelayExecution = NULL; oldNtQueryValueKey = NULL; oldNtQueryAttributesFile = NULL; oldNtReadVirtualMemory = NULL; oldNtResumeThread = NULL; oldNtCreateSection = NULL; oldNtUserCallOneParam = NULL; oldNtUserCallNoParam = NULL; oldNtClose = NULL; oldNtOpenFile = NULL; #ifdef DEBUG DbgPrint("IOCTL_CUCKOO_PATH : 0x%08x\n", IOCTL_CUCKOO_PATH); #endif // get os version if(!NT_SUCCESS(RtlGetVersion(&osInfo))) return status; // check os version if(osInfo.dwMajorVersion == 5 && osInfo.dwMinorVersion == 1) // xp 32 bits { is_xp = 1; #ifdef DEBUG DbgPrint("windows xp !\n"); #endif } else if(osInfo.dwMajorVersion == 6 && osInfo.dwMinorVersion == 1) // win 7 { is_xp = 0; #ifdef DEBUG DbgPrint("windows 7!\n"); #endif } else { #ifdef DEBUG DbgPrint("error : not supported os\n"); #endif return -1; } status = FltRegisterFilter(pDriverObject,®istration,&filter); if(!NT_SUCCESS(status)) return status; RtlInitUnicodeString(&filterPortName, L"\\FilterPort"); status = FltBuildDefaultSecurityDescriptor(&securityDescriptor, FLT_PORT_ALL_ACCESS); if(!NT_SUCCESS(status)) return status; InitializeObjectAttributes(&objAttr, &filterPortName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, securityDescriptor); status = FltCreateCommunicationPort(filter, &serverPort, &objAttr, NULL, ConnectCallback, DisconnectCallback, NULL, 1); FltFreeSecurityDescriptor(securityDescriptor); if(!NT_SUCCESS(status)) return status; KeInitializeMutex(&mutex, 0); status = CmRegisterCallback(regCallback, NULL, &cookie); if(!NT_SUCCESS(status)) return status; status = PsSetLoadImageNotifyRoutine(imageCallback); if(!NT_SUCCESS(status)) return status; KeServiceDescriptorTableShadow = getShadowTableAddress(); if(!KeServiceDescriptorTableShadow) { #ifdef DEBUG DbgPrint("error : couldn't retrieve Shadow SSDT\n"); #endif return STATUS_UNSUCCESSFUL; } pDriverObject->DriverUnload = Unload; return STATUS_SUCCESS; }
/* 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; }
/* * 函数说明: * 初始化通讯 * * 参数: * 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; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Description : initializes the driver and the filter port, registers driver and registry callbacks. // // Parameters : // _in_ PDRIVER_OBJECT pDriverObject : Data structure used to represent the driver. // _in_ PUNICODE_STRING pRegistryPath : Registry location where the information for the driver // was stored. // Return value : // NTSTATUS : STATUS_SUCCESS if the driver initialization has been well completed // Process : // Defines hidden / blocked processes names. // Creates the device driver and its symbolic link. // Sets IRP callbacks. // Creates filter communication port to send logs from the driver to the userland process. // Creates logs mutex. // Hooks SSDT. // Register image load and registry callbacks. ////////////////////////////////////////////////////////////////////////////////////////////////////////////// NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath) { PVOID adrFunc; PDEVICE_OBJECT pDeviceObject; UNICODE_STRING usDriverName; UNICODE_STRING filterPortName; UNICODE_STRING function; OBJECT_ATTRIBUTES objAttr; PSECURITY_DESCRIPTOR securityDescriptor; NTSTATUS status; ULONG i; // import some functions we will need RtlInitUnicodeString(&function, L"ZwQueryInformationThread"); ZwQueryInformationThread = MmGetSystemRoutineAddress(&function); RtlInitUnicodeString(&function, L"ZwQueryInformationProcess"); ZwQueryInformationProcess = MmGetSystemRoutineAddress(&function); RtlInitUnicodeString(&usDriverName, L"\\Device\\DriverSSDT"); RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\DriverSSDT"); status = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if(!NT_SUCCESS(status)) return status; status = IoCreateSymbolicLink(&usDosDeviceName, &usDriverName); if(!NT_SUCCESS(status)) return status; pDeviceObject->Flags |= DO_BUFFERED_IO; pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING); for(i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++) pDriverObject->MajorFunction[i] = ioctl_NotSupported; pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = ioctl_DeviceControl; monitored_process_list = NULL; hidden_process_list = NULL; // initialize every function pointers to null oldZwMapViewOfSection = NULL; oldZwSetContextThread = NULL; oldZwCreateThread = NULL; oldZwQueueApcThread = NULL; oldZwCreateProcess = NULL; oldZwSystemDebugControl = NULL; oldZwCreateProcessEx = NULL; oldZwWriteVirtualMemory = NULL; oldZwDebugActiveProcess = NULL; oldZwOpenProcess = NULL; oldZwOpenThread = NULL; oldZwQuerySystemInformation = NULL; oldZwCreateFile = NULL; oldZwReadFile = NULL; oldZwWriteFile = NULL; oldZwDeleteFile = NULL; oldZwSetInformationFile = NULL; oldZwQueryInformationFile = NULL; oldZwCreateMutant = NULL; status = FltRegisterFilter(pDriverObject,®istration,&filter); if(!NT_SUCCESS(status)) return status; RtlInitUnicodeString(&filterPortName, L"\\FilterPort"); status = FltBuildDefaultSecurityDescriptor(&securityDescriptor, FLT_PORT_ALL_ACCESS); if(!NT_SUCCESS(status)) return status; InitializeObjectAttributes(&objAttr, &filterPortName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, securityDescriptor); status = FltCreateCommunicationPort(filter, &serverPort, &objAttr, NULL, ConnectCallback, DisconnectCallback, NULL, 1); FltFreeSecurityDescriptor(securityDescriptor); if(!NT_SUCCESS(status)) return status; KeInitializeMutex(&mutex, 0); status = CmRegisterCallback(regCallback, NULL, &cookie); if(!NT_SUCCESS(status)) return status; status = PsSetLoadImageNotifyRoutine(imageCallback); if(!NT_SUCCESS(status)) return status; hook_ssdt_entries(); pDriverObject->DriverUnload = Unload; return STATUS_SUCCESS; }
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; }
/* * 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; }
NTSTATUS InitCommunicationPort(_In_ PFLT_FILTER FilterHandle, _Out_ PFLT_PORT *ServerPort){ NTSTATUS ntStatus = STATUS_SUCCESS; OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING PortName;// = RTL_CONSTANT_STRING(L"\\ArmaditoPortScanFilter"); PFLT_PORT LocalServerPort = NULL; PSECURITY_DESCRIPTOR SecurityDescriptor = NULL; // Create Security Descriptor/ //UNREFERENCED_PARAMETER( FilterHandle); //UNREFERENCED_PARAMETER(LocalServerPort ); //UNREFERENCED_PARAMETER( ServerPort); //UNREFERENCED_PARAMETER( ObjectAttributes); //UNREFERENCED_PARAMETER( PortName); __try { //Builds a default security descriptor for use with FltCreateCommunicationPort. ntStatus = FltBuildDefaultSecurityDescriptor(&SecurityDescriptor, FLT_PORT_ALL_ACCESS); if (!NT_SUCCESS(ntStatus)) { DbgPrint("[-] Error :: ArmaditoGuard!InitCommunicationPort :: FltBuildDefaultSecurityDescriptor() routine failed !! \n"); __leave; } ntStatus = RtlSetDaclSecurityDescriptor(SecurityDescriptor, TRUE, NULL, FALSE); if(!NT_SUCCESS(ntStatus)){ DbgPrint("[-] Error :: ArmaditoGuard!InitCommunicationPort :: RtlSetDaclSecurityDescriptor() routine failed !! \n"); __leave; } RtlInitUnicodeString(&PortName, SCAN_PORT_NAME); // Initialize Object Atrtibutes. InitializeObjectAttributes(&ObjectAttributes, &PortName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE ,NULL,SecurityDescriptor); ntStatus = FltCreateCommunicationPort( FilterHandle, // Filter handle &LocalServerPort, // Server port &ObjectAttributes, // ObjectAttributes NULL, // ServerPortCookie. (PFLT_CONNECT_NOTIFY)ConnectNotifyCallback, // Minifilter cals this routine whenever a user-mode apps calls FilterConnectCommunicationPort. (PFLT_DISCONNECT_NOTIFY)DisconnectNotifyCallback, // Minifilter call this routine whenever the user-mode handle count for the client port reached 0; or the minifilter driver is about to unload. (PFLT_MESSAGE_NOTIFY)MessageNotifyCallback, // Minifilter call this routine whenever a user-mode app calls FilterSendMessage to send a message. 1); // MaxConnections if (!NT_SUCCESS(ntStatus)) { DbgPrint("[-] Error :: ArmaditoGuard!InitCommunicationPort :: FltCreateCommunicationPort() routine failed !! \n"); __leave; } // TEST //FltCloseCommunicationPort(LocalServerPort); (*ServerPort) = LocalServerPort; DbgPrint("[+] Debug :: ArmaditoGuard!InitCommunicationPort :: FltCreateCommunicationPort() has succeded :: serverPort = 0x%p. \n",(PVOID)(*ServerPort)); /* if(SecurityDescriptor != NULL){ FltFreeSecurityDescriptor(SecurityDescriptor); } /* DbgPrint("[+] Debug :: ArmaditoGuard!InitCommunicationPort :: FltCreateCommunicationPort() has succeded :: serverPort = 0x%p. \n",(PVOID)(*ServerPort)); */ } __finally { // Free the security descriptor previously allocated if necessary. // if(SecurityDescriptor != NULL){ FltFreeSecurityDescriptor(SecurityDescriptor); DbgPrint("[+] Debug :: ArmaditoGuard!InitCommunicationPort :: Free SecurityDescriptor !!\n"); } } return ntStatus; }