bool DriverMinifilterCommunicator::InstallDriver(void)
{
	// don't install the driver if it already exists
	if(m_isInstalled)
	{
		return true;
	}

	// check if current user is administrator
	Logger::Instance().Log(_T("Check if running under administrator context..."), INFO);
	if(!Utils::IsAdmin())
	{
		Logger::Instance().Log(_T("Not admin - try to run the program as administrator"), CRITICAL_ERROR);
		return false;
	}
	Logger::Instance().Log(_T("Running as administrator -- connecting to driver port"), SUCCESS);

	// connect to communication port
	HRESULT hResult = FilterConnectCommunicationPort(	PORT_NAME,						// port name
														0,								// options must be zero (documentation)
														NULL,							// don't pass context to connect routine
														0,								// size of context
														NULL,							// don't inherit this handle
														&m_driverPort					// handle to communication port
													 );

	if (IS_ERROR( hResult ))
	{
		Logger::Instance().Log(_T("Cannot connect to driver port"), CRITICAL_ERROR);
		return false;
	}

	m_isInstalled = true;
	return true;
}
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;
}
	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);
	}
Exemple #4
0
int InitialCommunicationPort(void)
{
    DWORD hResult = FilterConnectCommunicationPort( 
		NPMINI_PORT_NAME, 
		0, 
		NULL, 
		0, 
		NULL, 
		&g_hPort );

	if (hResult != S_OK) {
		return hResult;
	}
	return 0;
}
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;
}
Exemple #7
0
bool Init()
{
	HANDLE port = INVALID_HANDLE_VALUE;
	//HAV_CONTEXT context;
	HRESULT hResult = S_OK;
	context.ShutDown = NULL;

	hResult = FilterConnectCommunicationPort(HAV_PORT_NAME,0,NULL,0,NULL,&port);
	if (IS_ERROR(hResult))
	{
		ShowERR("Could not connect to filter: 0x%08x\n",hResult);
		return false;
	}

	context.Port = port;
	context.ShutDown = CreateSemaphore(NULL,0,1,"Hav shut down");
	context.CleaningUp = FALSE;

	return true;
}
Exemple #8
0
HRESULT KhsConnect(
	_In_ LPCWSTR PortName)
{
	HRESULT result;
	HANDLE communicationPort;

	result = FilterConnectCommunicationPort(
		PortName,
		0,
		NULL,
		0,
		NULL,
		&communicationPort);

	if (SUCCEEDED(result))
	{
		HsKhsPortHandle = communicationPort;
	}

	return result;
}
HRESULT
UserScanInit (
    _Inout_  PUSER_SCAN_CONTEXT Context
    )
/*++

Routine Description:

    This routine initializes all the necessary data structures and forks listening threads.
    The caller thread is responsible for calling UserScanFinalize(...) to cleanup the 
    data structures and close the listening threads.

Arguments:

    Context    - User scan context, please see userscan.h

Return Value:

    S_OK if successful. Otherwise, it returns a HRESULT error value.

--*/
{
    HRESULT  hr = S_OK;
    ULONG    i = 0;
    HANDLE   hEvent = NULL;
    PSCANNER_THREAD_CONTEXT  scanThreadCtxes = NULL;
    HANDLE   hListenAbort = NULL;
    AV_CONNECTION_CONTEXT connectionCtx = {0};
    
    if (NULL == Context) {
    
        return MAKE_HRESULT(SEVERITY_ERROR, 0, E_POINTER);
    }
    
    //
    //  Create the abort listening thead.
    //  This thread is particularly listening the abortion event.
    //
    
    hListenAbort = CreateThread( NULL,
                                 0,
                                 (LPTHREAD_START_ROUTINE)UserScanListenAbortProc,
                                 Context,
                                 CREATE_SUSPENDED,
                                 NULL );
    
    if (NULL == hListenAbort) {
    
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto Cleanup;
    }
    
    //
    //  Initialize scan thread contexts.
    //
    
    scanThreadCtxes = HeapAlloc(GetProcessHeap(), 0, sizeof(SCANNER_THREAD_CONTEXT) * USER_SCAN_THREAD_COUNT);
    if (NULL == scanThreadCtxes) {
    
        hr = MAKE_HRESULT(SEVERITY_ERROR, 0, E_OUTOFMEMORY);
        goto Cleanup;
    }
    
    ZeroMemory(scanThreadCtxes, sizeof(SCANNER_THREAD_CONTEXT) * USER_SCAN_THREAD_COUNT);
    
    //
    //  Create scan listening threads.
    //
    
    for (i = 0;
         i < USER_SCAN_THREAD_COUNT;
         i ++ ) {
         
        scanThreadCtxes[i].Handle = CreateThread( NULL,
                                                  0,
                                                  (LPTHREAD_START_ROUTINE)UserScanWorker,
                                                  Context,
                                                  CREATE_SUSPENDED,
                                                  &scanThreadCtxes[i].ThreadId );
        
        if (NULL == scanThreadCtxes[i].Handle) {
            hr = HRESULT_FROM_WIN32(GetLastError());
            goto Cleanup;
        }
        InitializeCriticalSection(&(scanThreadCtxes[i].Lock));
    }
    
    //
    //  Prepare the scan communication port.
    //
    
    connectionCtx.Type = AvConnectForScan;
    hr = FilterConnectCommunicationPort( AV_SCAN_PORT_NAME,
                                         0,
                                         &connectionCtx,
                                         sizeof(AV_CONNECTION_CONTEXT),
                                         NULL,
                                         &Context->ConnectionPort );
    if (FAILED(hr)) {
    
        Context->ConnectionPort = NULL;
        goto Cleanup;
    }
    
    //
    //  Create the IO completion port for asynchronous message passing. 
    //
    
    Context->Completion = CreateIoCompletionPort( Context->ConnectionPort,
                                                  NULL,
                                                  0,
                                                  USER_SCAN_THREAD_COUNT );
    
    if ( NULL == Context->Completion ) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto Cleanup;
    }
    
    Context->ScanThreadCtxes = scanThreadCtxes;
    Context->AbortThreadHandle = hListenAbort;
    
    //
    //  Resume all the scanning threads.
    //
    
    for (i = 0;
         i < USER_SCAN_THREAD_COUNT;
         i ++ ) {
         if ( ResumeThread( scanThreadCtxes[i].Handle ) == -1) {
         
            fprintf(stderr, "[UserScanInit]: ResumeThread scan listening thread failed.\n");
            hr = HRESULT_FROM_WIN32(GetLastError());
            goto Cleanup;
         }
    }
    
    //
    //  Resume abort listening thread.
    //
    
    if ( ResumeThread( hListenAbort ) == -1 ) {
        fprintf(stderr, "[UserScanInit]: ResumeThread abort listening thread failed.\n");
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto Cleanup;
    }
    
    //
    //  Pump messages into queue of completion port.
    //
    
    for (i = 0;
         i < USER_SCAN_THREAD_COUNT;
         i ++ ) {

        PSCANNER_MESSAGE msg = HeapAlloc( GetProcessHeap(), 0, sizeof( SCANNER_MESSAGE ) );
        
        if (NULL == msg) {
        
            hr = MAKE_HRESULT(SEVERITY_ERROR, 0, E_OUTOFMEMORY);
            goto Cleanup;
        }
        
        FillMemory( &msg->Ovlp, sizeof(OVERLAPPED), 0);
        hr = FilterGetMessage( Context->ConnectionPort,
                               &msg->MessageHeader,
                               FIELD_OFFSET( SCANNER_MESSAGE, Ovlp ),
                               &msg->Ovlp );

        if (hr == HRESULT_FROM_WIN32( ERROR_IO_PENDING )) {
        
            hr = S_OK;
            
        } else {
        
            fprintf(stderr, "[UserScanInit]: FilterGetMessage failed.\n");
            DisplayError(hr);
            HeapFree(GetProcessHeap(), 0, msg );
            goto Cleanup;
        }
    }
    
    return hr;
    
Cleanup:

    if (Context->Completion && !CloseHandle(Context->Completion)) {
    
        fprintf(stderr, "[UserScanInit] Error! Close completion port failed.\n");
        DisplayError(HRESULT_FROM_WIN32(GetLastError()));
    }
    if (Context->ConnectionPort && !CloseHandle(Context->ConnectionPort)) {
    
        fprintf(stderr, "[UserScanInit] Error! Close connection port failed.\n");
        DisplayError(HRESULT_FROM_WIN32(GetLastError()));
    }
    if (scanThreadCtxes) {
    
        for (i = 0;
         i < USER_SCAN_THREAD_COUNT;
         i ++ ) {

            if (scanThreadCtxes[i].Handle && !CloseHandle(scanThreadCtxes[i].Handle)) {

                fprintf(stderr, "[UserScanInit] Error! Close scan thread failed.\n");
                DisplayError(HRESULT_FROM_WIN32(GetLastError()));
            }
            DeleteCriticalSection(&(scanThreadCtxes[i].Lock));
        }
        HeapFree(GetProcessHeap(), 0, scanThreadCtxes);
    }
    if (hListenAbort && !CloseHandle(hListenAbort)) {
    
        fprintf(stderr, "[UserScanInit] Error! Close listen abort thread failed.\n");
        DisplayError(HRESULT_FROM_WIN32(GetLastError()));
    }
    if (hEvent && !CloseHandle(hEvent)) {
    
        fprintf(stderr, "[UserScanInit] Error! Close event handle failed.\n");
        DisplayError(HRESULT_FROM_WIN32(GetLastError()));
    }
    
    return hr;
}
FileMonitor::FileMonitor(void)
{
	HRESULT hResult;
	monitorRunning = false;
	driverInstalled = false;
	int turn = 0;
	communicationPort = INVALID_HANDLE_VALUE;
	monitorModifiedFiles = false;

	hMonitorStoppedEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	
	FilterUnload(L"CaptureFileMonitor");
	hResult = FilterLoad(L"CaptureFileMonitor");
	// Keep trying to load the filter - On some VM's this can take a few seconds
	while((turn < 5) && IS_ERROR( hResult ))
	{
		turn++;
		printf("FileMonitor: WARNING - Filter driver not loaded (error: %x) waiting 3 seconds to try again ... (try %i of 5)\n", hResult, turn);
		Sleep(3000);
		hResult = FilterLoad(L"CaptureFileMonitor");
	}
	
	if (!IS_ERROR( hResult )) {
		
		hResult = FilterConnectCommunicationPort( CAPTURE_FILEMON_PORT_NAME,
												0,
												NULL,
												0,
												NULL,
												&communicationPort );
		if (IS_ERROR( hResult )) {

			printf( "FileMonitor: ERROR - Could not connect to filter: 0x%08x\n", hResult );
		} else {
			printf("Loaded filter driver: CaptureFileMonitor\n");
			driverInstalled = true;
			//this.setMonitorModifiedFiles(false);
		}
		
		wchar_t exListDriverPath[1024];
		GetFullPathName(L"FileMonitor.exl", 1024, exListDriverPath, NULL);
		Monitor::loadExclusionList(exListDriverPath);

		/* Create a log directory exclusion which allows all writes in
		   Captures log directory */
		wchar_t logDirectory[1024];
		GetFullPathName(L"logs", 1024, logDirectory, NULL);
		wstring captureLogDirectory = logDirectory;
		Monitor::prepareStringForExclusion(&captureLogDirectory);
		captureLogDirectory += L"\\\\.*";

		wstring captureExecutablePath = ProcessManager::getInstance()->getProcessPath(GetCurrentProcessId());
		Monitor::prepareStringForExclusion(&captureExecutablePath);
		
		/* Exclude file events in the log directory */
		/* NOTE we exclude all processes because files are copied/delete/openend
		   etc in the context of the calling process not Capture */
		Monitor::addExclusion(L"+", L"write", L".*", captureLogDirectory, true);
		Monitor::addExclusion(L"+", L"create", L".*", captureLogDirectory, true);
		Monitor::addExclusion(L"+", L"delete", L".*", captureLogDirectory, true);
		Monitor::addExclusion(L"+", L"open", L".*", captureLogDirectory, true);
		Monitor::addExclusion(L"+", L"read", L".*", captureLogDirectory, true);

		/* Exclude Captures temp directory */
		wchar_t tempDirectory[1024];
		GetFullPathName(L"temp", 1024, tempDirectory, NULL);
		wstring captureTempDirectory = tempDirectory;
		Monitor::prepareStringForExclusion(&captureTempDirectory);
		captureTempDirectory += L"\\\\.*";

		//wstring captureExecutablePath = ProcessManager::getInstance()->getProcessPath(GetCurrentProcessId());
		//Monitor::prepareStringForExclusion(&captureExecutablePath);
		
		/* Exclude file events in the log directory */
		/* NOTE we exclude all processes because files are copied/delete/openend
		   etc in the context of the calling process not Capture */
		Monitor::addExclusion(L"+", L"write", L".*", captureTempDirectory, true);
		Monitor::addExclusion(L"+", L"create", L".*", captureTempDirectory, true);
		Monitor::addExclusion(L"+", L"delete", L".*", captureTempDirectory, true);
		Monitor::addExclusion(L"+", L"open", L".*", captureTempDirectory, true);
		Monitor::addExclusion(L"+", L"read", L".*", captureTempDirectory, true);
		
		if(OptionsManager::getInstance()->getOption(L"log-system-events-file") != L"")
		{
			wstring loggerFile = Logger::getInstance()->getLogFullPath();
			Monitor::prepareStringForExclusion(&loggerFile);
			Monitor::addExclusion(L"+", L"create", captureExecutablePath, loggerFile, true);
			Monitor::addExclusion(L"+", L"write", captureExecutablePath, loggerFile, true);
		}
		onFileExclusionReceivedConnection = EventController::getInstance()->connect_onServerEvent(L"file-exclusion", boost::bind(&FileMonitor::onFileExclusionReceived, this, _1));

		initialiseDosNameMap();
	}
}