Esempio n. 1
0
void
FileMonitor::setMonitorModifiedFiles(bool monitor)
{
	FILEMONITOR_MESSAGE command;
	FILEMONITOR_SETUP setupFileMonitor;
	HRESULT hResult;
	DWORD bytesReturned;

	monitorModifiedFiles = monitor;

	if(monitor == true)
	{
		setupFileMonitor.bCollectDeletedFiles = TRUE;
	} else {
		setupFileMonitor.bCollectDeletedFiles = FALSE;
	}
	GetFullPathName(L"logs\\deleted_files", 1024, setupFileMonitor.wszLogDirectory, NULL);
	CreateDirectory(setupFileMonitor.wszLogDirectory,NULL);
	setupFileMonitor.nLogDirectorySize = (UINT)wcslen(setupFileMonitor.wszLogDirectory)*sizeof(wchar_t);
	
	DebugPrint(L"Deleted file directory: %i -> %ls\n", setupFileMonitor.nLogDirectorySize, setupFileMonitor.wszLogDirectory);

	command.Command = SetupMonitor;	

	hResult = FilterSendMessage( communicationPort,
							 &command,
							 sizeof( FILEMONITOR_COMMAND ),
							 &setupFileMonitor,
							 sizeof(FILEMONITOR_SETUP),
							 &bytesReturned );
}
Esempio n. 2
0
PPH_STRING KhspQueryFileName(
	_In_ LONGLONG ScanId,
	_In_ USHORT FileNameLength)
{
	HRESULT result;
	PWCHAR buffer;
	DWORD bytesReturned;
	PPH_STRING fileName;

	struct
	{
		ULONG Command;
		LONGLONG ScanId;
	} input = { HsCmdQueryFileName, ScanId };

	buffer = PhAllocate(FileNameLength);

	result = FilterSendMessage(
		HsKhsPortHandle,
		&input,
		sizeof(input),
		buffer,
		FileNameLength,
		&bytesReturned);

	if (SUCCEEDED(result))
		fileName = PhCreateStringEx(buffer, FileNameLength);
	else
		fileName = NULL;

	PhFree(buffer);

	return fileName;
}
Esempio n. 3
0
HRESULT KhspCreateSectionForDataScan(
	_In_ LONGLONG ScanId,
	_Out_ PHANDLE SectionHandle)
{
	HRESULT result;
	HANDLE sectionHandle;
	DWORD bytesReturned;

	struct
	{
		ULONG Command;
		LONGLONG ScanId;
	} input = { HsCmdCreateSectionForDataScan, ScanId };

	result = FilterSendMessage(
		HsKhsPortHandle,
		&input,
		sizeof(input),
		&sectionHandle,
		sizeof(HANDLE),
		&bytesReturned);

	if (SUCCEEDED(result))
		*SectionHandle = sectionHandle;

	return result;
}
int ISISandBoxSetRedirectPath(const wchar_t *aRedirectPath)
{
	int errCode = ERROR_SUCCESS;
	HANDLE driverPort = NULL;

	__try
	{
		if (!aRedirectPath)
		{
			errCode = ERROR_INVALID_PARAMETER;
			__leave;
		}

		if (wcslen(aRedirectPath) > 260)
		{
			errCode = ERROR_BAD_LENGTH;
			__leave;
		}

		// 测试连接
		HRESULT ret = FilterConnectCommunicationPort(ISISandBoxPortName, 0, NULL, 0, NULL, &driverPort);
		if (IS_ERROR(ret))
		{
			errCode = ERROR_NOT_CONNECTED;
			__leave;
		}

		MESSAGE_REDIRECT_PATH_SEND message;
		message.Message.MessageType = MESSAGE_INSERT_REDIRECT_PATH;
		wcscpy_s(message.Message.RedirectPath, 260, aRedirectPath);
		_wcsupr_s(message.Message.RedirectPath, 260);			// 在用户态强制改为大写
		message.Message.Length = (ULONG)wcslen(aRedirectPath);

		DWORD replyLength = 0;
		MESSAGE_REPLY reply;

		ret = FilterSendMessage(driverPort, (PFILTER_MESSAGE_HEADER)&message, sizeof(MESSAGE_PROTECT_PATH_SEND), (PVOID)&reply, sizeof(MESSAGE_REPLY), &replyLength);
		if (ret != S_OK)
		{
			errCode = GetLastError();
			__leave;
		}

		if (reply.MessageType != MESSAGE_INSERT_REDIRECT_PATH && reply.status != 0)
		{
			errCode = ERROR_NOT_SUPPORTED;
			__leave;
		}
	}
	__finally
	{
		CloseHandle(driverPort);
		driverPort = NULL;
	}
	
	return errCode;
}
bool DriverMinifilterCommunicator::SendSymbolsToDriver(const SymbolList &symbolList)
{
	// allocate symbol array which will be passed to the driver
	// count of the symbols is checked inside the driver and must be equal to the number of symbols obtained from the driver
	DWORD dwArraySize = m_driverSymbolCount * sizeof(INTERNAL_SYMBOL);
	PINTERNAL_SYMBOL pSymbolsArray = (PINTERNAL_SYMBOL) VirtualAlloc(0, dwArraySize, MEM_COMMIT, PAGE_READWRITE);
	if(pSymbolsArray == NULL)
	{
		Logger::Instance().Log(_T("Failed to allocate memory for driver symbols"), ERR);
		return false;
	}

	DWORD symIndex = 0;
	symIndex = TransformFromSymbolListToArray(symbolList, pSymbolsArray, symIndex, _T(""));

	// simple error checking - number of transformed items should be the same as the initial array size
	if(m_driverSymbolCount != symIndex)
	{
		Logger::Instance().Log(_T("Number of transformed driver symbols not equal to number of symbols received from the driver!"), WARNING);
		// do not exit, this is probably a non-fatal error
	}

	// format new message (be cautious when setting the required size)
	ULONG uCommandBlockSize = FIELD_OFFSET(COMMAND_MESSAGE, pData[dwArraySize]);
	PCOMMAND_MESSAGE pCommandMessage = (PCOMMAND_MESSAGE) VirtualAlloc(0, uCommandBlockSize, MEM_COMMIT, PAGE_READWRITE);
	if(pCommandMessage == NULL)
	{
		Logger::Instance().Log(_T("Failed to allocate memory for port command message block"), ERR);
		return false;
	}

	pCommandMessage->Command = DmfsSaveSymbols;
	memcpy_s(pCommandMessage->pData, uCommandBlockSize - FIELD_OFFSET(COMMAND_MESSAGE, pData), pSymbolsArray, dwArraySize);

	// send symbols to driver
	DWORD dwBytesReturned = 0;
	if(IS_ERROR(FilterSendMessage(	m_driverPort,					// communication port
									pCommandMessage,				// command message
									uCommandBlockSize,				// size of command message
									NULL,							// no output array
									0,								// no output array size
									&dwBytesReturned				// actual size of the array (in bytes)
									)))
	{
		Logger::Instance().Log(_T("Error sending symbols to driver"), ERR);
		VirtualFree(pSymbolsArray, 0, MEM_RELEASE);
		return false;
	}

	Logger::Instance().Log(_T("Symbols successfully sent to kernel-mode!"), SUCCESS);
	VirtualFree(pSymbolsArray, 0, MEM_RELEASE);
	VirtualFree(pCommandMessage, 0, MEM_RELEASE);

	return true;
}
	void testcommunication()
	{
		HANDLE port = INVALID_HANDLE_VALUE;

        UNICODE_STRING test1;
        RtlUnicodeStringInit(&test1, L"C:\\Program Files\\Microsoft\\filename.txt");

        UNICODE_STRING folder;
        UNICODE_STRING file;

        NTSTATUS status = GetFolderAndFileFromFilePath(&test1, &folder, &file);
        status;

        typedef struct _a {
            UNICODE_STRING b;
            UNICODE_STRING c;
        } a;

        //maybe we could just provide raw memory access to the items selected in the listview?

        a ana;
        ana.b = folder;
        ana.c = file;

		HRESULT result = FilterConnectCommunicationPort(SECRETSTASH_PORT_NAME, NULL, NULL, NULL, NULL, &port);

		if (result == S_OK)
		{
			//CommandMessage message;
			//message.Command = HideAllFiles;
			UNICODE_STRING test;
			RtlUnicodeStringInit(&test, L"test");

			//LPVOID buffer[4096 / sizeof(LPVOID)];
			DWORD bytesReturned = 0;

			//use this to send data http://stackoverflow.com/questions/10986551/windows-driver-passing-strings-between-user-mode-and-kernel-mode-dynamically

			result = FilterSendMessage(
				port,		//Port
                &ana,		//Buffer containing the message to be sent
                sizeof(ana),//Size of the buffer above
				NULL,		//Buffer that receives the reply
				NULL,		//Size of the buffer above
				&bytesReturned		//Amount of data that was actually written to the buffer above
				);

			CloseHandle(port);
		}

        free(folder.Buffer);
        free(file.Buffer);
	}
SymbolList DriverMinifilterCommunicator::GetDriverSymbols(void)
{
	SymbolList symbolList;

	// allocate space for 100 symbols -- will increase it if necessary
	DWORD dwArraySize = sizeof(INTERNAL_SYMBOL) * 100;

	COMMAND_MESSAGE command;

	command.Command = DmfsGetSymbols;

	// initialize array which will hold private symbols
	PINTERNAL_SYMBOL pSymbolsArray = (PINTERNAL_SYMBOL) VirtualAlloc(0, dwArraySize, MEM_COMMIT, PAGE_READWRITE);
	if(pSymbolsArray == NULL)
	{
		Logger::Instance().Log(_T("Failed to allocate memory for driver symbols"), ERR);
		return symbolList;
	}

	// get symbol array from the driver
	DWORD dwReturnedArraySize = 0;
	if(IS_ERROR(FilterSendMessage(	m_driverPort,				// communication port
									&command,					// command message specifying the action
									sizeof(COMMAND_MESSAGE),	// size of the message
									pSymbolsArray,				// output array that will hold the symbols from the driver
									dwArraySize,				// size of the output array
									&dwReturnedArraySize		// actual size of the array (in bytes)
								  )))
	{
		Logger::Instance().Log(_T("Error getting symbols from the driver"), ERR);
		VirtualFree(pSymbolsArray, 0, MEM_RELEASE);
		return symbolList;
	}

	// get number of the symbols returned from the driver
	m_driverSymbolCount = dwReturnedArraySize / sizeof(INTERNAL_SYMBOL);

	// put symbols into symbol list which will be passed to SymbolHelper
	TransformFromArrayToSymbolList(symbolList, pSymbolsArray, m_driverSymbolCount);

	// release allocated memory
	VirtualFree(pSymbolsArray, 0, MEM_RELEASE);

	return symbolList;
}
int ISISandBoxStop()
{
	int errCode = ERROR_SUCCESS;
	HANDLE driverPort = NULL;

	__try
	{
		// 测试连接
		HRESULT ret = FilterConnectCommunicationPort(ISISandBoxPortName, 0, NULL, 0, NULL, &driverPort);
		if (IS_ERROR(ret))
		{
			errCode = ERROR_NOT_CONNECTED;
			__leave;
		}

		MESSAGE_TYPE_SEND message;
		message.Message.MessageType = MESSAGE_DRIVER_STOP_WORKING;

		printf("message length : %d\n", sizeof(MESSAGE_TYPE_SEND));

		DWORD replyLength = 0;
		MESSAGE_REPLY reply;

		ret = FilterSendMessage(driverPort, (PFILTER_MESSAGE_HEADER)&message, sizeof(MESSAGE_TYPE_SEND), (PVOID)&reply, sizeof(MESSAGE_REPLY), &replyLength);
		if (ret != S_OK)
		{
			errCode = GetLastError();
			__leave;
		}

		if (reply.MessageType != MESSAGE_DRIVER_STOP_WORKING && reply.status != 0)
		{
			errCode = ERROR_NOT_SUPPORTED;
			__leave;
		}
	}
	__finally
	{
		CloseHandle(driverPort);
		driverPort = NULL;
	}

	return errCode;
}
int ISISandBoxRemoveProtectProcess(DWORD aProcessId)
{
	int errCode = ERROR_SUCCESS;
	HANDLE driverPort = NULL;

	__try
	{
		// 测试连接
		HRESULT ret = FilterConnectCommunicationPort(ISISandBoxPortName, 0, NULL, 0, NULL, &driverPort);
		if (IS_ERROR(ret))
		{
			errCode = ERROR_NOT_CONNECTED;
			__leave;
		}

		MESSAGE_PROTECT_PROCESS_SEND message;
		message.Message.MessageType = MESSAGE_REMOVE_PROTECT_PROCESS;
		message.Message.ProcessId = (HANDLE)aProcessId;

		DWORD replyLength = 0;
		MESSAGE_REPLY reply;

		ret = FilterSendMessage(driverPort, (PFILTER_MESSAGE_HEADER)&message, sizeof(MESSAGE_PROTECT_PATH_SEND), (PVOID)&reply, sizeof(MESSAGE_REPLY), &replyLength);
		if (ret != S_OK)
		{
			errCode = GetLastError();
			__leave;
		}

		if (reply.MessageType != MESSAGE_INSERT_PROTECT_PROCESS && reply.status != 0)
		{
			errCode = ERROR_NOT_SUPPORTED;
			__leave;
		}
	}
	__finally
	{
		CloseHandle(driverPort);
		driverPort = NULL;
	}

	return ERROR_SUCCESS;
}
Esempio n. 10
0
int NPSendMessage(PVOID InputBuffer)
{
	DWORD bytesReturned = 0;
	DWORD hResult = 0;
	PCOMMAND_MESSAGE commandMessage = (PCOMMAND_MESSAGE) InputBuffer;	
	
    hResult = FilterSendMessage(
		g_hPort,
        commandMessage,
        sizeof(COMMAND_MESSAGE),
        NULL,
        NULL,
        &bytesReturned );

	if (hResult != S_OK) {
		return hResult;
	}
	return 0;
}
Esempio n. 11
0
void OperaterFilter(char data[][MAX_PATH])
{
	int i = 0;
	while (strlen(data[i]))
	{
		//ShowERR("%s",data[i]);
		i++;
	}
	SIZE_T size = sizeof(COMMAND_MESSAGE) + MAX_PATH * DIR_COUNT;
	COMMAND_MESSAGE *msg = (COMMAND_MESSAGE*)new char[size];
	msg->Command = SetDir;
	memcpy_s(msg->Data,MAX_PATH*(i+1),data,MAX_PATH*(i+1));
	DWORD ByteReturned;
	DWORD result;
	HRESULT res = FilterSendMessage(context.Port,msg,sizeof(COMMAND_MESSAGE),&result,sizeof(DWORD),&ByteReturned);
	if (res != S_OK)
	{
		ShowERR("²Ù×÷ʧ°Ü.");
	}

	delete []msg;
}
Esempio n. 12
0
unsigned int WINAPI WaitFileEvent(PVOID pv)
{
    DWORD R;
    bool first = true;

    SendMessage(GetDlgItem(g_hMainDlg, IDC_LOGEDIT), EM_LIMITTEXT, -1, 0);


    while (DriCtl.FileMonitoringOn)
    {
        PFILEINFO pfi = new FILEINFO;
        memset(pfi, 0, sizeof(FILEINFO));

        WaitForSingleObject(DriCtl.hFileEvent, INFINITE);


        if (!DriCtl.FileMonitoringOn) break;

        FILTER_MESSAGE fm;
        fm.Cmd = ENUM_GET_FILE_INFO;
        int ret = FilterSendMessage(DriCtl.hFileFilterPort, &fm, sizeof(fm), pfi, sizeof(FILEINFO), &R);
        

        if (ret == S_OK)
        {
            AppendRecordToLog(pfi, EnumFileType);
        }
        else
            ResetEvent(DriCtl.hFileEvent);

        delete pfi;
        
    }
    
    return 0;
}
Esempio n. 13
0
void
FileMonitor::run()
{
	HRESULT hResult;
	DWORD bytesReturned = 0;
	monitorRunning = true;
	while(isMonitorRunning())
	{
		FILEMONITOR_MESSAGE command;
		command.Command = GetFileEvents;

		ZeroMemory(fileEvents, FILE_EVENTS_BUFFER_SIZE);

		hResult = FilterSendMessage( communicationPort,
                                     &command,
                                     sizeof( FILEMONITOR_COMMAND ),
                                     fileEvents,
                                     FILE_EVENTS_BUFFER_SIZE,
                                     &bytesReturned );
		if(bytesReturned >= sizeof(FILE_EVENT))
		{
			UINT offset = 0;
			do {
				PFILE_EVENT e = (PFILE_EVENT)(fileEvents + offset);

				wstring fileEventName;
				wstring fileEventPath;
				wstring processModuleName;
				wstring processPath;
				vector<wstring> extraData;
				//file event extra.at(0) == PID
				wchar_t processIdString[11];
				swprintf(processIdString, 11, L"%ld", e->processId);
				extraData.push_back(processIdString);

				if(getFileEventName(e, &fileEventName))
				{
					processPath = ProcessManager::getInstance()->getProcessPath(e->processId);
					processModuleName = ProcessManager::getInstance()->getProcessModuleName(e->processId);
					
					fileEventPath = e->filePath;
					fileEventPath = convertFileObjectNameToDosName(fileEventPath);

					if((fileEventPath != L"UNKNOWN"))
					{
						if(!Monitor::isEventAllowed(fileEventName, processPath, fileEventPath))
						{
							if(monitorModifiedFiles)
							{
		
								if(!isDirectory(fileEventPath))
								{
									if(e->majorFileEventType == IRP_MJ_CREATE || 
										e->majorFileEventType == IRP_MJ_WRITE )
									{	
										modifiedFiles.insert(fileEventPath);
									} else if(e->majorFileEventType == IRP_MJ_DELETE) 
									{
										modifiedFiles.erase(fileEventPath);
									}	
								}
							}

							wchar_t szTempTime[256];
							convertTimefieldsToString(e->time, szTempTime, 256);
							wstring time = szTempTime;

							signal_onFileEvent(fileEventName, time, processPath, fileEventPath, extraData);
						}
					}
				}
				
				offset += sizeof(FILE_EVENT) + e->filePathLength;
			} while(offset < bytesReturned);	
		}
		
		if(bytesReturned == FILE_EVENTS_BUFFER_SIZE)
		{
			Sleep(FILE_EVENT_BUFFER_FULL_WAIT_TIME);
		} else {
			Sleep(FILE_EVENT_WAIT_TIME);
		}
	}
	SetEvent(hMonitorStoppedEvent);
}
Esempio n. 14
0
DWORD
CEncryptionDriver::WaitForNotification(_Out_ /*PUCA_NOTIFICATION*/ PVOID *Notification,
                                       _Out_ LPDWORD lpdwBufferSize)
{
#if 0
    UCA_FLT_QUERY_MESSAGE QueryMessage;
    UCA_FLT_GET_MESSAGE RequestMessage;
    UCA_NOTIFICATION_INFO NotificationInfo;
    DWORD BytesReturned;
    HRESULT hResult;
    DWORD dwError;

    TRACE_ENTER(TraceHandle);

    if (!Notification || !lpdwBufferSize) return ERROR_INVALID_PARAMETER;

    *Notification = NULL;
    *lpdwBufferSize = 0;

    /* Request the next message info */
    QueryMessage.Header.Message = FLT_GET_NEXT_MESSAGE;

    /* This call blocks, so set the cancel IO event */
    QueryMessage.Header.hCancelIo = m_hCancelIo;

    /* Send the message to the driver */
    hResult = FilterSendMessage(m_hPort,
                                &QueryMessage,
                                sizeof(UCA_FLT_QUERY_MESSAGE),
                                &NotificationInfo,
                                sizeof(UCA_NOTIFICATION_INFO),
                                &BytesReturned);
    if (hResult != S_OK)
    {
        TRACE_ERROR(TraceHandle, "Failed to send a query message to the driver : %X", hResult);
        return SCODE_CODE(hResult);
    }

    TRACE_INFO(TraceHandle, "Handle is %X", NotificationInfo.NotificationHandle);
    TRACE_INFO(TraceHandle, "Allocating %lu bytes", NotificationInfo.NotificationSize);

    /* Allocate memory to hold the data */
    *Notification = (PUCA_NOTIFICATION)HeapAlloc(GetProcessHeap(),
                                                 0,
                                                 NotificationInfo.NotificationSize);
    if (*Notification == NULL) return ERROR_NOT_ENOUGH_MEMORY;

    /* Set the header to actually get the message */
    RequestMessage.Header.Message = FLT_GET_MESSAGE;
    RequestMessage.Header.hCancelIo = NULL;

    /* Set the handle to the data we want */
    RequestMessage.NotificationHandle = NotificationInfo.NotificationHandle;

    /* Send the message to the driver */
    hResult = FilterSendMessage(m_hPort,
                                &RequestMessage,
                                sizeof(UCA_FLT_GET_MESSAGE),
                                *Notification,
                                NotificationInfo.NotificationSize,
                                &BytesReturned);
    if (hResult == S_OK)
    {
        /* Store the buffer size */
        *lpdwBufferSize = NotificationInfo.NotificationSize;
        dwError = ERROR_SUCCESS;
    }
    else
    {
        /* Cleanup */
        TRACE_ERROR(TraceHandle, "Failed to send a get message to the driver : %X", hResult);
        dwError = SCODE_CODE(hResult);
        HeapFree(GetProcessHeap(), 0, *Notification);
        *Notification = NULL;
    }

    TRACE_EXIT(TraceHandle);
#endif
    return 0;//dwError;
}
Esempio n. 15
0
DWORD
WINAPI
RetrieveLogRecords(
    _In_ LPVOID lpParameter
    )
/*++

Routine Description:

    This runs as a separate thread.  Its job is to retrieve log records
    from the filter and then output them

Arguments:

    lpParameter - Contains context structure for synchronizing with the
        main program thread.

Return Value:

    The thread successfully terminated

--*/
{
    PLOG_CONTEXT context = (PLOG_CONTEXT)lpParameter;
    DWORD bytesReturned = 0;
    DWORD used;
    PVOID alignedBuffer[BUFFER_SIZE/sizeof( PVOID )];
    PCHAR buffer = (PCHAR) alignedBuffer;
    HRESULT hResult;
    PLOG_RECORD pLogRecord;
    PRECORD_DATA pRecordData;
    COMMAND_MESSAGE commandMessage;

    //printf("Log: Starting up\n");

#pragma warning(push)
#pragma warning(disable:4127) // conditional expression is constant

    while (TRUE) {

#pragma warning(pop)

        //
        //  Check to see if we should shut down.
        //

        if (context->CleaningUp) {

            break;
        }

        //
        //  Request log data from MiniSpy.
        //

        commandMessage.Command = GetMiniSpyLog;

        hResult = FilterSendMessage( context->Port,
                                     &commandMessage,
                                     sizeof( COMMAND_MESSAGE ),
                                     buffer,
                                     sizeof(alignedBuffer),
                                     &bytesReturned );

        if (IS_ERROR( hResult )) {

            if (HRESULT_FROM_WIN32( ERROR_INVALID_HANDLE ) == hResult) {

                printf( "The kernel component of minispy has unloaded. Exiting\n" );
                ExitProcess( 0 );
            } else {

                if (hResult != HRESULT_FROM_WIN32( ERROR_NO_MORE_ITEMS )) {

                    printf( "UNEXPECTED ERROR received: %x\n", hResult );
                }

                Sleep( POLL_INTERVAL );
            }

            continue;
        }

        //
        //  Buffer is filled with a series of LOG_RECORD structures, one
        //  right after another.  Each LOG_RECORD says how long it is, so
        //  we know where the next LOG_RECORD begins.
        //

        pLogRecord = (PLOG_RECORD) buffer;
        used = 0;

        //
        //  Logic to write record to screen and/or file
        //

        for (;;) {

            if (used+FIELD_OFFSET(LOG_RECORD,Name) > bytesReturned) {

                break;
            }

            if (pLogRecord->Length < (sizeof(LOG_RECORD)+sizeof(WCHAR))) {

                printf( "UNEXPECTED LOG_RECORD->Length: length=%d expected>=%d\n",
                        pLogRecord->Length,
                        (sizeof(LOG_RECORD)+sizeof(WCHAR)));

                break;
            }

            used += pLogRecord->Length;

            if (used > bytesReturned) {

                printf( "UNEXPECTED LOG_RECORD size: used=%d bytesReturned=%d\n",
                        used,
                        bytesReturned);

                break;
            }

            pRecordData = &pLogRecord->Data;

            //
            //  See if a reparse point entry
            //

            if (FlagOn(pLogRecord->RecordType,RECORD_TYPE_FILETAG)) {

                if (!TranslateFileTag( pLogRecord )){

                    //
                    // If this is a reparse point that can't be interpreted, move on.
                    //

                    pLogRecord = (PLOG_RECORD)Add2Ptr(pLogRecord,pLogRecord->Length);
                    continue;
                }
            }

            if (context->LogToScreen) {

                ScreenDump( pLogRecord->SequenceNumber,
                            pLogRecord->Name,
                            pRecordData );
            }

            if (context->LogToFile) {

                FileDump( pLogRecord->SequenceNumber,
                          pLogRecord->Name,
                          pRecordData,
                          context->OutputFile );
            }

            //
            //  The RecordType could also designate that we are out of memory
            //  or hit our program defined memory limit, so check for these
            //  cases.
            //

            if (FlagOn(pLogRecord->RecordType,RECORD_TYPE_FLAG_OUT_OF_MEMORY)) {

                if (context->LogToScreen) {

                    printf( "M:  %08X System Out of Memory\n",
                            pLogRecord->SequenceNumber );
                }

                if (context->LogToFile) {

                    fprintf( context->OutputFile,
                             "M:\t0x%08X\tSystem Out of Memory\n",
                             pLogRecord->SequenceNumber );
                }

            } else if (FlagOn(pLogRecord->RecordType,RECORD_TYPE_FLAG_EXCEED_MEMORY_ALLOWANCE)) {

                if (context->LogToScreen) {

                    printf( "M:  %08X Exceeded Mamimum Allowed Memory Buffers\n",
                            pLogRecord->SequenceNumber );
                }

                if (context->LogToFile) {

                    fprintf( context->OutputFile,
                             "M:\t0x%08X\tExceeded Mamimum Allowed Memory Buffers\n",
                             pLogRecord->SequenceNumber );
                }
            }

            //
            // Move to next LOG_RECORD
            //

            pLogRecord = (PLOG_RECORD)Add2Ptr(pLogRecord,pLogRecord->Length);
        }

        //
        //  If we didn't get any data, pause for 1/2 second
        //

        if (bytesReturned == 0) {

            Sleep( POLL_INTERVAL );
        }
    }

    printf( "Log: Shutting down\n" );
    ReleaseSemaphore( context->ShutDown, 1, NULL );
    printf( "Log: All done\n" );
    return 0;
}
bool DriverMinifilterCommunicator::StartHiding(const TargetObjectList &targetObjects)
{
	// do nothing if the driver is not installed
	if(!m_isInstalled)
	{
		return false;
	}

	if(targetObjects.empty())
	{
		Logger::Instance().Log(_T("Objects to be hidden are not defined... Not sending information to driver"), WARNING);
		return false;
	}

	// allocate space for all objects to be hidden
	DWORD dwArraySize = sizeof(TARGET_OBJECT) * targetObjects.size();

	// initialize array which will hold all objects for hiding
	PTARGET_OBJECT pTargetObjectArray = (PTARGET_OBJECT) VirtualAlloc(0, dwArraySize, MEM_COMMIT, PAGE_READWRITE);
	if(pTargetObjectArray == NULL)
	{
		Logger::Instance().Log(_T("Failed to allocate memory for array of objects to be hidden"), ERR);
		return false;
	}

	// "linearize" all objects to be hidden to array
	DWORD dwObjIndex = 0;
	TargetObjectList::const_iterator iter;
	for(iter = targetObjects.begin(); iter != targetObjects.end(); ++iter)
	{
		TargetObjectPtr targetObject = *iter;
		pTargetObjectArray[dwObjIndex] = targetObject->LinearizeObject();
		dwObjIndex++;
	}

	// format new message (be cautious when setting the required size)
	ULONG uCommandBlockSize = FIELD_OFFSET(COMMAND_MESSAGE, pData[dwArraySize]);
	PCOMMAND_MESSAGE pCommandMessage = (PCOMMAND_MESSAGE) VirtualAlloc(0, uCommandBlockSize, MEM_COMMIT, PAGE_READWRITE);
	if(pCommandMessage == NULL)
	{
		Logger::Instance().Log(_T("Failed to allocate memory for port command message block"), ERR);
		return false;
	}

	pCommandMessage->Command = DmfsStartHiding;
	memcpy_s(pCommandMessage->pData, uCommandBlockSize - FIELD_OFFSET(COMMAND_MESSAGE, pData), pTargetObjectArray, dwArraySize);

	// send symbols to driver
	DWORD dwBytesReturned = 0;
	if(IS_ERROR(FilterSendMessage(	m_driverPort,					// communication port
									pCommandMessage,				// command message
									uCommandBlockSize,				// size of command message
									NULL,							// no output array
									0,								// no output array size
									&dwBytesReturned				// actual size of the array (in bytes)
								 )))
	{
		Logger::Instance().Log(_T("Error starting hiding engine"), ERR);
		VirtualFree(pTargetObjectArray, 0, MEM_RELEASE);
		return false;
	}

	Logger::Instance().Log(_T("Hiding engine started!"), SUCCESS);
	VirtualFree(pTargetObjectArray, 0, MEM_RELEASE);
	VirtualFree(pCommandMessage, 0, MEM_RELEASE);

	// TEST ONLY!
	Sleep(900000);

	return true;
}