BOOL TryIsProbeProcess(PCWSTR ApplicationName, PWSTR CommandLine) { UNICODE_STRING AppName, CmdLine; RtlInitUnicodeString(&AppName, ApplicationName); RtlInitUnicodeString(&CmdLine, CommandLine); SEH_TRY { if (CmdLine.Length < ProbeCommandLine.Length) return FALSE; CmdLine.Buffer = PtrAdd(CmdLine.Buffer, CmdLine.Length - ProbeCommandLine.Length); CmdLine.Length = ProbeCommandLine.Length; if (!RtlEqualUnicodeString(&CmdLine, &ProbeCommandLine, TRUE)) return FALSE; if (!RtlEqualUnicodeString(&AppName, &ProbeApplicationName, TRUE)) return FALSE; return TRUE; } SEH_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { return FALSE; } }
static VOID HistoryAddEntry(PCSRSS_CONSOLE Console) { UNICODE_STRING NewEntry; PHISTORY_BUFFER Hist; INT i; NewEntry.Length = NewEntry.MaximumLength = Console->LineSize * sizeof(WCHAR); NewEntry.Buffer = Console->LineBuffer; if (!(Hist = HistoryCurrentBuffer(Console))) return; /* Don't add blank or duplicate entries */ if (NewEntry.Length == 0 || Hist->MaxEntries == 0 || (Hist->NumEntries > 0 && RtlEqualUnicodeString(&Hist->Entries[Hist->NumEntries - 1], &NewEntry, FALSE))) { return; } if (Console->HistoryNoDup) { /* Check if this line has been entered before */ for (i = Hist->NumEntries - 1; i >= 0; i--) { if (RtlEqualUnicodeString(&Hist->Entries[i], &NewEntry, FALSE)) { /* Just rotate the list to bring this entry to the end */ NewEntry = Hist->Entries[i]; memmove(&Hist->Entries[i], &Hist->Entries[i + 1], (Hist->NumEntries - (i + 1)) * sizeof(UNICODE_STRING)); Hist->Entries[Hist->NumEntries - 1] = NewEntry; Hist->Position = Hist->NumEntries - 1; return; } } } if (Hist->NumEntries == Hist->MaxEntries) { /* List is full, remove oldest entry */ RtlFreeUnicodeString(&Hist->Entries[0]); memmove(&Hist->Entries[0], &Hist->Entries[1], --Hist->NumEntries * sizeof(UNICODE_STRING)); } if (NT_SUCCESS(RtlDuplicateUnicodeString(0, &NewEntry, &Hist->Entries[Hist->NumEntries]))) Hist->NumEntries++; Hist->Position = Hist->NumEntries - 1; }
// Attention! PID has a HANDLE type. But it still is PID. VOID DDKAPI load_image_watcher(PUNICODE_STRING uszFullImageName, HANDLE dwProcessId, PIMAGE_INFO pImageInfo) { //DbgPrint("LI callback runned PID: %d, Name: %wZ\r\n", // dwProcessId, uszFullImageName); int j; for (j = 0; j < g_used_progs && !RtlEqualUnicodeString(&g_usz_hprogs[j], uszFullImageName, TRUE); ++j) //DbgPrint("%wZ\r\nvs\r\n%wZ\r\n", &g_usz_hprogs[j], uszFullImageName); ; if (j == g_used_progs) return; int i; // Let us find a free entry for (i = 0; i < ENT_CNT && g_proc_table[i].pid; ++i); if (g_proc_table[i].pid) { // No more free entries DbgPrint("Sorry, can not handle this process\r\n"); return; } g_proc_table[i].pid = dwProcessId; run_process(i, g_pwc_rprogs[j]); return; }
BOOL CALLBACK kull_m_handle_getHandlesOfType_callback(PSYSTEM_HANDLE pSystemHandle, PVOID pvArg) { PHANDLE_ENUM_DATA pData = (PHANDLE_ENUM_DATA) pvArg; BOOL status = TRUE; HANDLE hProcess, hRemoteHandle; POBJECT_TYPE_INFORMATION pInfos; ULONG szNeeded; if(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pSystemHandle->ProcessId)) { if(DuplicateHandle(hProcess, (HANDLE) pSystemHandle->Handle, GetCurrentProcess(), &hRemoteHandle, pData->dwDesiredAccess, TRUE, pData->dwOptions)) { if(NtQueryObject(hRemoteHandle, ObjectTypeInformation, NULL, 0, &szNeeded) == STATUS_INFO_LENGTH_MISMATCH) { if(pInfos = (POBJECT_TYPE_INFORMATION) LocalAlloc(LPTR, szNeeded)) { if(NT_SUCCESS(NtQueryObject(hRemoteHandle, ObjectTypeInformation, pInfos, szNeeded, &szNeeded))) { if(!pData->type || RtlEqualUnicodeString(&pInfos->TypeName, pData->type, TRUE)) status = pData->callBack(hRemoteHandle, pSystemHandle, pData->pvArg); } LocalFree(pInfos); } } CloseHandle(hRemoteHandle); } CloseHandle(hProcess); } return status; }
/*! * 查找目标模块 * * 通过该驱动对象的 DriverSection 域,顺序查询内核模块链表,比较模块名是否相同(不区分大小写),返回目标模块信息 * * @param DriverObject DriverEntry传递进来的驱动对象 * @param pDestDriverName 目标模块名称 * @return 目标模块信息 */ PLDR_DATA_TABLE_ENTRY FindModule(IN PDRIVER_OBJECT DriverObject, PUNICODE_STRING pDestDriverName) { PLDR_DATA_TABLE_ENTRY pModuleCurrent = NULL; PLDR_DATA_TABLE_ENTRY PStop = NULL; if (DriverObject == NULL) return 0; pModuleCurrent = (PLDR_DATA_TABLE_ENTRY)(DriverObject->DriverSection); if (pModuleCurrent == NULL) return 0; PStop = pModuleCurrent; do { if ( NULL == pDestDriverName) { // ntoskrnl.exe,\SystemRoot\system32\ntkrnlpa.exe, 基地址 - 大小0x410000 KdPrint(("%wZ [0x%04X - 0x%04X] %wZ\n",&pModuleCurrent->BaseDllName,pModuleCurrent->DllBase,pModuleCurrent->SizeOfImage,&pModuleCurrent->FullDllName)) ; } else { if ( RtlEqualUnicodeString( &pModuleCurrent->BaseDllName,pDestDriverName,FALSE )) return pModuleCurrent ; } pModuleCurrent = (PLDR_DATA_TABLE_ENTRY)pModuleCurrent->InLoadOrderLinks.Flink; } while ( pModuleCurrent != PStop ); return NULL; }
void CheckFileToHideAgainstFolder(Folder* folder, UNICODE_STRING* directory, UNICODE_STRING* filename, BOOLEAN* hideFile) { if (RtlEqualUnicodeString(directory, &folder->VolumeDirPath, FALSE)) { CheckFileToHideAgainstFolderFileNames(folder, directory, filename, hideFile); } }
static NTSTATUS TestIrpHandler( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN PIO_STACK_LOCATION IoStackLocation) { NTSTATUS Status = STATUS_NOT_SUPPORTED; PAGED_CODE(); DPRINT("IRP %x/%x\n", IoStackLocation->MajorFunction, IoStackLocation->MinorFunction); ASSERT(IoStackLocation->MajorFunction == IRP_MJ_DIRECTORY_CONTROL); ok(IoStackLocation->MinorFunction == IRP_MN_QUERY_DIRECTORY, "Minor function: %u\n", IoStackLocation->MinorFunction); if (IoStackLocation->MinorFunction == IRP_MN_QUERY_DIRECTORY) { ok(IoStackLocation->Parameters.QueryDirectory.FileInformationClass == FileBothDirectoryInformation, "FileInformationClass: %d\n", IoStackLocation->Parameters.QueryDirectory.FileInformationClass); if (IoStackLocation->Parameters.QueryDirectory.FileInformationClass == FileBothDirectoryInformation) { ok(RtlEqualUnicodeString(IoStackLocation->Parameters.QueryDirectory.FileName, &ExpectedExpression, FALSE), "Expression is '%wZ', expected '%wZ'\n", IoStackLocation->Parameters.QueryDirectory.FileName, &ExpectedExpression); RtlZeroMemory(Irp->UserBuffer, IoStackLocation->Parameters.QueryDirectory.Length); Status = STATUS_SUCCESS; } } Irp->IoStatus.Status = Status; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return Status; }
/* * @implemented */ BOOLEAN RedirectSavedLink(IN PSAVED_LINK_INFORMATION SavedLinkInformation, IN PUNICODE_STRING DosName, IN PUNICODE_STRING NewLink) { PLIST_ENTRY NextEntry; PSYMLINK_INFORMATION SymlinkInformation; /* Find the link */ for (NextEntry = SavedLinkInformation->SymbolicLinksListHead.Flink; NextEntry != &(SavedLinkInformation->SymbolicLinksListHead); NextEntry = NextEntry->Flink) { SymlinkInformation = CONTAINING_RECORD(NextEntry, SYMLINK_INFORMATION, SymbolicLinksListEntry); if (!RtlEqualUnicodeString(DosName, &(SymlinkInformation->Name), TRUE)) { /* Delete old link */ GlobalDeleteSymbolicLink(DosName); /* Set its new location */ GlobalCreateSymbolicLink(DosName, NewLink); /* And remove it from the list (not valid any more) */ RemoveEntryList(&(SymlinkInformation->SymbolicLinksListEntry)); FreePool(SymlinkInformation->Name.Buffer); FreePool(SymlinkInformation); return TRUE; } } return FALSE; }
BOOLEAN NTAPI PhpGetImageBaseCallback( __in PLDR_DATA_TABLE_ENTRY Module, __in_opt PVOID Context ) { PPHP_GET_IMAGE_BASE_CONTEXT context = Context; if (RtlEqualUnicodeString(&Module->FullDllName, &context->ImagePath, TRUE) || RtlEqualUnicodeString(&Module->BaseDllName, &context->ImagePath, TRUE)) { context->BaseAddress = Module->DllBase; return FALSE; } return TRUE; }
static NTSTATUS _DeleteFilter(PWCHAR Filters, PSIZE_T ResultLength) { UNICODE_STRING uFilter; SIZE_T len = 0; PWCHAR ours = NULL; PWCHAR tmp = Filters; NTSTATUS status = STATUS_UNSUCCESSFUL; DEBUG_ENTER_FUNCTION("Filters=\"%S\"; ResultLength=0x%p", Filters, ResultLength); status = STATUS_SUCCESS; while (*tmp != L'\0') { len = wcslen(tmp); RtlInitUnicodeString(&uFilter, tmp); if (RtlEqualUnicodeString(&uFilter, &_driverServiceName, TRUE)) ours = tmp; tmp += (len + 1); } if (ours != NULL) { ++tmp; *ResultLength = (tmp - Filters)*sizeof(WCHAR) - _driverServiceName.Length - sizeof(WCHAR); memmove(ours, ours + _driverServiceName.Length / sizeof(WCHAR) + 1, sizeof(WCHAR)*(tmp - ours - _driverServiceName.Length / sizeof(WCHAR) - 1)); } else status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_EXIT_FUNCTION("0x%x, *ResultLength=%Iu", status, *ResultLength); return status; }
BOOLEAN _VolumeEntryShouldAttach( _In_ PVOLUME_ENTRY VolumeEntry, _In_ PCUNICODE_STRING VolumeName) { return RtlEqualUnicodeString(&VolumeEntry->DeviceName, VolumeName, FALSE); }
/* * @implemented */ BOOLEAN IsDriveLetter(PUNICODE_STRING SymbolicName) { WCHAR Letter; BOOLEAN Result = FALSE; /* We must have a precise length */ if (SymbolicName->Length != sizeof(DosDevices.Buffer) + 2 * sizeof(WCHAR)) { return FALSE; } /* Check if len is correct */ Letter = SymbolicName->Buffer[sizeof(DosDevices.Buffer) / sizeof(WCHAR)]; if (((Letter >= L'A' && Letter <= L'Z') || Letter == (WCHAR)-1) && SymbolicName->Buffer[(sizeof(DosDevices.Buffer) + sizeof(WCHAR)) / sizeof (WCHAR)] == L':') { /* In case it's not a normal drive letter, check differently */ SymbolicName->Length = sizeof(DosDevices.Buffer); Result = RtlEqualUnicodeString(SymbolicName, &DosDevices, TRUE); SymbolicName->Length = sizeof(DosDevices.Buffer) + 2 * sizeof(WCHAR); } return Result; }
static PDEVICE_OBJECT IopTraverseDeviceNode(PDEVICE_NODE Node, PUNICODE_STRING DeviceInstance) { PDEVICE_OBJECT DeviceObject; PDEVICE_NODE ChildNode; if (RtlEqualUnicodeString(&Node->InstancePath, DeviceInstance, TRUE)) { ObReferenceObject(Node->PhysicalDeviceObject); return Node->PhysicalDeviceObject; } /* Traversal of all children nodes */ for (ChildNode = Node->Child; ChildNode != NULL; ChildNode = ChildNode->Sibling) { DeviceObject = IopTraverseDeviceNode(ChildNode, DeviceInstance); if (DeviceObject != NULL) { return DeviceObject; } } return NULL; }
/*! \brief Find cached symbol file. * * Looks through the list of cached symbol files and tries to find an already * loaded one. * * \param FileName FileName of the symbol file to look for. * * \returns A pointer to the cached symbol info. * \retval NULL No cached info found. * * \sa KdbpSymAddCachedFile */ PROSSYM_INFO KdbpSymFindCachedFile( IN PUNICODE_STRING FileName) { PIMAGE_SYMBOL_INFO_CACHE Current; PLIST_ENTRY CurrentEntry; KIRQL Irql; KeAcquireSpinLock(&SymbolFileListLock, &Irql); CurrentEntry = SymbolFileListHead.Flink; while (CurrentEntry != (&SymbolFileListHead)) { Current = CONTAINING_RECORD(CurrentEntry, IMAGE_SYMBOL_INFO_CACHE, ListEntry); if (RtlEqualUnicodeString(&Current->FileName, FileName, TRUE)) { Current->RefCount++; KeReleaseSpinLock(&SymbolFileListLock, Irql); DPRINT("Found cached file!\n"); return Current->RosSymInfo; } CurrentEntry = CurrentEntry->Flink; } KeReleaseSpinLock(&SymbolFileListLock, Irql); DPRINT("Cached file not found!\n"); return NULL; }
static PHISTORY_BUFFER HistoryCurrentBuffer(PCSRSS_CONSOLE Console) { /* TODO: use actual EXE name sent from process that called ReadConsole */ UNICODE_STRING ExeName = { 14, 14, L"cmd.exe" }; PLIST_ENTRY Entry = Console->HistoryBuffers.Flink; PHISTORY_BUFFER Hist; for (; Entry != &Console->HistoryBuffers; Entry = Entry->Flink) { Hist = CONTAINING_RECORD(Entry, HISTORY_BUFFER, ListEntry); if (RtlEqualUnicodeString(&ExeName, &Hist->ExeName, FALSE)) return Hist; } /* Couldn't find the buffer, create a new one */ Hist = HeapAlloc(Win32CsrApiHeap, 0, sizeof(HISTORY_BUFFER) + ExeName.Length); if (!Hist) return NULL; Hist->MaxEntries = Console->HistoryBufferSize; Hist->NumEntries = 0; Hist->Entries = HeapAlloc(Win32CsrApiHeap, 0, Hist->MaxEntries * sizeof(UNICODE_STRING)); if (!Hist->Entries) { HeapFree(Win32CsrApiHeap, 0, Hist); return NULL; } Hist->ExeName.Length = Hist->ExeName.MaximumLength = ExeName.Length; Hist->ExeName.Buffer = (PWCHAR)(Hist + 1); memcpy(Hist->ExeName.Buffer, ExeName.Buffer, ExeName.Length); InsertHeadList(&Console->HistoryBuffers, &Hist->ListEntry); return Hist; }
SECURITY_STATUS SEC_ENTRY QuerySecurityPackageInfoW( PSECURITY_STRING pssPackageName, // Name of package PSecPkgInfo * ppPackageInfo // Receives package info ) { UNICODE_STRING PackageName; ULONG PackageCount; PAGED_CODE(); RtlInitUnicodeString( &PackageName, NTLMSP_NAME ); if (!RtlEqualUnicodeString( pssPackageName, &PackageName, TRUE // case insensitive )) { return(SEC_E_SECPKG_NOT_FOUND); } return(EnumerateSecurityPackages(&PackageCount,ppPackageInfo)); }
static PNTOS_INSTALLATION FindExistingNTOSInstall( IN PGENERIC_LIST List, IN PCWSTR SystemRootArcPath OPTIONAL, IN PUNICODE_STRING SystemRootNtPath OPTIONAL // or PCWSTR ? ) { PGENERIC_LIST_ENTRY Entry; PNTOS_INSTALLATION NtOsInstall; UNICODE_STRING SystemArcPath; /* * We search either via ARC path or NT path. * If both pointers are NULL then we fail straight away. */ if (!SystemRootArcPath && !SystemRootNtPath) return NULL; RtlInitUnicodeString(&SystemArcPath, SystemRootArcPath); Entry = GetFirstListEntry(List); while (Entry) { NtOsInstall = (PNTOS_INSTALLATION)GetListEntryUserData(Entry); Entry = GetNextListEntry(Entry); /* * Note that if both ARC paths are equal, then the corresponding * NT paths must be the same. However, two ARC paths may be different * but resolve into the same NT path. */ if ( (SystemRootArcPath && RtlEqualUnicodeString(&NtOsInstall->SystemArcPath, &SystemArcPath, TRUE)) || (SystemRootNtPath && RtlEqualUnicodeString(&NtOsInstall->SystemNtPath, SystemRootNtPath, TRUE)) ) { /* Found it! */ return NtOsInstall; } } return NULL; }
BOOLEAN FilterCharDevs ( IN PSERVER_REQUEST_PACKET Srp, IN PVOID Block ) /*++ Routine Description: This routine is intended to be called by SrvEnumApiHandler to check whether a particular comm device should be returned. Arguments: Srp - a pointer to the SRP for the operation. Name1 is specified NetCharDevGetInfo, and if set must match the DOS path name of the device for the device to be returned. Block - a pointer to the comm device to check. Return Value: TRUE if the block should be placed in the output buffer, FALSE if it should be passed over. --*/ { PCOMM_DEVICE commDevice = Block; PAGED_CODE( ); // // If there's a device name in the SRP, it must match the // DOS path name of the device. // if ( Srp->Name1.Length > 0 ) { if ( !RtlEqualUnicodeString( &Srp->Name1, &commDevice->DosPathName, TRUE ) ) { return FALSE; } } // // We want the comm device. // return TRUE; } // FilterCharDevs
PUNC_PROVIDER MupCheckForUnregisteredProvider( PUNICODE_STRING DeviceName ) /*++ Routine Description: This routine checks the list of unregistered providers for one whose device name matches the provider attempting to register. If one is found it is dequeued from the list of unregistered providers. Arguments: DeviceName - The device name of the registering provider. Return Value: UNC_PROVIDER - A pointer to the matching unregistered provider, or NULL if no match is found. --*/ { PLIST_ENTRY listEntry; PUNC_PROVIDER uncProvider; PAGED_CODE(); MupAcquireGlobalLock(); for (listEntry = MupUnregisteredProviderList.Flink; listEntry != &MupUnregisteredProviderList; listEntry = listEntry->Flink ) { uncProvider = CONTAINING_RECORD( listEntry, UNC_PROVIDER, ListEntry ); // // If we find a match take it out of the unregistered list, and // return it to the caller. // if ( RtlEqualUnicodeString( DeviceName, &uncProvider->DeviceName, TRUE )) { RemoveEntryList( listEntry ); uncProvider->BlockHeader.BlockState = BlockStateActive; MupReleaseGlobalLock(); return uncProvider; } } MupReleaseGlobalLock(); return NULL; }
BOOL Initialize2(PVOID BaseAddress) { BOOL QQUINSpecified; NTSTATUS Status; PVOID module; ULONG_PTR CreateThreadIAT; PROCESS_BASIC_INFORMATION BasicInfo; PLDR_MODULE Self, Netapi32; ml::MlInitialize(); LdrDisableThreadCalloutsForDll(BaseAddress); Self = FindLdrModuleByHandle(nullptr); if (RtlEqualUnicodeString(&Self->BaseDllName, &USTR(L"QQ.exe"), TRUE) == FALSE && RtlEqualUnicodeString(&Self->BaseDllName, &USTR(L"QQ2.exe"), TRUE) == FALSE) { return TRUE; } InitializeQqFunctionTable(); PVOID DllNotificationCookie; LdrRegisterDllNotification(0, [] (ULONG NotificationReason, PCLDR_DLL_NOTIFICATION_DATA NotificationData, PVOID Context) { PDLL_HOOK_ENTRY Entry; if (NotificationReason != LDR_DLL_NOTIFICATION_REASON_LOADED) return; FOR_EACH_ARRAY(Entry, Hooks) { if (RtlEqualUnicodeString(&Entry->DllName, NotificationData->Loaded.BaseDllName, TRUE) == FALSE) continue; Entry->HookRoutine(NotificationData->Loaded.DllBase); break; } },
void CheckFileToHideAgainstFolderFileNames(Folder* folder, UNICODE_STRING* directory, UNICODE_STRING* filename, BOOLEAN* hideFile) { for (size_t j = 0; j < folder->FileNames.size; j++) { UNICODE_STRING* vectFileName = UnicodeStringVectorGet(&folder->FileNames, j); if (RtlEqualUnicodeString(filename, vectFileName, FALSE)) { DBG_PRINT("SecretStash!ShouldHideFile: Hiding %wZ\\%wZ!", &directory, &filename); *hideFile = TRUE; } } }
ULONG WINAPI BaseIsDosApplication(IN PUNICODE_STRING PathName, IN NTSTATUS Status) { UNICODE_STRING String; /* Is it a .com? */ String.Length = BaseDotComSuffixName.Length; String.Buffer = &PathName->Buffer[(PathName->Length - String.Length) / sizeof(WCHAR)]; if (RtlEqualUnicodeString(&String, &BaseDotComSuffixName, TRUE)) return 2; /* Is it a .pif? */ String.Length = BaseDotPifSuffixName.Length; String.Buffer = &PathName->Buffer[(PathName->Length - String.Length) / sizeof(WCHAR)]; if (RtlEqualUnicodeString(&String, &BaseDotPifSuffixName, TRUE)) return 3; /* Is it an exe? */ String.Length = BaseDotExeSuffixName.Length; String.Buffer = &PathName->Buffer[(PathName->Length - String.Length) / sizeof(WCHAR)]; if (RtlEqualUnicodeString(&String, &BaseDotExeSuffixName, TRUE)) return 1; return 0; }
HANDLE GetPidAndTidByName(PWCHAR ProcessName, PHANDLE pThreadId) { HANDLE Ret = 0; PVOID SysInfo; ULONG Size = 0x1000; NTSTATUS St; UNICODE_STRING NeededName; do { SysInfo = ExAllocatePool(NonPagedPool, Size); if (!SysInfo) return Ret; St = ZwQuerySystemInformation(SystemProcessInformation, SysInfo, Size, NULL); if (St == STATUS_INFO_LENGTH_MISMATCH) { ExFreePool(SysInfo); Size *= 2; } else if (!NT_SUCCESS(St)) { ExFreePool(SysInfo); return Ret; } } while (St == STATUS_INFO_LENGTH_MISMATCH); RtlInitUnicodeString(&NeededName, ProcessName); PSYSTEM_PROCESS_INFORMATION pProcess = (PSYSTEM_PROCESS_INFORMATION)SysInfo; for (;;) { if (RtlEqualUnicodeString(&NeededName, &pProcess->ImageName, TRUE)) { Ret = pProcess->ProcessId; *pThreadId = pProcess->Threads[0].ClientId.UniqueThread; break; } if (!pProcess->NextEntryOffset) break; pProcess = (PSYSTEM_PROCESS_INFORMATION)((PUCHAR)pProcess + pProcess->NextEntryOffset); } ExFreePool(SysInfo); return Ret; }
/* * SfuElevatePriv * * Purpose: * * Attempt to elevate current thread privileges by impersonating lsass thread token and adding privilegs next. * */ BOOL SfuElevatePriv( VOID ) { BOOLEAN WasEnabled; BOOL cond = FALSE, bResult = FALSE; NTSTATUS status; PSYSTEM_PROCESSES_INFORMATION ProcessList = NULL, pList; UNICODE_STRING uLookupProcess; ULONG i; do { status = RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &WasEnabled); if (!NT_SUCCESS(status)) break; ProcessList = SfuGetSystemInfo(SystemProcessInformation); if (ProcessList == NULL) break; RtlInitUnicodeString(&uLookupProcess, L"lsass.exe"); pList = ProcessList; for (;;) { if (RtlEqualUnicodeString(&uLookupProcess, &pList->ImageName, TRUE)) { for (i = 0; i < pList->ThreadCount; i++) { bResult = SfuAdjustCurrentThreadPriv(&pList->Threads[i].ClientId); if (bResult) break; } break; } if (pList->NextEntryDelta == 0) { break; } pList = (PSYSTEM_PROCESSES_INFORMATION)(((LPBYTE)pList) + pList->NextEntryDelta); } } while (cond); if (ProcessList != NULL) RtlFreeHeap(NtCurrentPeb()->ProcessHeap, 0, ProcessList); return bResult; }
PGRAPHICS_DEVICE NTAPI EngpFindGraphicsDevice( _In_opt_ PUNICODE_STRING pustrDevice, _In_ ULONG iDevNum, _In_ DWORD dwFlags) { UNICODE_STRING ustrCurrent; PGRAPHICS_DEVICE pGraphicsDevice; ULONG i; TRACE("EngpFindGraphicsDevice('%wZ', %lu, 0x%lx)\n", pustrDevice, iDevNum, dwFlags); /* Lock list */ EngAcquireSemaphore(ghsemGraphicsDeviceList); if (pustrDevice && pustrDevice->Buffer) { /* Loop through the list of devices */ for (pGraphicsDevice = gpGraphicsDeviceFirst; pGraphicsDevice; pGraphicsDevice = pGraphicsDevice->pNextGraphicsDevice) { /* Compare the device name */ RtlInitUnicodeString(&ustrCurrent, pGraphicsDevice->szWinDeviceName); if (RtlEqualUnicodeString(&ustrCurrent, pustrDevice, FALSE)) { break; } } } else { /* Loop through the list of devices */ for (pGraphicsDevice = gpGraphicsDeviceFirst, i = 0; pGraphicsDevice && i < iDevNum; pGraphicsDevice = pGraphicsDevice->pNextGraphicsDevice, i++); } /* Unlock list */ EngReleaseSemaphore(ghsemGraphicsDeviceList); return pGraphicsDevice; }
BOOL ResStrCmp( PUNICODE_STRING pstr1, PUNICODE_STRING pstr2) { if (pstr1->Length == 0) { /* * pstr1 is a resource ID, so just compare the values. */ if (pstr1->Buffer == pstr2->Buffer) return TRUE; } else { /* * pstr1 is a string. if pstr2 is an actual string compare the * string values; if pstr2 is not a string then pstr1 may be an * "integer string" of the form "#123456". so convert it to an * integer and compare the integers. * Before calling lstrcmp(), make sure pstr2 is an actual * string, not a resource ID. */ if (pstr2->Length != 0) { if (RtlEqualUnicodeString(pstr1, pstr2, TRUE)) return TRUE; } else if (pstr1->Buffer[0] == '#') { UNICODE_STRING strId; int id; strId.Length = pstr1->Length - sizeof(WCHAR); strId.MaximumLength = strId.Length; strId.Buffer = pstr1->Buffer + 1; RtlUnicodeStringToInteger(&strId, 10, (PULONG)&id); if (id == (int)pstr2->Buffer) return TRUE; } } return FALSE; }
//失败返回0 ULONG GetTcpipProtocolBlock() { UNICODE_STRING uniTCPIP; ULONG uHeader=0; NTSTATUS status = STATUS_SUCCESS; struct my_NDIS_PROTOCOL_BLOCK *pProtoBLock=NULL; BOOLEAN bFound = FALSE; struct my_NDIS_PROTOCOL_BLOCK *pTcpipProtocolBlock=NULL; do { RtlInitUnicodeString(&uniTCPIP, L"tcpip"); uHeader = GetProtocolHeader(); if (uHeader==0) { status = STATUS_UNSUCCESSFUL; break; } pProtoBLock = (struct my_NDIS_PROTOCOL_BLOCK *)uHeader; while(pProtoBLock) { if (RtlEqualUnicodeString(&pProtoBLock->ProtocolCharacteristics.Ndis40Chars.Name, &uniTCPIP,TRUE)) { bFound = TRUE; break; } pProtoBLock = pProtoBLock->NextProtocol; } if (!bFound) { kprintf("Can not find tcpip.sys by its protocol name: tcpip\n"); break; } pTcpipProtocolBlock = pProtoBLock; //NdisDeregisterProtocol(&status, (NDIS_HANDLE)uHeader); // deregister it } while (0); return (ULONG)pTcpipProtocolBlock; }
USHORT NTAPI PpInitGetGroupOrderIndex(IN HANDLE ServiceHandle) { NTSTATUS Status; PKEY_VALUE_FULL_INFORMATION KeyValueInformation; USHORT i; PVOID Buffer; UNICODE_STRING Group; PAGED_CODE(); /* Make sure we have a cache */ if (!PiInitGroupOrderTable) return -1; /* If we don't have a handle, the rest is easy -- return the count */ if (!ServiceHandle) return PiInitGroupOrderTableCount + 1; /* Otherwise, get the group value */ Status = IopGetRegistryValue(ServiceHandle, L"Group", &KeyValueInformation); if (!NT_SUCCESS(Status)) return PiInitGroupOrderTableCount; /* Make sure we have a valid string */ ASSERT(KeyValueInformation->Type == REG_SZ); ASSERT(KeyValueInformation->DataLength); /* Convert to unicode string */ Buffer = (PVOID)((ULONG_PTR)KeyValueInformation + KeyValueInformation->DataOffset); PnpRegSzToString(Buffer, KeyValueInformation->DataLength, &Group.Length); Group.MaximumLength = (USHORT)KeyValueInformation->DataLength; Group.Buffer = Buffer; /* Loop the groups */ for (i = 0; i < PiInitGroupOrderTableCount; i++) { /* Try to find a match */ if (RtlEqualUnicodeString(&Group, &PiInitGroupOrderTable[i], TRUE)) break; } /* We're done */ ExFreePool(KeyValueInformation); return i; }
PVOID GetProcAddressInModule(PWCHAR ModuleName, PCHAR FunctionName) { NTSTATUS St; PROCESS_BASIC_INFORMATION Info; PVOID pModuleBase = NULL; ULONG t; St = ZwQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &Info, sizeof(Info), &t); if (NT_SUCCESS(St)) { UNICODE_STRING uStr; PPEB Peb = Info.PebBaseAddress; RtlInitUnicodeString(&uStr, ModuleName); LIST_ENTRY* head = &Peb->LoaderData->InLoadOrderModuleList; for (LIST_ENTRY* entry = head->Flink; entry != head; entry = entry->Flink) { LDR_DATA_TABLE_ENTRY* ldr_entry = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); if (RtlEqualUnicodeString(&ldr_entry->BaseDllName, &uStr, TRUE)) { pModuleBase = ldr_entry->DllBase; break; } } } if (pModuleBase) { return GetProcedureAddressByHash(pModuleBase, FunctionName); } else { DbgPrint("pModuleBase error\n"); } return NULL; }
static NTSTATUS _AppendFilter(BOOLEAN Beginning, PWCHAR Filters, PSIZE_T ResultLength) { SIZE_T len = 0; UNICODE_STRING uFilter; PWCHAR tmp = Filters; SIZE_T dataLength = sizeof(WCHAR); NTSTATUS status = STATUS_UNSUCCESSFUL; DEBUG_ENTER_FUNCTION("Beginning=%u; Filters=\"%S\"; ResultLength=0x%p", Beginning, Filters, ResultLength); status = STATUS_SUCCESS; while (*tmp != L'\0') { len = wcslen(tmp); dataLength += ((len + 1)*sizeof(WCHAR)); RtlInitUnicodeString(&uFilter, tmp); if (RtlEqualUnicodeString(&uFilter, &_driverServiceName, TRUE)) { status = STATUS_OBJECT_NAME_COLLISION; break; } tmp += (len + 1); } if (NT_SUCCESS(status)) { if (Beginning) { memmove(Filters + _driverServiceName.Length / sizeof(WCHAR) + 1, Filters, dataLength); memcpy(Filters, _driverServiceName.Buffer, _driverServiceName.Length); Filters[_driverServiceName.Length / sizeof(WCHAR)] = L'\0'; } else { memcpy(Filters + dataLength / sizeof(WCHAR) - 1, _driverServiceName.Buffer, _driverServiceName.Length); Filters[dataLength / sizeof(WCHAR) - 1 + _driverServiceName.Length / sizeof(WCHAR)] = L'\0'; Filters[dataLength / sizeof(WCHAR) + _driverServiceName.Length / sizeof(WCHAR)] = L'\0'; } *ResultLength = dataLength + _driverServiceName.Length + sizeof(WCHAR); } DEBUG_EXIT_FUNCTION("0x%x, *ResultLength=%Iu", status, *ResultLength); return status; }