Ejemplo n.º 1
0
NTSTATUS CleanupMatchExpression()
{
	if (IsListEmpty(&MatchExpressionList.HeadList))
		return STATUS_SUCCESS;

	KIRQL irql;
	KeAcquireSpinLock(&MatchExpressionList.Lock, &irql);

	// 链表头
	PLIST_ENTRY pList = MatchExpressionList.HeadList.Flink;

	while (pList != &MatchExpressionList.HeadList)
	{
		PMATCH_EXPRESSION element = CONTAINING_RECORD(pList, MATCH_EXPRESSION, ListEntry);

		pList->Blink->Flink = pList->Flink;
		pList->Flink->Blink = pList->Blink;
		pList = pList->Flink;

		// 这里的指针都已经断开了,即链表中不存在element了,现在只需要将其内存释放就OK了
		ExFreeToPagedLookasideList(&MatchExpressionList.PageList, element);
	}

	KeReleaseSpinLock(&MatchExpressionList.Lock, irql);

	KdPrint(("[ISISandBox] CleanupMatchExpression Cleanup all expression.\n"));
	return STATUS_SUCCESS;
}
Ejemplo n.º 2
0
void TestLookaside()
{
	KdPrint(("enter TestLookaside ......\n"));
	PAGED_LOOKASIDE_LIST tLookaside;
	ExInitializePagedLookasideList(&tLookaside,NULL,NULL,0,sizeof(MyListNode),'1234',0);

	MyListNode* MyList[10] = {0};
	for(int i=0; i<10; i++)
	{
		MyList[i] = (MyListNode*)ExAllocateFromPagedLookasideList(&tLookaside);
		if(MyList[i] == NULL)
		{
			KdPrint(("i f**k ..\n"));
			continue;
		}
		MyList[i]->data = i;
	}

	for(int k=0; k<10; k++)
	{
		if(MyList[k] == NULL)
		{
			KdPrint(("i f**k too \n"));
			continue;
		}
		KdPrint(("%d   ",MyList[k]->data));
		ExFreeToPagedLookasideList(&tLookaside,MyList[k]);
		MyList[k] = NULL;
	}

	ExDeletePagedLookasideList(&tLookaside);
	
	KdPrint(("leave TestLookaside ......\n"));

}
//
// Функция, вызываемая при выгрузке драйвера.
//
VOID DriverUnload(IN PDRIVER_OBJECT pDriverObject) {
	ULONG reg;

	// удаление символьной ссылки и объекта устройства
	IoDeleteSymbolicLink(&glSymLinkName);
	IoDeleteDevice(pDriverObject->DeviceObject);

	// удаляем элементы списка файлов
	while (!IsListEmpty(&glOpenFiles)) {
		PLIST_ENTRY pLink = RemoveHeadList(&glOpenFiles);
		OpenFileEntry *entry = CONTAINING_RECORD(pLink, OpenFileEntry, link);

		RtlFreeAnsiString(&entry->fileName);
		RtlFreeUnicodeString(&entry->fullName);

		ExFreeToPagedLookasideList(&glPagedList, entry);
	}

	// удаляем резервный список
	ExDeletePagedLookasideList(&glPagedList);

	KdPrint(("Driver unload\n"));
	//reg = ClearWP();
	KeServiceDescriptorTable->Base[NUMBER_NT_CREATE_FILE] = (ULONG)glRealNtCreateFile;
	KeServiceDescriptorTable->Base[NUMBER_NT_OPEN_FILE] = (ULONG)glRealNtOpenFile;
	//WriteCR0(reg);

	WaitHookUnload(&glHookCounter);
	//FreeProtectedFiles();

	return;
}
Ejemplo n.º 4
0
NTSTATUS FreePagedLookasideListForDirectory()
{
	NTSTATUS status = STATUS_SUCCESS;
	PDIRECTORY_INFO pDirectoryInfo = g_pDirectoryInfo, pNextDirectoryInfo = NULL;

	__try
	{
		if (NULL != g_pPageListDirectory && NULL != g_pDirectoryInfo)
		{
			while (pDirectoryInfo)
			{
				pNextDirectoryInfo = pDirectoryInfo->next;

				ExFreeToPagedLookasideList(g_pPageListDirectory, pDirectoryInfo);

				pDirectoryInfo = pNextDirectoryInfo;
			}

			ExDeletePagedLookasideList(g_pPageListDirectory);
			ExFreePool(g_pPageListDirectory);
			g_pPageListDirectory = NULL;
			g_pDirectoryInfo = NULL;
		}
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		KdPrint(("SSDT:FreePagedLookasideListForSSDT failed!"));
		status = GetExceptionCode();
	}


	return status;
}
Ejemplo n.º 5
0
NTSTATUS CleanupProtectProcess()
{
	if (IsListEmpty(&ProtectProcessList.HeadList))
		return STATUS_SUCCESS;

	KIRQL irql;
	KeAcquireSpinLock(&ProtectProcessList.Lock, &irql);

	// 链表头
	PLIST_ENTRY pList = ProtectProcessList.HeadList.Flink;

	while (pList != &ProtectProcessList.HeadList)
	{
		PPROTECT_PROCESS element = CONTAINING_RECORD(pList, PROTECT_PROCESS, ListEntry);

		pList->Blink->Flink = pList->Flink;
		pList->Flink->Blink = pList->Blink;
		pList = pList->Flink;

		// 这里的指针都已经断开了,即链表中不存在element了,现在只需要将其内存释放就OK了
		ExFreeToPagedLookasideList(&ProtectProcessList.PageList, element);
	}

	KeReleaseSpinLock(&ProtectProcessList.Lock, irql);

	KdPrint(("[ISISandBox] CleanupProtectProcess Cleanup all process.\n"));
	return STATUS_SUCCESS;
}
Ejemplo n.º 6
0
NTSTATUS FreePagedLookasideListForServices()
{
	NTSTATUS status = STATUS_SUCCESS;
	PSERVICES_INFO pServicesInfo = NULL,\
		pNextServicesInfo = NULL;

	__try
	{

		if (g_pServicesInfo != NULL)
		{
			pServicesInfo = g_pServicesInfo;

			while (pServicesInfo != NULL)
			{
				pNextServicesInfo = pServicesInfo->next;

				ExFreeToPagedLookasideList(&g_PageListServices, pServicesInfo);

				pServicesInfo = pNextServicesInfo;
			}

			ExDeletePagedLookasideList(&g_PageListServices);
			g_pServicesInfo = NULL;
		}

	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		KdPrint(("Services:FreePagedLookasideListForDriverModule failed!"));
		status = STATUS_UNSUCCESSFUL;
	}

	return status;
}
Ejemplo n.º 7
0
/*
 * @implemented
 */
VOID
NTAPI
FsRtlFreeFileLock(IN PFILE_LOCK FileLock)
{
    /* Uninitialize and free the lock */
    FsRtlUninitializeFileLock(FileLock);
    ExFreeToPagedLookasideList(&FsRtlFileLockLookasideList, FileLock);
}
Ejemplo n.º 8
0
VOID
NTAPI
LpcpFreeToPortZone(IN PLPCP_MESSAGE Message,
                   IN ULONG LockFlags)
{
    PLPCP_CONNECTION_MESSAGE ConnectMessage;
    PLPCP_PORT_OBJECT ClientPort = NULL;
    PETHREAD Thread = NULL;
    BOOLEAN LockHeld = (LockFlags & LPCP_LOCK_HELD);
    BOOLEAN ReleaseLock = (LockFlags & LPCP_LOCK_RELEASE);

    PAGED_CODE();

    LPCTRACE(LPC_CLOSE_DEBUG, "Message: %p. LockFlags: %lx\n", Message, LockFlags);

    /* Acquire the lock if not already */
    if (!LockHeld) KeAcquireGuardedMutex(&LpcpLock);

    /* Check if the queue list is empty */
    if (!IsListEmpty(&Message->Entry))
    {
        /* Remove and re-initialize */
        RemoveEntryList(&Message->Entry);
        InitializeListHead(&Message->Entry);
    }

    /* Check if we've already replied */
    if (Message->RepliedToThread)
    {
        /* Set thread to dereference and clean up */
        Thread = Message->RepliedToThread;
        Message->RepliedToThread = NULL;
    }

    /* Check if this is a connection request */
    if (Message->Request.u2.s2.Type == LPC_CONNECTION_REQUEST)
    {
        /* Get the connection message */
        ConnectMessage = (PLPCP_CONNECTION_MESSAGE)(Message + 1);

        /* Clear the client port */
        ClientPort = ConnectMessage->ClientPort;
        if (ClientPort) ConnectMessage->ClientPort = NULL;
    }

    /* Release the lock */
    KeReleaseGuardedMutex(&LpcpLock);

    /* Check if we had anything to dereference */
    if (Thread) ObDereferenceObject(Thread);
    if (ClientPort) ObDereferenceObject(ClientPort);

    /* Free the entry */
    ExFreeToPagedLookasideList(&LpcpMessagesLookaside, Message);

    /* Reacquire the lock if needed */
    if ((LockHeld) && !(ReleaseLock)) KeAcquireGuardedMutex(&LpcpLock);
}
Ejemplo n.º 9
0
NTSTATUS RegSetValueKey( IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName,
						IN ULONG TitleIndex, IN ULONG Type, 
						IN PVOID Data, IN ULONG DataSize )
{
	WCHAR			szFullPath[MAXPATHLEN]	= {0};		
	PVOID			pKeyObj					= NULL;
	ULONG			ulRet					= 0;
	PUNICODE_STRING	fullUniName				= NULL;
	int				i;
	ULONG			nAllowd					= 1;
	WCHAR			szValueName[256]		= {0};
	WCHAR			szValue[512]			= {0};

	if(FALSE == IsGuardStart())
		goto allowed;
	if(STATUS_SUCCESS == ObReferenceObjectByHandle(KeyHandle, 0, NULL, KernelMode, &pKeyObj, NULL))
 	{
		PINNERPACK_LIST			pList;
		LONG					nSubType		= 0;

 		fullUniName = ExAllocateFromPagedLookasideList(&gRegMonLooaside);
		if(NULL == fullUniName)
			goto allowed;

 		fullUniName->MaximumLength = MAXPATHLEN * 2;
 		ObQueryNameString(pKeyObj, (POBJECT_NAME_INFORMATION)fullUniName, MAXPATHLEN, &ulRet);
 		ObDereferenceObject(pKeyObj);
		// 转换路径
		ConvertKeyPath(szFullPath, fullUniName->Buffer, MAXPATHLEN);
		ExFreeToPagedLookasideList(&gRegMonLooaside, fullUniName);
		// 复制路径
		wcsncpy(szValueName, (NULL != ValueName)?ValueName->Buffer:L""
			, (NULL != ValueName)?ValueName->Length:0);
		// 比较路径
		if(FALSE == IsRegGuardPath(szFullPath, szValueName, &nSubType))
			goto allowed;
		if(REG_SZ == Type)
		{
			wcsncpy(szValue, Data, arrayof(szValueName));
		}
		// 到用户求请
		if(FALSE != CheckRequestIsAllowed(MAKEGUARDTYPE(MASK_GUARDLITE_REGMON, nSubType)
			, szFullPath, szValueName, szValue))
		{
			goto allowed;
		}
	}
	return STATUS_ACCESS_DENIED;
allowed:
	return RealRegSetValueKey(KeyHandle, ValueName, TitleIndex, Type, Data, DataSize);
}
Ejemplo n.º 10
0
void kmem_cache_free (kmem_cache_t *cachep, void *objp)
{
	if (cachep->dtor != NULL) cachep->dtor(objp, cachep, 0); // 0 might be wrong --sadyc

#ifdef USE_NONPAGED_MEMORY
	ExFreeToNPagedLookasideList(&cachep->lookaside, objp);
#else
	ExFreeToPagedLookasideList(&cachep->lookaside, objp);
#endif
#if DBG
	cachep->objects_allocated--;
	printk("kmem_cache: %s: objects: %d [-]\n", cachep->name, cachep->objects_allocated);
#endif
}
Ejemplo n.º 11
0
NTSTATUS RemoveMatchExpression(__in WCHAR Expression[], __in ULONG ExpressionLength)
{
	// 这里要先判断链表是否为空
	if (IsListEmpty(&MatchExpressionList.HeadList))
	{
		KdPrint(("[ISISandBox] RemoveMatchExpression -> List is empty.\n"));
		return STATUS_SUCCESS;
	}

	KdPrint(("[ISISandBox] RemoveMatchExpression -> Get spinlock.\n"));
	KIRQL irql;
	KeAcquireSpinLock(&MatchExpressionList.Lock, &irql);

	// 链表头
	PLIST_ENTRY pList = MatchExpressionList.HeadList.Flink;

	BOOLEAN isFind = FALSE;
	while (pList != &MatchExpressionList.HeadList)
	{
		PMATCH_EXPRESSION element = CONTAINING_RECORD(pList, MATCH_EXPRESSION, ListEntry);

		if (RtlCompareMemory(element->Expression, Expression, ExpressionLength) == ExpressionLength)
		{
			pList->Blink->Flink = pList->Flink;
			pList->Flink->Blink = pList->Blink;
			pList = pList->Flink;

			// 这里的指针都已经断开了,即链表中不存在element了,现在只需要将其内存释放就OK了
			ExFreeToPagedLookasideList(&MatchExpressionList.PageList, element);
			KdPrint(("[ISISandBox] RemoveMatchExpression Delete expression | Expression : %S.\n", Expression));

			isFind = TRUE;
			break;
		}

		pList = pList->Flink;
	}

	KeReleaseSpinLock(&MatchExpressionList.Lock, irql);

	if (isFind)
		return STATUS_SUCCESS;
	else
	{
		KdPrint(("[ISISandBox] RemoveMatchExpression Cannot find expression : %S.\n", Expression));
		return STATUS_NOT_FOUND;
	}
}
Ejemplo n.º 12
0
/*
 * @implemented
 */
VOID
NTAPI
FsRtlUninitializeBaseMcb(IN PBASE_MCB Mcb)
{
    FsRtlResetBaseMcb(Mcb);

    if ((Mcb->PoolType == PagedPool)/* && (Mcb->MaximumPairCount == MAXIMUM_PAIR_COUNT)*/)
    {
        ExFreeToPagedLookasideList(&FsRtlFirstMappingLookasideList,
                                   Mcb->Mapping);
    }
    else
    {
        ExFreePoolWithTag(Mcb->Mapping, 'FSBC');
    }
}
Ejemplo n.º 13
0
__drv_mustHoldCriticalRegion
VOID
FFSFreeMcb(
	IN PFFS_MCB Mcb)
{
#ifndef __REACTOS__
    PFFS_MCB   Parent = Mcb->Parent;
#endif
    PAGED_CODE();

	ASSERT(Mcb != NULL);

	ASSERT((Mcb->Identifier.Type == FFSMCB) &&
			(Mcb->Identifier.Size == sizeof(FFS_MCB)));

	FFSPrint((DBG_INFO, "FFSFreeMcb: Mcb %S will be freed.\n", Mcb->ShortName.Buffer));

	if (Mcb->ShortName.Buffer)
		ExFreePool(Mcb->ShortName.Buffer);

	if (FlagOn(Mcb->Flags, MCB_FROM_POOL))
	{
		ExFreePool(Mcb);
	}
	else
	{
		ExAcquireResourceExclusiveLite(
				&FFSGlobal->LAResource,
				TRUE);

		ExFreeToPagedLookasideList(&(FFSGlobal->FFSMcbLookasideList), Mcb);

		ExReleaseResourceForThreadLite(
				&FFSGlobal->LAResource,
				ExGetCurrentResourceThread());
	}

	ExAcquireResourceExclusiveLite(
			&FFSGlobal->CountResource,
			TRUE);

	FFSGlobal->McbAllocated--;

	ExReleaseResourceForThreadLite(
			&FFSGlobal->CountResource,
			ExGetCurrentResourceThread());
}
Ejemplo n.º 14
0
NTSTATUS RemoveProtectProcess(__in HANDLE ProcessId)
{
	// 这里要先判断链表是否为空
	if (IsListEmpty(&ProtectProcessList.HeadList))
		return STATUS_SUCCESS;

	KIRQL irql;
	KeAcquireSpinLock(&ProtectProcessList.Lock, &irql);

	// 链表头
	PLIST_ENTRY pList = ProtectProcessList.HeadList.Flink;

	BOOLEAN isFind = FALSE;
	while (pList != &ProtectProcessList.HeadList)
	{
		PPROTECT_PROCESS element = CONTAINING_RECORD(pList, PROTECT_PROCESS, ListEntry);

		if (element->ProcessId == ProcessId)
		{
			pList->Blink->Flink = pList->Flink;
			pList->Flink->Blink = pList->Blink;
			pList = pList->Flink;

			// 这里的指针都已经断开了,即链表中不存在element了,现在只需要将其内存释放就OK了
			ExFreeToPagedLookasideList(&ProtectProcessList.PageList, element);
			KdPrint(("[ISISandBox] RemoveProtectProcess Delete process | ProcessId : %u.\n", ProcessId));

			isFind = TRUE;
			break;
		}

		pList = pList->Flink;
	}

	KeReleaseSpinLock(&ProtectProcessList.Lock, irql);

	if (isFind)
		return STATUS_SUCCESS;
	else
	{
		KdPrint(("[ISISandBox] RemoveProtectProcess Cannot find ProcessId : %u.\n", ProcessId));
		return STATUS_NOT_FOUND;
	}
}
Ejemplo n.º 15
0
__inline VOID
FsRtlFreeTunnelNode (
    PTUNNEL_NODE Node,
    PLIST_ENTRY FreePoolList OPTIONAL
    )
/*++

Routine Description:

    Free a node

Arguments:

    Node            - a tunnel node to free

    FreePoolList    - optional list to hold freeable pool memory

Return Value:

    None

-*/
{
    if (FreePoolList) {

        InsertHeadList(FreePoolList, &Node->ListLinks);

    } else {

        if (FlagOn(Node->Flags, TUNNEL_FLAG_NON_LOOKASIDE)) {
    
            ExFreePool(Node);
    
        } else {
    
            ExFreeToPagedLookasideList(&TunnelLookasideList, Node);
        }
    }
}
Ejemplo n.º 16
0
PFFS_MCB
FFSAllocateMcb(
	PFFS_VCB        Vcb,
	PUNICODE_STRING FileName,
	ULONG           FileAttr)
{
	PFFS_MCB    Mcb = NULL;
	PLIST_ENTRY List = NULL;

	ULONG       Extra = 0;

#define MCB_NUM_SHIFT   0x04

	if (FFSGlobal->McbAllocated > (FFSGlobal->MaxDepth << MCB_NUM_SHIFT))
		Extra = FFSGlobal->McbAllocated - 
			(FFSGlobal->MaxDepth << MCB_NUM_SHIFT) +
			FFSGlobal->MaxDepth;

	FFSPrint((DBG_INFO,
				"FFSAllocateMcb: CurrDepth=%xh/%xh/%xh FileName=%S\n", 
				FFSGlobal->McbAllocated,
				FFSGlobal->MaxDepth << MCB_NUM_SHIFT,
				FFSGlobal->FcbAllocated,
				FileName->Buffer));

	List = Vcb->McbList.Flink;

	while ((List != &(Vcb->McbList)) && (Extra > 0))
	{
		Mcb = CONTAINING_RECORD(List, FFS_MCB, Link);
		List = List->Flink;

		if ((Mcb->Inode != 2) && (Mcb->Child == NULL) &&
				(Mcb->FFSFcb == NULL) && (!IsMcbUsed(Mcb)))
		{
			FFSPrint((DBG_INFO, "FFSAllocateMcb: Mcb %S will be freed.\n",
						Mcb->ShortName.Buffer));

			if (FFSDeleteMcbNode(Vcb, Vcb->McbTree, Mcb))
			{
				FFSFreeMcb(Mcb);

				Extra--;
			}
		}
	}

	ExAcquireResourceExclusiveLite(
			&FFSGlobal->LAResource,
			TRUE);

	Mcb = (PFFS_MCB)(ExAllocateFromPagedLookasideList(
				&(FFSGlobal->FFSMcbLookasideList)));

	ExReleaseResourceForThreadLite(
			&FFSGlobal->LAResource,
			ExGetCurrentResourceThread());

	if (Mcb == NULL)
	{
		Mcb = (PFFS_MCB)ExAllocatePool(PagedPool, sizeof(FFS_MCB));

		RtlZeroMemory(Mcb, sizeof(FFS_MCB));

		SetFlag(Mcb->Flags, MCB_FROM_POOL);
	}
	else
	{
		RtlZeroMemory(Mcb, sizeof(FFS_MCB));
	}

	if (!Mcb)
	{
		return NULL;
	}

	Mcb->Identifier.Type = FFSMCB;
	Mcb->Identifier.Size = sizeof(FFS_MCB);

	if (FileName && FileName->Length)
	{
		Mcb->ShortName.Length = FileName->Length;
		Mcb->ShortName.MaximumLength = Mcb->ShortName.Length + 2;

		Mcb->ShortName.Buffer = ExAllocatePool(PagedPool, Mcb->ShortName.MaximumLength);

		if (!Mcb->ShortName.Buffer)
			goto errorout;

		RtlZeroMemory(Mcb->ShortName.Buffer, Mcb->ShortName.MaximumLength);
		RtlCopyMemory(Mcb->ShortName.Buffer, FileName->Buffer, Mcb->ShortName.Length);
	} 

	Mcb->FileAttr = FileAttr;

	ExAcquireResourceExclusiveLite(
			&FFSGlobal->CountResource,
			TRUE);

	FFSGlobal->McbAllocated++;

	ExReleaseResourceForThreadLite(
			&FFSGlobal->CountResource,
			ExGetCurrentResourceThread());

	return Mcb;

errorout:

	if (Mcb)
	{
		if (Mcb->ShortName.Buffer)
			ExFreePool(Mcb->ShortName.Buffer);

		if (FlagOn(Mcb->Flags, MCB_FROM_POOL))
		{
			ExFreePool(Mcb);
		}
		else
		{
			ExAcquireResourceExclusiveLite(
					&FFSGlobal->LAResource,
					TRUE);

			ExFreeToPagedLookasideList(&(FFSGlobal->FFSMcbLookasideList), Mcb);

			ExReleaseResourceForThreadLite(
					&FFSGlobal->LAResource,
					ExGetCurrentResourceThread());
		}
	}

	return NULL;
}
//
// Функция обработки запроса на запись.
//
NTSTATUS DispatchWrite(IN PDEVICE_OBJECT pDeviceObject, IN PIRP pIrp) {

	NTSTATUS status = STATUS_SUCCESS;
	PIO_STACK_LOCATION pIrpStack;
	ULONG info = 0;
	OpenFileEntry *entry;
	char* str;
	char* str1;
	PLIST_ENTRY link;
	int len;
	ANSI_STRING f;
	BOOLEAN FileNonExist = TRUE;
	int l;
	char *inputBuffer;
	int i;

	pIrpStack = IoGetCurrentIrpStackLocation(pIrp);

	if (pDeviceObject->Flags & DO_BUFFERED_IO) {
		// если для устройства определён буферизованный ввод/вывод,
		// то записываем данные в системный буфер
		inputBuffer = (char*)pIrp->AssociatedIrp.SystemBuffer;
	}
	else {
		// иначе непосредственно в пользовательский буфер
		inputBuffer = (char*)pIrp->UserBuffer;
	}

	// выделяем память для нового элемента и вставляем его в конец списка
	entry = (OpenFileEntry*)ExAllocateFromPagedLookasideList(&glPagedList);
	InsertTailList(&glOpenFiles, &entry->link);


	// копируем имя файла в созданный элемент
	RtlUnicodeStringToAnsiString(&entry->fileName, &pIrpStack->FileObject->FileName, TRUE);
	len = strlen(entry->fileName.Buffer) + 1;
	do
		str = ExAllocatePool(NonPagedPool, len);
	while (str == NULL);
	strcpy(str, entry->fileName.Buffer);
	if (strstr(str, "??") != NULL){
		do
			str1 = ExAllocatePool(NonPagedPool, len - 4);
		while (str1 == NULL);
		strcpy(str1, &str[4]);
		do
			entry->fullName.Buffer = AnsiToUnicode(str1);
		while (entry->fullName.Buffer == NULL);

		ExFreePool(str1);
	}
	else
		entry->fullName.Buffer = AnsiToUnicode(str);

	//если ввели "ddd" отчищаем весь список хукнутых файлов
	if (strstr(str, "ddd") != NULL){
		while (!IsListEmpty(&glOpenFiles)) {
			PLIST_ENTRY pLink = RemoveHeadList(&glOpenFiles);
			entry = CONTAINING_RECORD(pLink, OpenFileEntry, link);
			RtlFreeAnsiString(&entry->fileName);
			RtlFreeUnicodeString(&entry->fullName);
			ExFreeToPagedLookasideList(&glPagedList, entry);
		}

	}
	ExFreePool(str);

	return CompleteIrp(pIrp, status, info);
}
Ejemplo n.º 18
0
NTSTATUS EnumServices()
{
	//_asm int 3
	NTSTATUS status = STATUS_SUCCESS;
	ULONG	SubKeyIndex, ResultLength, ulSize;
	HANDLE					i, HandleRegKey = NULL;
	UNICODE_STRING			RegistryKeyName, KeyValue;
	UNICODE_STRING			KeyName;
	OBJECT_ATTRIBUTES		ObjectAttributes;
	PLIST_ENTRY pListHead = NULL, pListCur = NULL;
	PLDR_DATA_TABLE_ENTRY pLdrDataTable = NULL;
	PSERVICES_INFO pServicesInfo = NULL,\
		pPreServicesInfo = NULL;
	PKEY_BASIC_INFORMATION pKeyBasicInfo = NULL;
	PKEY_FULL_INFORMATION pKeyFullInfo = NULL;
	/************************************************************************/
	/* 
	User-mode Handle		Corresponding Object Name 
	HKEY_LOCAL_MACHINE		\Registry\Machine 
	HKEY_USERS				\Registry\User 
	HKEY_CLASSES_ROOT		No kernel-mode equivalent 
	HKEY_CURRENT_USER		No simple kernel-mode equivalent, but see Registry Run-Time Library Routines 
	*/
	/************************************************************************/

	WCHAR ServiceRegisterPath[] = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\";

	//pListHead = ((PLIST_ENTRY)pDriverObj->DriverSection)->Flink;
	//pListCur = pListHead;

	__try
	{

		FreePagedLookasideListForServices();
		ExInitializePagedLookasideList(&g_PageListServices, NULL, NULL, 0, sizeof(SERVICES_INFO), NULL, 0);

		RtlInitUnicodeString(&RegistryKeyName, ServiceRegisterPath);
		InitializeObjectAttributes(&ObjectAttributes, 
			&RegistryKeyName,
			OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
			NULL,    // handle
			NULL);
		status = ZwOpenKey(&HandleRegKey, KEY_READ, &ObjectAttributes);

		// 第一次调用是为了获取需要的长度
		ZwQueryKey(HandleRegKey, KeyFullInformation, NULL, 0, &ulSize);
		pKeyFullInfo = (PKEY_FULL_INFORMATION)ExAllocatePool(PagedPool, ulSize);
		// 第二次调用是为了获取数据
		ZwQueryKey(HandleRegKey, KeyFullInformation, pKeyFullInfo, ulSize, &ulSize);

		//循环遍历各个子项
		for (SubKeyIndex = 0; SubKeyIndex <pKeyFullInfo->SubKeys; SubKeyIndex++)
		{
			ZwEnumerateKey(HandleRegKey, SubKeyIndex, KeyBasicInformation, NULL, 0, &ulSize);
			pKeyBasicInfo = (PKEY_BASIC_INFORMATION)ExAllocatePool(PagedPool, ulSize);
			//获取第I个子项的数据
			ZwEnumerateKey(HandleRegKey, SubKeyIndex, KeyBasicInformation, pKeyBasicInfo, ulSize, &ulSize);

			pServicesInfo = (PSERVICES_INFO)ExAllocateFromPagedLookasideList(&g_PageListServices);
			RtlZeroMemory(pServicesInfo, sizeof(SERVICES_INFO));


			//服务的名称
			RtlCopyMemory(pServicesInfo->lpwzSrvName, pKeyBasicInfo->Name, pKeyBasicInfo->NameLength);
			KeyName.Buffer = (PWCH)ExAllocatePool(PagedPool, RegistryKeyName.Length + pKeyBasicInfo->NameLength);
			KeyName.Length = RegistryKeyName.Length + pKeyBasicInfo->NameLength;
			KeyName.MaximumLength = KeyName.Length;
			RtlZeroMemory(KeyName.Buffer, KeyName.Length);
			RtlCopyMemory(KeyName.Buffer, RegistryKeyName.Buffer, RegistryKeyName.Length);
			RtlCopyMemory((PUCHAR)KeyName.Buffer + RegistryKeyName.Length, pKeyBasicInfo->Name, pKeyBasicInfo->NameLength);
			if (!QueryServiceRunType(&KeyName, pServicesInfo))
			{
				if (NULL != pServicesInfo)
				{
					ExFreeToPagedLookasideList(&g_PageListServices, pServicesInfo);
					pServicesInfo = NULL;
				}
			}
			else
			{
				pServicesInfo->next = NULL;

				if (g_pServicesInfo == NULL)
				{
					g_pServicesInfo = pServicesInfo;
					pPreServicesInfo = pServicesInfo;
				}
				else
				{
					pPreServicesInfo->next = pServicesInfo;
					pPreServicesInfo = pServicesInfo;
				}
			}


			if (KeyName.Buffer != NULL)
			{
				ExFreePool(KeyName.Buffer);
				KeyName.Buffer = NULL;
			}

			if (pKeyBasicInfo != NULL)
			{
				ExFreePool(pKeyBasicInfo);
				pKeyBasicInfo = NULL;
			}
		}

	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		FreePagedLookasideListForServices();
		KdPrint(("Services:EnumServices failed!"));
		status = STATUS_UNSUCCESSFUL;
	}

	if (NULL != HandleRegKey)
	{
		ZwClose(HandleRegKey);
		HandleRegKey = NULL;
	}

	if (pKeyBasicInfo != NULL)
	{
		ExFreePool(pKeyBasicInfo);
		pKeyBasicInfo = NULL;
	}

	if (pKeyFullInfo != NULL)
	{
		ExFreePool(pKeyFullInfo);
		pKeyFullInfo = NULL;
	}

	return status;
}