/* * @implemented */ BOOLEAN WINAPI DllMain(HINSTANCE hDllHandle, DWORD nReason, LPVOID Reserved) { switch(nReason) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hDllHandle); if (NtCurrentPeb()->ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_PROFILE_USER) { PsParseCommandLine(); PsInitializeAndStartProfile(); } break; case DLL_PROCESS_DETACH: if (NtCurrentPeb()->ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_PROFILE_USER) { PsStopAndAnalyzeProfile(); } break; } return TRUE; }
/* * @implemented */ PVOID NTAPI RtlPcToFileHeader(IN PVOID PcValue, PVOID* BaseOfImage) { PLIST_ENTRY ModuleListHead; PLIST_ENTRY Entry; PLDR_DATA_TABLE_ENTRY Module; PVOID ImageBase = NULL; RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock); ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList; Entry = ModuleListHead->Flink; while (Entry != ModuleListHead) { Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); if ((ULONG_PTR)PcValue >= (ULONG_PTR)Module->DllBase && (ULONG_PTR)PcValue < (ULONG_PTR)Module->DllBase + Module->SizeOfImage) { ImageBase = Module->DllBase; break; } Entry = Entry->Flink; } RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock); *BaseOfImage = ImageBase; return ImageBase; }
VOID TaskDialogCreateIcons( _In_ PPH_SETUP_CONTEXT Context ) { HICON largeIcon; HICON smallIcon; largeIcon = PhLoadIcon( NtCurrentPeb()->ImageBaseAddress, MAKEINTRESOURCE(IDI_ICON1), PH_LOAD_ICON_SIZE_LARGE, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON) ); smallIcon = PhLoadIcon( NtCurrentPeb()->ImageBaseAddress, MAKEINTRESOURCE(IDI_ICON1), PH_LOAD_ICON_SIZE_LARGE, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON) ); Context->IconLargeHandle = largeIcon; Context->IconSmallHandle = smallIcon; SendMessage(Context->DialogHandle, WM_SETICON, ICON_SMALL, (LPARAM)largeIcon); SendMessage(Context->DialogHandle, WM_SETICON, ICON_BIG, (LPARAM)smallIcon); }
/* * @implemented */ DWORD WINAPI TlsAlloc(VOID) { ULONG Index; RtlAcquirePebLock(); /* Try to get regular TEB slot. */ Index = RtlFindClearBitsAndSet(NtCurrentPeb()->TlsBitmap, 1, 0); if (Index == ~0U) { /* If it fails, try to find expansion TEB slot. */ Index = RtlFindClearBitsAndSet(NtCurrentPeb()->TlsExpansionBitmap, 1, 0); if (Index != ~0U) { if (NtCurrentTeb()->TlsExpansionSlots == NULL) { NtCurrentTeb()->TlsExpansionSlots = HeapAlloc(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, TLS_EXPANSION_SLOTS * sizeof(PVOID)); } if (NtCurrentTeb()->TlsExpansionSlots == NULL) { RtlClearBits(NtCurrentPeb()->TlsExpansionBitmap, Index, 1); Index = ~0; SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { /* Clear the value. */ NtCurrentTeb()->TlsExpansionSlots[Index] = 0; Index += TLS_MINIMUM_AVAILABLE; } } else { SetLastError(ERROR_NO_MORE_ITEMS); } } else { /* Clear the value. */ NtCurrentTeb()->TlsSlots[Index] = 0; } RtlReleasePebLock(); return Index; }
/* * @implemented */ BOOL WINAPI TlsFree(DWORD Index) { BOOL BitSet; if (Index >= TLS_EXPANSION_SLOTS + TLS_MINIMUM_AVAILABLE) { SetLastErrorByStatus(STATUS_INVALID_PARAMETER); return FALSE; } RtlAcquirePebLock(); if (Index >= TLS_MINIMUM_AVAILABLE) { BitSet = RtlAreBitsSet(NtCurrentPeb()->TlsExpansionBitmap, Index - TLS_MINIMUM_AVAILABLE, 1); if (BitSet) RtlClearBits(NtCurrentPeb()->TlsExpansionBitmap, Index - TLS_MINIMUM_AVAILABLE, 1); } else { BitSet = RtlAreBitsSet(NtCurrentPeb()->TlsBitmap, Index, 1); if (BitSet) RtlClearBits(NtCurrentPeb()->TlsBitmap, Index, 1); } if (BitSet) { /* Clear the TLS cells (slots) in all threads of the current process. */ NtSetInformationThread(NtCurrentThread(), ThreadZeroTlsCell, &Index, sizeof(DWORD)); } else { SetLastError(ERROR_INVALID_PARAMETER); } RtlReleasePebLock(); return BitSet; }
PVOID WINAPI MemAlloc(IN HANDLE Heap, IN PVOID Ptr, IN ULONG Size) { PVOID pBuf = NULL; if(Size == 0 && Ptr == NULL) { return NULL; } if(Heap == NULL) { Heap = NtCurrentPeb()->ProcessHeap; } if(Size > 0) { if(Ptr == NULL) /* malloc */ pBuf = RtlAllocateHeap(Heap, 0, Size); else /* realloc */ pBuf = RtlReAllocateHeap(Heap, 0, Ptr, Size); } else /* free */ RtlFreeHeap(Heap, 0, Ptr); return pBuf; }
BOOL WINAPI BaseCheckForVDM(IN HANDLE ProcessHandle, OUT LPDWORD ExitCode) { #if 0 // Unimplemented in BASESRV NTSTATUS Status; EVENT_BASIC_INFORMATION EventBasicInfo; BASE_API_MESSAGE ApiMessage; PBASE_GET_VDM_EXIT_CODE GetVdmExitCode = &ApiMessage.Data.GetVdmExitCode; /* It's VDM if the process is actually a wait handle (an event) */ Status = NtQueryEvent(ProcessHandle, EventBasicInformation, &EventBasicInfo, sizeof(EventBasicInfo), NULL); if (!NT_SUCCESS(Status)) return FALSE; /* Setup the input parameters */ GetVdmExitCode->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle; GetVdmExitCode->hParent = ProcessHandle; /* Call CSRSS */ Status = CsrClientCallServer((PCSR_API_MESSAGE)&ApiMessage, NULL, CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX, BasepGetVDMExitCode), sizeof(BASE_GET_VDM_EXIT_CODE)); if (!NT_SUCCESS(Status)) return FALSE; /* Get the exit code from the reply */ *ExitCode = GetVdmExitCode->ExitCode; #endif return TRUE; }
static VOID PhInitializeSecurity( _In_ ULONG Flags ) { HANDLE tokenHandle; PhElevated = TRUE; PhElevationType = TokenElevationTypeDefault; PhCurrentSessionId = NtCurrentPeb()->SessionId; if (Flags & PHLIB_INIT_TOKEN_INFO) { if (NT_SUCCESS(PhOpenProcessToken( &tokenHandle, TOKEN_QUERY, NtCurrentProcess() ))) { if (WINDOWS_HAS_UAC) { PhGetTokenIsElevated(tokenHandle, &PhElevated); PhGetTokenElevationType(tokenHandle, &PhElevationType); } PhCurrentTokenQueryHandle = tokenHandle; } } }
/* * ucmLoadCallback * * Purpose: * * Image load notify callback, when kernel32 available - acquire import and run target application. * */ VOID NTAPI ucmLoadCallback( PWSTR DllName, PVOID DllBase, SIZE_T DllSize, PVOID Reserved ) { BOOL bReadSuccess, bIsLocalSystem = FALSE; PWSTR lpParameter = NULL; ULONG cbParameter = 0L; UNREFERENCED_PARAMETER(DllSize); UNREFERENCED_PARAMETER(Reserved); if (DllName == NULL) { return; } if (_strcmpi(DllName, L"kernel32.dll") == 0) { g_pvKernel32 = DllBase; } if (_strcmpi(DllName, L"user32.dll") == 0) { if (g_pvKernel32) { pCreateProcessW = ucmLdrGetProcAddress( (PCHAR)g_pvKernel32, "CreateProcessW"); if (pCreateProcessW != NULL) { ucmIsLocalSystem(&bIsLocalSystem); bReadSuccess = ucmReadParameters( &lpParameter, &cbParameter, NULL, NULL, bIsLocalSystem); ucmLaunchPayloadEx( pCreateProcessW, lpParameter, cbParameter); if ((bReadSuccess) && (lpParameter != NULL)) { RtlFreeHeap( NtCurrentPeb()->ProcessHeap, 0, lpParameter); } NtTerminateProcess(NtCurrentProcess(), STATUS_SUCCESS); } } } }
/* * @implemented */ ULONG NTAPI RtlGetNtGlobalFlags(VOID) { PPEB pPeb = NtCurrentPeb(); return pPeb->NtGlobalFlag; }
VOID ShowLatestVersionDialog( _In_ PPH_UPDATER_CONTEXT Context ) { TASKDIALOGCONFIG config; LARGE_INTEGER time; SYSTEMTIME systemTime = { 0 }; PIMAGE_DOS_HEADER imageDosHeader; PIMAGE_NT_HEADERS imageNtHeader; memset(&config, 0, sizeof(TASKDIALOGCONFIG)); config.cbSize = sizeof(TASKDIALOGCONFIG); config.dwFlags = TDF_USE_HICON_MAIN | TDF_ALLOW_DIALOG_CANCELLATION | TDF_CAN_BE_MINIMIZED | TDF_ENABLE_HYPERLINKS | TDF_EXPAND_FOOTER_AREA; config.dwCommonButtons = TDCBF_CLOSE_BUTTON; config.hMainIcon = Context->IconLargeHandle; config.cxWidth = 200; config.pfCallback = FinalTaskDialogCallbackProc; config.lpCallbackData = (LONG_PTR)Context; // HACK imageDosHeader = (PIMAGE_DOS_HEADER)NtCurrentPeb()->ImageBaseAddress; imageNtHeader = (PIMAGE_NT_HEADERS)PTR_ADD_OFFSET(imageDosHeader, imageDosHeader->e_lfanew); RtlSecondsSince1970ToTime(imageNtHeader->FileHeader.TimeDateStamp, &time); PhLargeIntegerToLocalSystemTime(&systemTime, &time); config.pszWindowTitle = L"Process Hacker - Updater"; config.pszMainInstruction = L"You're running the latest version."; config.pszContent = PhaFormatString( L"Version: v%s\r\nCompiled: %s\r\n\r\n<A HREF=\"changelog.txt\">View Changelog</A>", PhGetStringOrEmpty(Context->CurrentVersionString), PhaFormatDateTime(&systemTime)->Buffer )->Buffer; TaskDialogNavigatePage(Context->DialogHandle, &config); }
PVOID WINAPI RtlpAddVectoredHandler(ULONG FirstHandler, PVECTORED_EXCEPTION_HANDLER VectorHandler, ULONG Type) { PVOID Peb = NtCurrentPeb(); PVEH_NODE VehNode = NULL; VehNode = (PVEH_NODE)fnRtlAllocateHeap(*(PVOID*)((PBYTE)Peb + 0x18), // Peb.ProcessHeap 0, // No flags sizeof(VEH_NODE)); // 0x10 bytes if (VehNode == NULL) { return NULL; } VehNode->RefCount = 1; VehNode->Handler = (PVECTORED_EXCEPTION_HANDLER)fnRtlEncodePointer(VectorHandler); fnRtlAcquireSRWLockExclusive(&LdrpVectorHandlerList[Type].Lock); if (IsListEmpty(&LdrpVectorHandlerList[Type].Head)) { InterlockedBitTestAndSet((LONG*)((PBYTE)Peb+0x28), // Peb.EnvironmentUpdateCount, seems not a count... Type + 2); } if (FirstHandler == 0) { InsertHeadList(&LdrpVectorHandlerList[Type].Head, &VehNode->Entry); } else { InsertTailList(&LdrpVectorHandlerList[Type].Head, &VehNode->Entry); } fnRtlReleaseSRWLockExclusive(&LdrpVectorHandlerList[Type].Lock); return VehNode; }
/* * @implemented */ VOID WINAPI GetStartupInfoW(LPSTARTUPINFOW lpStartupInfo) { PRTL_USER_PROCESS_PARAMETERS Params; if (lpStartupInfo == NULL) { SetLastError(ERROR_INVALID_PARAMETER); return; } Params = NtCurrentPeb()->ProcessParameters; lpStartupInfo->cb = sizeof(STARTUPINFOW); lpStartupInfo->lpDesktop = Params->DesktopInfo.Buffer; lpStartupInfo->lpTitle = Params->WindowTitle.Buffer; lpStartupInfo->dwX = Params->StartingX; lpStartupInfo->dwY = Params->StartingY; lpStartupInfo->dwXSize = Params->CountX; lpStartupInfo->dwYSize = Params->CountY; lpStartupInfo->dwXCountChars = Params->CountCharsX; lpStartupInfo->dwYCountChars = Params->CountCharsY; lpStartupInfo->dwFillAttribute = Params->FillAttribute; lpStartupInfo->dwFlags = Params->WindowFlags; lpStartupInfo->wShowWindow = (WORD)Params->ShowWindowFlags; lpStartupInfo->cbReserved2 = Params->RuntimeData.Length; lpStartupInfo->lpReserved2 = (LPBYTE)Params->RuntimeData.Buffer; lpStartupInfo->hStdInput = Params->StandardInput; lpStartupInfo->hStdOutput = Params->StandardOutput; lpStartupInfo->hStdError = Params->StandardError; }
BOOLEAN NTAPI RtlpCheckForActiveDebugger(VOID) { /* Return the flag in the PEB */ return NtCurrentPeb()->BeingDebugged; }
static DWORD IntGetConsoleCommandHistory(LPVOID lpHistory, DWORD cbHistory, LPCVOID lpExeName, BOOLEAN bUnicode) { CONSOLE_API_MESSAGE ApiMessage; PCONSOLE_GETCOMMANDHISTORY GetCommandHistoryRequest = &ApiMessage.Data.GetCommandHistoryRequest; PCSR_CAPTURE_BUFFER CaptureBuffer; USHORT NumChars = (USHORT)(lpExeName ? (bUnicode ? wcslen(lpExeName) : strlen(lpExeName)) : 0); if (lpExeName == NULL || NumChars == 0) { SetLastError(ERROR_INVALID_PARAMETER); return 0; } GetCommandHistoryRequest->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle; GetCommandHistoryRequest->HistoryLength = cbHistory; GetCommandHistoryRequest->ExeLength = NumChars * (bUnicode ? sizeof(WCHAR) : sizeof(CHAR)); GetCommandHistoryRequest->Unicode = GetCommandHistoryRequest->Unicode2 = bUnicode; // CaptureBuffer = CsrAllocateCaptureBuffer(2, IntStringSize(lpExeName, bUnicode) + // HistoryLength); CaptureBuffer = CsrAllocateCaptureBuffer(2, GetCommandHistoryRequest->ExeLength + GetCommandHistoryRequest->HistoryLength); if (!CaptureBuffer) { DPRINT1("CsrAllocateCaptureBuffer failed!\n"); SetLastError(ERROR_NOT_ENOUGH_MEMORY); return 0; } CsrCaptureMessageBuffer(CaptureBuffer, (PVOID)lpExeName, GetCommandHistoryRequest->ExeLength, (PVOID)&GetCommandHistoryRequest->ExeName); CsrAllocateMessagePointer(CaptureBuffer, GetCommandHistoryRequest->HistoryLength, (PVOID*)&GetCommandHistoryRequest->History); CsrClientCallServer((PCSR_API_MESSAGE)&ApiMessage, CaptureBuffer, CSR_CREATE_API_NUMBER(CONSRV_SERVERDLL_INDEX, ConsolepGetCommandHistory), sizeof(*GetCommandHistoryRequest)); if (!NT_SUCCESS(ApiMessage.Status)) { CsrFreeCaptureBuffer(CaptureBuffer); BaseSetLastNTError(ApiMessage.Status); return 0; } RtlCopyMemory(lpHistory, GetCommandHistoryRequest->History, GetCommandHistoryRequest->HistoryLength); CsrFreeCaptureBuffer(CaptureBuffer); return GetCommandHistoryRequest->HistoryLength; }
BOOL Init(VOID) { USERCONNECT UserCon; /* Set PEB data */ NtCurrentPeb()->KernelCallbackTable = apfnDispatch; NtCurrentPeb()->PostProcessInitRoutine = NULL; NtUserProcessConnect( NtCurrentProcess(), &UserCon, sizeof(USERCONNECT)); g_ppi = GetWin32ClientInfo()->ppi; // Snapshot PI, used as pointer only! g_ulSharedDelta = UserCon.siClient.ulSharedDelta; gpsi = SharedPtrToUser(UserCon.siClient.psi); gHandleTable = SharedPtrToUser(UserCon.siClient.aheList); gHandleEntries = SharedPtrToUser(gHandleTable->handles); RtlInitializeCriticalSection(&gcsUserApiHook); gfServerProcess = FALSE; // FIXME HAX! Used in CsrClientConnectToServer(,,,,&gfServerProcess); //CsrClientConnectToServer(L"\\Windows", 0, NULL, 0, &gfServerProcess); //ERR("1 SI 0x%x : HT 0x%x : D 0x%x\n", UserCon.siClient.psi, UserCon.siClient.aheList, g_ulSharedDelta); /* Allocate an index for user32 thread local data. */ User32TlsIndex = TlsAlloc(); if (User32TlsIndex != TLS_OUT_OF_INDEXES) { if (MessageInit()) { if (MenuInit()) { InitializeCriticalSection(&U32AccelCacheLock); GdiDllInitialize(NULL, DLL_PROCESS_ATTACH, NULL); LoadAppInitDlls(); return TRUE; } MessageCleanup(); } TlsFree(User32TlsIndex); } return FALSE; }
/* * @implemented */ LPWSTR WINAPI GetEnvironmentStringsW ( VOID ) { return (LPWSTR)(NtCurrentPeb ()->ProcessParameters->Environment); }
int _cdecl _main(int argc, char *argv[], char *envp[], int DebugFlag) { KPRIORITY BasePriority = (8 + 1) + 4; NTSTATUS Status; //ULONG Response; // see the #if 0 UNREFERENCED_PARAMETER(envp); UNREFERENCED_PARAMETER(DebugFlag); /* Set the Priority */ NtSetInformationProcess(NtCurrentProcess(), ProcessBasePriority, &BasePriority, sizeof(KPRIORITY)); /* Give us IOPL so that we can access the VGA registers */ Status = NtSetInformationProcess(NtCurrentProcess(), ProcessUserModeIOPL, NULL, 0); if (!NT_SUCCESS(Status)) { /* Raise a hard error */ DPRINT1("CSRSS: Could not raise IOPL, Status: 0x%08lx\n", Status); #if 0 Status = NtRaiseHardError(STATUS_IO_PRIVILEGE_FAILED, 0, 0, NULL, OptionOk, &Response); #endif } /* Initialize CSR through CSRSRV */ Status = CsrServerInitialization(argc, argv); if (!NT_SUCCESS(Status)) { /* Kill us */ DPRINT1("CSRSS: Unable to initialize server, Status: 0x%08lx\n", Status); NtTerminateProcess(NtCurrentProcess(), Status); } /* Disable errors */ CsrpSetDefaultProcessHardErrorMode(); /* If this is Session 0, make sure killing us bugchecks the system */ if (NtCurrentPeb()->SessionId == 0) RtlSetProcessIsCritical(TRUE, NULL, FALSE); /* Kill this thread. CSRSRV keeps us going */ NtTerminateThread(NtCurrentThread(), Status); return 0; }
/* * @implemented */ VOID NTAPI DbgUiRemoteBreakin(VOID) { /* Make sure a debugger is enabled; if so, breakpoint */ if (NtCurrentPeb()->BeingDebugged) DbgBreakPoint(); /* Exit the thread */ RtlExitUserThread(STATUS_SUCCESS); }
/* * @implemented */ VOID NTAPI RtlSetCurrentEnvironment(PWSTR NewEnvironment, PWSTR *OldEnvironment) { PVOID EnvPtr; DPRINT("NewEnvironment 0x%p OldEnvironment 0x%p\n", NewEnvironment, OldEnvironment); RtlAcquirePebLock(); EnvPtr = NtCurrentPeb()->ProcessParameters->Environment; NtCurrentPeb()->ProcessParameters->Environment = NewEnvironment; if (OldEnvironment != NULL) *OldEnvironment = EnvPtr; RtlReleasePebLock(); }
static DWORD get_win_ver() { # ifdef COMPILE_AS_ROSTEST PPEB Peb = NtCurrentPeb(); const DWORD dwWinVer = (DWORD)(Peb->OSMinorVersion << 8) | Peb->OSMajorVersion; # else const DWORD dwWinVer = GetVersion(); # endif return dwWinVer; }
static BOOL IntSetConsoleNumberOfCommands(DWORD dwNumCommands, LPCVOID lpExeName, BOOLEAN bUnicode) { CONSOLE_API_MESSAGE ApiMessage; PCONSOLE_SETHISTORYNUMBERCOMMANDS SetHistoryNumberCommandsRequest = &ApiMessage.Data.SetHistoryNumberCommandsRequest; PCSR_CAPTURE_BUFFER CaptureBuffer; USHORT NumChars = (USHORT)(lpExeName ? (bUnicode ? wcslen(lpExeName) : strlen(lpExeName)) : 0); if (lpExeName == NULL || NumChars == 0) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } SetHistoryNumberCommandsRequest->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle; SetHistoryNumberCommandsRequest->NumCommands = dwNumCommands; SetHistoryNumberCommandsRequest->ExeLength = NumChars * (bUnicode ? sizeof(WCHAR) : sizeof(CHAR)); SetHistoryNumberCommandsRequest->Unicode = SetHistoryNumberCommandsRequest->Unicode2 = bUnicode; // CaptureBuffer = CsrAllocateCaptureBuffer(1, IntStringSize(lpExeName, bUnicode)); CaptureBuffer = CsrAllocateCaptureBuffer(1, SetHistoryNumberCommandsRequest->ExeLength); if (!CaptureBuffer) { DPRINT1("CsrAllocateCaptureBuffer failed!\n"); SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } // IntCaptureMessageString(CaptureBuffer, lpExeName, bUnicode, // &SetHistoryNumberCommandsRequest->ExeName); CsrCaptureMessageBuffer(CaptureBuffer, (PVOID)lpExeName, SetHistoryNumberCommandsRequest->ExeLength, (PVOID)&SetHistoryNumberCommandsRequest->ExeName); CsrClientCallServer((PCSR_API_MESSAGE)&ApiMessage, CaptureBuffer, CSR_CREATE_API_NUMBER(CONSRV_SERVERDLL_INDEX, ConsolepSetNumberOfCommands), sizeof(*SetHistoryNumberCommandsRequest)); CsrFreeCaptureBuffer(CaptureBuffer); if (!NT_SUCCESS(ApiMessage.Status)) { BaseSetLastNTError(ApiMessage.Status); return FALSE; } return TRUE; }
/* * @implemented */ DWORD WINAPI GetVersion(VOID) { PPEB Peb = NtCurrentPeb(); return (DWORD)( ((Peb->OSPlatformId ^ 2) << 30) | (Peb->OSBuildNumber << 16) | (Peb->OSMinorVersion << 8 ) | Peb->OSMajorVersion ); }
DECL_EXTERN_API(HANDLE, ObjectTranslateHandle, CONST IN HANDLE Handle) { PRTL_USER_PROCESS_PARAMETERS Ppb = NtCurrentPeb()->ProcessParameters; switch (HandleToUlong(Handle)) { case STD_INPUT_HANDLE: return Ppb->StandardInput; case STD_OUTPUT_HANDLE: return Ppb->StandardOutput; case STD_ERROR_HANDLE: return Ppb->StandardError; } return Handle; }
DWORD WINAPI SignalObjectAndWait( HANDLE hObjectToSignal, HANDLE hObjectToWaitOn, DWORD dwMilliseconds, BOOL bAlertable ) { NTSTATUS Status; LARGE_INTEGER TimeOut; PLARGE_INTEGER pTimeOut; PPEB Peb; Peb = NtCurrentPeb(); switch( (DWORD)hObjectToWaitOn ) { case STD_INPUT_HANDLE: hObjectToWaitOn = Peb->ProcessParameters->StandardInput; break; case STD_OUTPUT_HANDLE: hObjectToWaitOn = Peb->ProcessParameters->StandardOutput; break; case STD_ERROR_HANDLE: hObjectToWaitOn = Peb->ProcessParameters->StandardError; break; } if (CONSOLE_HANDLE(hObjectToWaitOn) && VerifyConsoleIoHandle(hObjectToWaitOn)) { hObjectToWaitOn = GetConsoleInputWaitHandle(); } pTimeOut = BaseFormatTimeOut(&TimeOut,dwMilliseconds); rewait: Status = NtSignalAndWaitForSingleObject( hObjectToSignal, hObjectToWaitOn, (BOOLEAN)bAlertable, pTimeOut ); if ( !NT_SUCCESS(Status) ) { BaseSetLastNTError(Status); Status = (NTSTATUS)0xffffffff; } else { if ( bAlertable && Status == STATUS_ALERTED ) { goto rewait; } } return (DWORD)Status; }
PVOID WINAPI BasepMapModuleHandle(HMODULE hModule, BOOLEAN AsDataFile) { /* If no handle is provided - use current image base address */ if (!hModule) return NtCurrentPeb()->ImageBaseAddress; /* Check if it's a normal or a datafile one */ if (LDR_IS_DATAFILE(hModule) && !AsDataFile) return NULL; /* It'a a normal DLL, just return its handle */ return hModule; }
///This is just for demo reasons: It unmaps everything executable within the processes VA space and then exits. void selfUnmap(void) { PVOID pModuleBases[0x20]; ULONG i = 0; ULONG ntUnmapViewOfFileNum = ((PNT_SYSCALL_STUB)NtUnmapViewOfSection)->syscallNumber; PVOID pSelfBase = NtCurrentPeb()->ImageBaseAddress; PLDR_DATA_TABLE_ENTRY pFirstEntry = (PLDR_DATA_TABLE_ENTRY)(NtCurrentPeb()->Ldr->InLoadOrderModuleList.Flink); PLDR_DATA_TABLE_ENTRY pCurrEntry = pFirstEntry; for (; i < sizeof(pModuleBases) / sizeof(PVOID); i++) { if (pSelfBase != pCurrEntry->DllBase) pModuleBases[i] = pCurrEntry->DllBase; else i--; pCurrEntry = (PLDR_DATA_TABLE_ENTRY)pCurrEntry->InLoadOrderLinks.Flink; if (pFirstEntry == pCurrEntry) break; } for (ULONG j = 0; j < i; j++) if (syscallStub(ntUnmapViewOfFileNum, INVALID_HANDLE_VALUE, pModuleBases[j], 0x2978634294367583, 0xaecfaefceaaebaef)) break; }
HANDLE FASTCALL TranslateStdHandle(HANDLE hHandle) { PRTL_USER_PROCESS_PARAMETERS Ppb = NtCurrentPeb()->ProcessParameters; switch ((ULONG)hHandle) { case STD_INPUT_HANDLE: return Ppb->StandardInput; case STD_OUTPUT_HANDLE: return Ppb->StandardOutput; case STD_ERROR_HANDLE: return Ppb->StandardError; } return hHandle; }
NTSTATUS NTAPI UserCreateWinstaDirectory(VOID) { PPEB Peb; NTSTATUS Status; WCHAR wstrWindowStationsDir[MAX_PATH]; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE hWinstaDir; /* Create the WindowStations directory and cache its path for later use */ Peb = NtCurrentPeb(); if(Peb->SessionId == 0) { if (!RtlCreateUnicodeString(&gustrWindowStationsDir, WINSTA_OBJ_DIR)) { return STATUS_INSUFFICIENT_RESOURCES; } } else { swprintf(wstrWindowStationsDir, L"%ws\\%lu%ws", SESSION_DIR, Peb->SessionId, WINSTA_OBJ_DIR); if (!RtlCreateUnicodeString(&gustrWindowStationsDir, wstrWindowStationsDir)) { return STATUS_INSUFFICIENT_RESOURCES; } } InitializeObjectAttributes(&ObjectAttributes, &gustrWindowStationsDir, 0, NULL, NULL); Status = ZwCreateDirectoryObject(&hWinstaDir, 0, &ObjectAttributes); if (!NT_SUCCESS(Status)) { ERR("Could not create %wZ directory (Status 0x%X)\n", &gustrWindowStationsDir, Status); return Status; } TRACE("Created directory %wZ for session %lu\n", &gustrWindowStationsDir, Peb->SessionId); return Status; }
/* * SfuLoadPeerList * * Purpose: * * Load peer list from filename given in win32 format. * */ NTSTATUS SfuLoadPeerList( _In_ OBJECT_ATTRIBUTES *ObjectAttributes, _In_ ZA_PEERINFO **PeerList, _In_ PULONG NumberOfPeers ) { BOOL cond = FALSE; HANDLE hFile = NULL; PVOID pData = NULL; NTSTATUS status = STATUS_UNSUCCESSFUL; IO_STATUS_BLOCK iost; FILE_STANDARD_INFORMATION fsi; if ((NumberOfPeers == NULL) || (PeerList == NULL)) return status; do { status = NtOpenFile(&hFile, FILE_READ_ACCESS | SYNCHRONIZE, ObjectAttributes, &iost, FILE_SHARE_READ, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT); if (!NT_SUCCESS(status)) break; RtlSecureZeroMemory(&fsi, sizeof(fsi)); status = NtQueryInformationFile(hFile, &iost, (PVOID)&fsi, sizeof(fsi), FileStandardInformation); if (!NT_SUCCESS(status)) break; pData = RtlAllocateHeap(NtCurrentPeb()->ProcessHeap, HEAP_ZERO_MEMORY, (SIZE_T)fsi.EndOfFile.LowPart); if (pData == NULL) { status = STATUS_MEMORY_NOT_ALLOCATED; break; } if ((fsi.EndOfFile.LowPart % sizeof(ZA_PEERINFO)) != 0) {// incomplete/damaged file status = STATUS_BAD_DATA; break; } status = NtReadFile(hFile, NULL, NULL, NULL, &iost, pData, fsi.EndOfFile.LowPart, NULL, NULL); if (NT_SUCCESS(status)) { *NumberOfPeers = (ULONG)(iost.Information / sizeof(ZA_PEERINFO)); *PeerList = pData; } else { RtlFreeHeap(NtCurrentPeb()->ProcessHeap, 0, pData); *NumberOfPeers = 0; *PeerList = NULL; } } while (cond); if (hFile) NtClose(hFile); return status; }