Process environment block windows

From Wikipedia, the free encyclopedia

In computing the Process Environment Block (abbreviated PEB) is a data structure in the Windows NT operating system family. It is an opaque data structure that is used by the operating system internally, most of whose fields are not intended for use by anything other than the operating system.[1] Microsoft notes, in its MSDN Library documentation — which documents only a few of the fields — that the structure «may be altered in future versions of Windows».[2] The PEB contains data structures that apply across a whole process, including global context, startup parameters, data structures for the program image loader, the program image base address, and synchronization objects used to provide mutual exclusion for process-wide data structures.[1]

The PEB is closely associated with the kernel mode EPROCESS data structure, as well as with per-process data structures managed within the address space of the Client-Server Runtime Sub-System process. However, (like the CSRSS data structures) the PEB is not a kernel mode data structure itself. It resides in the application mode address space of the process that it relates to. This is because it is designed to be used by the application-mode code in the operating system libraries, such as NTDLL, that executes outside of kernel mode, such as the code for the program image loader and the heap manager.[3]

In WinDbg, the command that dumps the contents of a PEB is the !peb command, which is passed the address of the PEB within a process’ application address space. That information, in turn, is obtained by the !process command, which displays the information from the EPROCESS data structure, one of whose fields is the address of the PEB.[3]

Fields of the PEB that are documented by Microsoft[2]

Field meaning notes
BeingDebugged Whether the process is being debugged Microsoft recommends not using this field but using the official Win32 CheckRemoteDebuggerPresent() library function instead.[2]
Ldr A pointer to a PEB_LDR_DATA structure providing information about loaded modules Contains the base address of kernel32 and ntdll.
ProcessParameters A pointer to a RTL_USER_PROCESS_PARAMETERS structure providing information about process startup parameters The RTL_USER_PROCESS_PARAMETERS structure is also mostly opaque and not guaranteed to be consistent across multiple versions of Windows.[4]
PostProcessInitRoutine A pointer to a callback function called after DLL initialization but before the main executable code is invoked This callback function is used on Windows 2000, but is not guaranteed to be used on later versions of Windows NT.[2]
SessionId The session ID of the Terminal Services session that the process is part of The NtCreateUserProcess() system call initializes this by calling the kernel’s internal MmGetSessionId() function.[3]

The contents of the PEB are initialized by the NtCreateUserProcess() system call, the Native API function that implements part of, and underpins, the Win32 CreateProcess(), CreateProcessAsUser(), CreateProcessWithTokenW(), and CreateProcessWithLogonW() library functions that are in the kernel32.dll and advapi32.dll libraries as well as underpinning the fork() function in the Windows NT POSIX library, posix.dll.[3]

For Windows NT POSIX processes, the contents of a new process’ PEB are initialized by NtCreateUserProcess() as simply a direct copy of the parent process’ PEB, in line with how the fork() function operates. For Win32 processes, the initial contents of a new process’ PEB are mainly taken from global variables maintained within the kernel. However, several fields may instead be taken from information provided within the process’ image file, in particular information provided in the IMAGE_OPTIONAL_HEADER32 data structure within the PE file format (PE+ or PE32+ in 64 bit executable images).[3]

Fields from a PEB that are initialized from kernel global variables[3]

Field is initialized from overridable by PE information?
NumberOfProcessors KeNumberOfProcessors No
NtGlobalFlag NtGlobalFlag No
CriticalSectionTimeout MmCriticalSectionTimeout No
HeapSegmentReserve MmHeapSegmentReserve No
HeapSegmentCommit MmHeapSegmentCommit No
HeapDeCommitTotalFreeThreshold MmHeapDeCommitTotalFreeThreshold No
HeapDeCommitFreeBlockThreshold MmHeapDeCommitFreeBlockThreshold No
MinimumStackCommit MmMinimumStackCommitInBytes No
ImageProcessAffinityMask KeActiveProcessors ImageLoadConfigDirectory.ProcessAffinityMask
OSMajorVersion NtMajorVersion OptionalHeader.Win32VersionValue & 0xFF
OSMinorVersion NtMinorVersion (OptionalHeader.Win32VersionValue >> 8) & 0xFF
OSBuildNumber NtBuildNumber & 0x3FFF combined with CmNtCSDVersion (OptionalHeader.Win32VersionValue >> 16) & 0x3FFF combined with ImageLoadConfigDirectory.CmNtCSDVersion
OSPlatformId VER_PLATFORM_WIN32_NT (OptionalHeader.Win32VersionValue >> 30) ^ 0x2

The WineHQ project provides a fuller PEB definition in its version of winternl.h.[5] Later versions of Windows have adjusted the number and purpose of some fields.[6]

  1. ^ a b Rajeev Nagar (1997). Windows NT file system internals: a developer’s guide. O’Reilly Series. O’Reilly. pp. 129. ISBN 9781565922495.
  2. ^ a b c d «Process and Thread structures: PEB Structure». MSDN Library. Microsoft. 2010-07-15. Archived from the original on 2012-10-22. Retrieved 2010-07-15.
  3. ^ a b c d e f Mark E. Russinovich, David A. Solomon, and Alex Ionescu (2009). Windows internals. Microsoft Press Series (5th ed.). Microsoft Press. pp. 335–336, 341–342, 348, 357–358. ISBN 9780735625303.{{cite book}}: CS1 maint: multiple names: authors list (link)
  4. ^ «Process and Thread structures: RTL_USER_PROCESS_PARAMETERS Structure». MSDN Library. Microsoft. 2010-07-15. Retrieved 2010-07-15.
  5. ^ «wine winternl.h: typedef struct _PEB». GitHub. wine-mirror. 29 October 2019.
  6. ^ Chappel, Geoff. «PEB». Retrieved 30 October 2019.
  • PEB definitions for various Windows versions

PEB — структура процесса в windows, заполняется загрузчиком на этапе создания процесса, которая содержит информацию о окружении, загруженных модулях (LDR_DATA), базовой информации по текущему модулю и другие критичные данные необходимые для функционирования процесса. Многие системные api windows, получающие информацию о модулях (библиотеках) в процессе, вызывают ReadProcessMemory для считывания информации из PEB нужного процесса.

TEB — структура которая используется для хранения информации о потоках в текущем процессе, каждый поток имеет свой TEB. Wow64 процессы в Windows имеют два Process Environment Blocks и два Thread Environment Blocks. TEB создается функцией MmCreateTeb, PEB создается функцией MmCreatePeb, если интересен процесс создания, то можно посмотреть исходники ReactOS, или взять WinDBG и исследовать самостоятельно. Перед собой была поставлена цель в изменении PEB чужого процесса.

TEB имеет следующий вид:

typedef struct _CLIENT_ID {
    DWORD UniqueProcess;
    DWORD UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _THREAD_BASIC_INFORMATION {
typedef PVOID KPRIORITY;
NTSTATUS ExitStatus; PVOID TebBaseAddress; CLIENT_ID ClientId; KAFFINITY AffinityMask; KPRIORITY Priority; KPRIORITY BasePriority;

} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
[TEB+0] Указатель на первый SEH на стэке.
[TEB+4] Указатель на конец области памяти, выделенных на стеке.
[TEB+8] Указатель на начало области памяти выделенных на стеке, для контроля исключений переполнения стека.
[TEB+18] Адрес текущей TEB.
[TEB+30] Адрес PEB.

Для получения TEB конкретного потока можно воспользоваться NtQueryInformationThread.

#include <Windows.h>
#include <stdio.h>
#pragma comment(lib,"ntdll.lib")
typedef struct _CLIENT_ID {
    DWORD UniqueProcess;
    DWORD UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _THREAD_BASIC_INFORMATION {
typedef PVOID KPRIORITY;
NTSTATUS ExitStatus; PVOID TebBaseAddress; CLIENT_ID ClientId; KAFFINITY AffinityMask; KPRIORITY Priority; KPRIORITY BasePriority;

} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
typedef   enum   _THREADINFOCLASS
{
    ThreadBasicInformation,
    ThreadTimes,
    ThreadPriority,
    ThreadBasePriority,
    ThreadAffinityMask,
    ThreadImpersonationToken,
    ThreadDescriptorTableEntry,
    ThreadEnableAlignmentFaultFixup,
    ThreadEventPair_Reusable,
    ThreadQuerySetWin32StartAddress,
    ThreadZeroTlsCell,
    ThreadPerformanceCount,
    ThreadAmILastThread,
    ThreadIdealProcessor,
    ThreadPriorityBoost,
    ThreadSetTlsArrayAddress,
    ThreadIsIoPending,
    ThreadHideFromDebugger,
    ThreadBreakOnTermination,
    MaxThreadInfoClass
}   THREADINFOCLASS;
THREADINFOCLASS   ThreadInformationClass;
  extern "C"
  {
  NTSTATUS WINAPI NtQueryInformationThread(
  _In_       HANDLE ThreadHandle,
  _In_       THREADINFOCLASS ThreadInformationClass,
  _Inout_    PVOID ThreadInformation,
  _In_       ULONG ThreadInformationLength,
  _Out_opt_  PULONG ReturnLength
);
}
THREAD_BASIC_INFORMATION ThreadInfo;
DWORD ntstatus = NtQueryInformationThread(
	        GetCurrentThread(), // хэндл на поток
			ThreadBasicInformation,
			&ThreadInfo, //ThreadInfo.TebBaseAddress содержит адрес теба для указанного потока.
			sizeof(THREAD_BASIC_INFORMATION),
			0
			);
// Если нужен teb только своего потока, использовать  __readfsdword(0x18)  в 32 бит или __readgsqword(0x30) в х64.

на MSDN PEB описывается следующим образом для 32 битного процесса:

typedef struct _PEB {
  BYTE                          Reserved1[2];
  BYTE                          BeingDebugged;
  BYTE                          Reserved2[1];
  PVOID                         Reserved3[2];
  PPEB_LDR_DATA                 Ldr;
  PRTL_USER_PROCESS_PARAMETERS  ProcessParameters;
  BYTE                          Reserved4[104];
  PVOID                         Reserved5[52];
  PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine;
  BYTE                          Reserved6[128];
  PVOID                         Reserved7[1];
  ULONG                         SessionId;
} PEB, *PPEB;

и для 64 битного:

typedef struct _PEB {
    BYTE Reserved1[2];
    BYTE BeingDebugged;
    BYTE Reserved2[21];
    PPEB_LDR_DATA LoaderData;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
    BYTE Reserved3[520];
    PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine;
    BYTE Reserved4[136];
    ULONG SessionId;
} PEB;

в моем проекте используется следующая структура для 32 и 64 бит

//автор структуры - http://blog.rewolf.pl/blog/?p=573
#pragma pack(push)
#pragma pack(1)
template <class T>
struct LIST_ENTRY_T
{
	T Flink;
	T Blink;
};
 
template <class T>
struct UNICODE_STRING_T
{
	union
	{
		struct
		{
			WORD Length;
			WORD MaximumLength;
		};
		T dummy;
	};
	T _Buffer;
};
 
template <class T, class NGF, int A>
struct _PEB_T
{
	union
	{
		struct
		{
			BYTE InheritedAddressSpace;
			BYTE ReadImageFileExecOptions;
			BYTE BeingDebugged;
			BYTE _SYSTEM_DEPENDENT_01;
		};
		T dummy01;
	};
	T Mutant;
	T ImageBaseAddress;
	T Ldr;
	T ProcessParameters;
	T SubSystemData;
	T ProcessHeap;
	T FastPebLock;
	T _SYSTEM_DEPENDENT_02;
	T _SYSTEM_DEPENDENT_03;
	T _SYSTEM_DEPENDENT_04;
	union
	{
		T KernelCallbackTable;
		T UserSharedInfoPtr;
	};
	DWORD SystemReserved;
	DWORD _SYSTEM_DEPENDENT_05;
	T _SYSTEM_DEPENDENT_06;
	T TlsExpansionCounter;
	T TlsBitmap;
	DWORD TlsBitmapBits[2];
	T ReadOnlySharedMemoryBase;
	T _SYSTEM_DEPENDENT_07;
	T ReadOnlyStaticServerData;
	T AnsiCodePageData;
	T OemCodePageData;
	T UnicodeCaseTableData;
	DWORD NumberOfProcessors;
	union
	{
		DWORD NtGlobalFlag;
		NGF dummy02;
	};
	LARGE_INTEGER CriticalSectionTimeout;
	T HeapSegmentReserve;
	T HeapSegmentCommit;
	T HeapDeCommitTotalFreeThreshold;
	T HeapDeCommitFreeBlockThreshold;
	DWORD NumberOfHeaps;
	DWORD MaximumNumberOfHeaps;
	T ProcessHeaps;
	T GdiSharedHandleTable;
	T ProcessStarterHelper;
	T GdiDCAttributeList;
	T LoaderLock;
	DWORD OSMajorVersion;
	DWORD OSMinorVersion;
	WORD OSBuildNumber;
	WORD OSCSDVersion;
	DWORD OSPlatformId;
	DWORD ImageSubsystem;
	DWORD ImageSubsystemMajorVersion;
	T ImageSubsystemMinorVersion;
	union
	{
		T ImageProcessAffinityMask;
		T ActiveProcessAffinityMask;
	};
	T GdiHandleBuffer[A];
	T PostProcessInitRoutine;
	T TlsExpansionBitmap;
	DWORD TlsExpansionBitmapBits[32];
	T SessionId;
	ULARGE_INTEGER AppCompatFlags;
	ULARGE_INTEGER AppCompatFlagsUser;
	T pShimData;
	T AppCompatInfo;
	UNICODE_STRING_T<T> CSDVersion;
	T ActivationContextData;
	T ProcessAssemblyStorageMap;
	T SystemDefaultActivationContextData;
	T SystemAssemblyStorageMap;
	T MinimumStackCommit;
};
 
typedef _PEB_T<DWORD, DWORD64, 34> PEB32;
typedef _PEB_T<DWORD64, DWORD, 30> PEB64;

#pragma pack(pop)

PEB можно получить следующим образом:

// воспользуемся  intrinsics функциями, так как в 12 студии инлайн асм для х64 компиляции отсутствует.
// адрес PEB - константа для всех процессов в системе.
#if defined _M_IX86
int offset = 0x30;
DWORD peb __readfsdword(PEB) //mov eax, fs:[0x30]
#elif defined _M_X64
//На 64 битных windows сегментный регистр GS хранит указатель на PEB в GS:[0x60]
int offset = 0x60;
DWORD64 peb =__readgsqword(PEB); //mov rax, gs:[0x60]

Получение базы kernel32 и адрес GetProcAddress:

//х64, проверено, работать будет начиная с xp x64 sp2 до последней win 8.
typedef FARPROC (WINAPI * GetProcAddress_t) (HMODULE, const char *);
struct LDR_MODULE
  {
   LIST_ENTRY e[3];
   HMODULE    base;
   void      *entry;
   UINT       size;
   UNICODE_STRING dllPath;
   UNICODE_STRING dllname;
  };
   int offset = 0x60;
   int ModuleList = 0x18;
   int ModuleListFlink = 0x18;
   int KernelBaseAddr = 0x10;

   INT_PTR peb    =__readgsqword(offset);
   INT_PTR mdllist=*(INT_PTR*)(peb+ ModuleList);
   INT_PTR mlink  =*(INT_PTR*)(mdllist+ ModuleListFlink);
   INT_PTR krnbase=*(INT_PTR*)(mlink+ KernelBaseAddr);

   LDR_MODULE *mdl=(LDR_MODULE*)mlink;
   do 
   {
      mdl=(LDR_MODULE*)mdl->e[0].Flink;

      if(mdl->base!=NULL)
        {
         if(!lstrcmpiW(mdl->dllname.Buffer,L"kernel32.dll")) //сравниваем имя библиотеки в буфере с необходимым
           {
            break;
           }
        }
   } while (mlink!=(INT_PTR)mdl);

	kernel32base = (HMODULE)mdl->base;
	ULONG_PTR base = (ULONG_PTR) kernel32base;
	IMAGE_NT_HEADERS * pe = PIMAGE_NT_HEADERS(base + PIMAGE_DOS_HEADER(base)->e_lfanew);
	IMAGE_EXPORT_DIRECTORY * exportDir = PIMAGE_EXPORT_DIRECTORY(base + pe->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
	DWORD * namePtr = (DWORD *) (base + exportDir->AddressOfNames); // Адрес имен функций.
	WORD * ordPtr = (WORD *) (base + exportDir->AddressOfNameOrdinals); //Адрес имени для функции.
	for(;_stricmp((const char *) (base +*namePtr), "GetProcAddress"); ++namePtr, ++ordPtr);
	DWORD funcRVA = *(DWORD *) (base + exportDir->AddressOfFunctions + *ordPtr * 4);

	auto myGetProcAddress = (GetProcAddress_t) (base + funcRVA); //получили адрес GetProcAddress.

Базовый адрес PEB для определенного процесса получаем так:

typedef enum _PROCESSINFOCLASS {
	ProcessBasicInformation = 0
} PROCESSINFOCLASS;
    status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), &dwLength);
    
    if(status != 0x0)
    {
        printf("NtQueryInformationProcess Error  0x%x\n", status);
		exit(EXIT_FAILURE);
    }
    
    printf("PEB address : 0x%x\n", pbi.PebBaseAddress);

Интересное наблюдение, что если немного «испортить» LDR_DATA, такие api функции как GetModuleHandleEx и EnumProcessModules, QueryFullProcessImageName не будут выдавать нужный результат, так как они вызывают ReadProcessMemory для чтения PEB. Кода много, поэтому манипуляции с PEB (чтение из процесса, изменение и запись) оформлены в виде простого тестового класса, который можно найти тут.

Если эта публикация вас вдохновила и вы хотите поддержать автора — не стесняйтесь нажать на кнопку

The Process Environment Block (PEB) is a wonderful thing, and I’d be lying if I told you that I didn’t love it. It has been present in Windows since the introduction of the Win2k (Windows 2000) and it has been improved through newer versions of Windows ever since. On earlier versions of Windows, it could be abused to do some nasty things like hiding loaded modules present within a process (to prevent them from being found – obviously this is not a beautiful thing though).

What is this magic so-called “Process Environment (PEB)”? The PEB is a structure which holds data about the current process under it’s field values – some fields being structures themselves to hold even more data. Every process has it’s own PEB and the Windows Kernel will also have access to the PEB of every user-mode process so it can keep track of certain data stored within it.

Where does this sorcery come from? The PEB structure comes from the Windows Kernel (although is accessible in user-mode as well). The PEB comes from the Thread Environment Block (TEB) which also happens to be commonly referred to as the Thread Information Block (TIB). The TEB is responsible for holding data about the current thread – every thread has it’s own TEB structure.

Can the Thread Environment Block or the Process Environment Block be abused for malicious purposes? Of course they can! In fact, they have been abused for malicious purposes in the past but Microsoft has made many changes over the recent years to help prevent this. An example would be in the past where rootkits would inject a DLL into another running process, and then access the PEB structure of the current process they had injected into (the PPEB structure is a pointer to the PEB structure) so they could locate the list of loaded modules and remove their own module from the list… Thus hiding their injected module from view when someone enumerates the loaded modules of the affected process. This is known as memory patching because you would be modifying memory by patching the PEB. Microsoft’s mitigation for this behavior was to prevent the manual altering of the list which represents the loaded modules in user-mode – you can still access it for reading the data in user-mode though and you can still patch the memory from kernel-mode.

This article will be split up into two different sections: theory and user-mode practical.

Theoretical


We’re going to take a look at the Thread Environment Block (TEB) structure using WinDbg. Since the TEB structure is available in user-mode, and used by user-mode Windows components such as NTDLL and KERNEL32, we won’t require kernel-debugging to query about the structure.

Bear in mind that you will need to have your symbols correctly setup otherwise you will fail with the next upcoming steps, please see the following URL: https://msdn.microsoft.com/en-us/library/windows/desktop/ee416588(v=vs.85).aspx

We’ll start by opening up WinDbg – I’ll be opening up the 64-bit version.

1

WinDbg default view.

Now we’ll open up notepad.exe. Once it is open, we can attach to notepad.exe in WinDbg by going to File -> Attach to a Process -> notepad.exe. Alternatively, you can use the default hot-key which should be F6.

2

Attaching to a process via WinDbg. 1/2
Attaching to a process via WinDbg. 2/2

After doing this, the WinDbg command window will be displayed. The command window is the work-space we will have to enter commands at our own discretion to get back various desired results. For example, if we wish to manipulate something, or query information about something, we can do this with a command. WinDbg has a whole wide-range of commands available and you can learn more about that here: http://windbg.info/doc/1-common-cmds.html

We’ll be using the dt instruction. “dt” stands for “Display Type” and can be used to display information about a specific data-type, including structures. In our case, it is more than appropriate because it supports structures and we need to find out information about the TEB structure.

We can use the following instruction to query information about the TEB structure.

dt ntdll!_TEB
4

WinDbg command (dt) for the _TEB structure.

We can see already that there are many fields of the structure, so many fields that they all don’t fit on the singular image view. However, if we look towards the very top of the structure, we’ll find the Process Environment Block’s field.

5

Highlighting the ProcessEnvironmentBlock field of the _TEB structure.

We can see that WinDbg is labelling the data-type for the field as “Ptr64 _PEB”. This simply means that the data-type is a pointer to the PEB structure (PPEB). Since we are debugging a 64-bit compiled program (notepad.exe since our OS architecture is 64-bit), the addresses are 8 bytes instead of 4 bytes like on a 32-bit environment, which is why “64” is appended to the “Ptr”.

We can view the fields of the PEB structure with the following WinDbg command.

dt ntdll!_PEB

6

7

WinDbg command (dt) for the _PEB structure.

The WinDbg output is below.

0:007> dt ntdll!_PEB
 +0x000 InheritedAddressSpace : UChar
 +0x001 ReadImageFileExecOptions : UChar
 +0x002 BeingDebugged : UChar
 +0x003 BitField : UChar
 +0x003 ImageUsesLargePages : Pos 0, 1 Bit
 +0x003 IsProtectedProcess : Pos 1, 1 Bit
 +0x003 IsImageDynamicallyRelocated : Pos 2, 1 Bit
 +0x003 SkipPatchingUser32Forwarders : Pos 3, 1 Bit
 +0x003 IsPackagedProcess : Pos 4, 1 Bit
 +0x003 IsAppContainer : Pos 5, 1 Bit
 +0x003 IsProtectedProcessLight : Pos 6, 1 Bit
 +0x003 IsLongPathAwareProcess : Pos 7, 1 Bit
 +0x004 Padding0 : [4] UChar
 +0x008 Mutant : Ptr64 Void
 +0x010 ImageBaseAddress : Ptr64 Void
 +0x018 Ldr : Ptr64 _PEB_LDR_DATA
 +0x020 ProcessParameters : Ptr64 _RTL_USER_PROCESS_PARAMETERS
 +0x028 SubSystemData : Ptr64 Void
 +0x030 ProcessHeap : Ptr64 Void
 +0x038 FastPebLock : Ptr64 _RTL_CRITICAL_SECTION
 +0x040 AtlThunkSListPtr : Ptr64 _SLIST_HEADER
 +0x048 IFEOKey : Ptr64 Void
 +0x050 CrossProcessFlags : Uint4B
 +0x050 ProcessInJob : Pos 0, 1 Bit
 +0x050 ProcessInitializing : Pos 1, 1 Bit
 +0x050 ProcessUsingVEH : Pos 2, 1 Bit
 +0x050 ProcessUsingVCH : Pos 3, 1 Bit
 +0x050 ProcessUsingFTH : Pos 4, 1 Bit
 +0x050 ProcessPreviouslyThrottled : Pos 5, 1 Bit
 +0x050 ProcessCurrentlyThrottled : Pos 6, 1 Bit
 +0x050 ReservedBits0 : Pos 7, 25 Bits
 +0x054 Padding1 : [4] UChar
 +0x058 KernelCallbackTable : Ptr64 Void
 +0x058 UserSharedInfoPtr : Ptr64 Void
 +0x060 SystemReserved : Uint4B
 +0x064 AtlThunkSListPtr32 : Uint4B
 +0x068 ApiSetMap : Ptr64 Void
 +0x070 TlsExpansionCounter : Uint4B
 +0x074 Padding2 : [4] UChar
 +0x078 TlsBitmap : Ptr64 Void
 +0x080 TlsBitmapBits : [2] Uint4B
 +0x088 ReadOnlySharedMemoryBase : Ptr64 Void
 +0x090 SharedData : Ptr64 Void
 +0x098 ReadOnlyStaticServerData : Ptr64 Ptr64 Void
 +0x0a0 AnsiCodePageData : Ptr64 Void
 +0x0a8 OemCodePageData : Ptr64 Void
 +0x0b0 UnicodeCaseTableData : Ptr64 Void
 +0x0b8 NumberOfProcessors : Uint4B
 +0x0bc NtGlobalFlag : Uint4B
 +0x0c0 CriticalSectionTimeout : _LARGE_INTEGER
 +0x0c8 HeapSegmentReserve : Uint8B
 +0x0d0 HeapSegmentCommit : Uint8B
 +0x0d8 HeapDeCommitTotalFreeThreshold : Uint8B
 +0x0e0 HeapDeCommitFreeBlockThreshold : Uint8B
 +0x0e8 NumberOfHeaps : Uint4B
 +0x0ec MaximumNumberOfHeaps : Uint4B
 +0x0f0 ProcessHeaps : Ptr64 Ptr64 Void
 +0x0f8 GdiSharedHandleTable : Ptr64 Void
 +0x100 ProcessStarterHelper : Ptr64 Void
 +0x108 GdiDCAttributeList : Uint4B
 +0x10c Padding3 : [4] UChar
 +0x110 LoaderLock : Ptr64 _RTL_CRITICAL_SECTION
 +0x118 OSMajorVersion : Uint4B
 +0x11c OSMinorVersion : Uint4B
 +0x120 OSBuildNumber : Uint2B
 +0x122 OSCSDVersion : Uint2B
 +0x124 OSPlatformId : Uint4B
 +0x128 ImageSubsystem : Uint4B
 +0x12c ImageSubsystemMajorVersion : Uint4B
 +0x130 ImageSubsystemMinorVersion : Uint4B
 +0x134 Padding4 : [4] UChar
 +0x138 ActiveProcessAffinityMask : Uint8B
 +0x140 GdiHandleBuffer : [60] Uint4B
 +0x230 PostProcessInitRoutine : Ptr64 void 
 +0x238 TlsExpansionBitmap : Ptr64 Void
 +0x240 TlsExpansionBitmapBits : [32] Uint4B
 +0x2c0 SessionId : Uint4B
 +0x2c4 Padding5 : [4] UChar
 +0x2c8 AppCompatFlags : _ULARGE_INTEGER
 +0x2d0 AppCompatFlagsUser : _ULARGE_INTEGER
 +0x2d8 pShimData : Ptr64 Void
 +0x2e0 AppCompatInfo : Ptr64 Void
 +0x2e8 CSDVersion : _UNICODE_STRING
 +0x2f8 ActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
 +0x300 ProcessAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
 +0x308 SystemDefaultActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
 +0x310 SystemAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
 +0x318 MinimumStackCommit : Uint8B
 +0x320 FlsCallback : Ptr64 _FLS_CALLBACK_INFO
 +0x328 FlsListHead : _LIST_ENTRY
 +0x338 FlsBitmap : Ptr64 Void
 +0x340 FlsBitmapBits : [4] Uint4B
 +0x350 FlsHighIndex : Uint4B
 +0x358 WerRegistrationData : Ptr64 Void
 +0x360 WerShipAssertPtr : Ptr64 Void
 +0x368 pUnused : Ptr64 Void
 +0x370 pImageHeaderHash : Ptr64 Void
 +0x378 TracingFlags : Uint4B
 +0x378 HeapTracingEnabled : Pos 0, 1 Bit
 +0x378 CritSecTracingEnabled : Pos 1, 1 Bit
 +0x378 LibLoaderTracingEnabled : Pos 2, 1 Bit
 +0x378 SpareTracingBits : Pos 3, 29 Bits
 +0x37c Padding6 : [4] UChar
 +0x380 CsrServerReadOnlySharedMemoryBase : Uint8B
 +0x388 TppWorkerpListLock : Uint8B
 +0x390 TppWorkerpList : _LIST_ENTRY
 +0x3a0 WaitOnAddressHashTable : [128] Ptr64 Void
 +0x7a0 TelemetryCoverageHeader : Ptr64 Void
 +0x7a8 CloudFileFlags : Uint4B

As we can see, there’s a lot of fields for the PEB structure. We’ll only be focusing on a select few of them during the practical sections though.

Before we can continue, we need to briefly talk about how the Process Environment Block is actually found. It’s located at FS:[0x30] in the Thread Environment Block/Thread Information Block for 32-bit processes, and it’s located at GS:[0x60] for 64-bit processes.

To start off, the third field of the PEB structure (“BeingDebugged”) can be read to determine if the current process is attached to via a debugger – this is one vector which is commonly closed by analysts who are debugging malicious software, because malicious software tends to keep a close-eye out for debuggers and other analysis tools to make things more difficult for malware analysts. There’s a routine from the Win32 API called IsDebuggerPresent (KERNEL32) and the routine works by checking the BeingDebugged field of the PEB structure. We can validate this by reverse-engineering kernel32.dll ourselves.

IDA pseudo-code for IsDebuggerPresentStub (KERNEL32 – Windows 8+).

As we can see, kernel32.dll has a routine named IsDebuggerPresentStub which calls IsDebuggerPresent. This is because the environment I’m getting these images from is Windows 10 64-bit, and Microsoft moved to using KernelBase.dll (introduced starting Windows 8). However, for backwards-compatibility, kernel32.dll is still pushed for usage by their documentation – and if they had dropped support for it then they would have to have moved more than they have across to a new module project, and there’d have been a lot of incompatible software for Windows 8+ at the time.

Therefore, we need to take a look at KernelBase.dll.

9

Disassembly for IsDebuggerPresent (KERNEL32 / KERNELBASE).

Perfect! KernelBase.dll has an exported routine named IsDebuggerPresent. We’re going to debunk what the above disassembly is telling us.

  1. The address of the Process Environment Block is being moved into the RAX register. Since we’re looking at the 64-bit compiled version of KernelBase.dll, 64-bit registers are being used. The Process Environment Block is located at + 0x60 for 64-bit processes.
  2. The value from the BeingDebugged field under the Process Environment Block is being extracted and put into the EAX register. The data-type for the BeingDebugged field is UCHAR (which is one byte), and it’s offset is 0x002 – the first field of the PEB structure is located at 0x000 which means the third field (which is the BeingDebugged field) is located +2 bytes from this address. Since the RAX register is holding the address to the Process Environment Block, (RAX + 2) is performed to reach the address of the BeingDebugged field.
  3. Returning with the RETN instruction. Since the value for the BeingDebugged field of the PEB structure is held within the EAX register, the caller of the routine is going to return the value stored within the BeingDebugged field.

A routine like IsDebuggerPresent (KERNEL32 / KERNELBASE) might be an obvious sign for a malware analyst who is taking a look at the API calls being made by a sample therefore some malware samples will manually access the PEB structure to check – doing this is stealthier and usually less-expected.

The next fields we’re going to briefly talk about are the IsProtectedProcess and IsProtectedProcessLight fields of the Process Environment Block.

These fields can be used to determine if the current process is “protected” or not, hence the “ProtectedProcess” key-word in the field names. In Windows, there’s multiple process protection mechanisms although the former (non-Light variant) has been around a lot longer than the Process Protection Light (PPL) variant. Standard process protection mechanism in Windows has been around since Windows Vista, however the PPL feature came into play starting Windows 8. Microsoft use these mechanisms to protect their own System processes from being abused by malicious software or forcefully shut-down by a third-party source (because for some Windows processes this can cause the system to bug-check/improperly function). If we can access these fields within the Process Environment Block, then we can check if the current process is protected or not by Windows. All of this is enforced from kernel-mode by the Windows Kernel using the undocumented and opaque EPROCESS structure, and you cannot write to these fields in the PEB structure and have the changes take effect because it won’t update the EPROCESS structure for the current process.

The standard process protection mechanism is used by Windows system processes. This mechanism is enforced from within the Windows Kernel and it’s not supposed to be used by third-parties, and it helps prevent system processes from being exploited by attackers (or forcefully shut-down – the Operating System cannot function properly without it’s critical user-mode components). On top of this, Windows will set the state of various system processes to “critical”, and this is flag-based and will cause the system to be forcefully crashed (via a bug-check) if the “critical” processes become terminated. There are two different implementations for the “critical” state: critical processes and critical threads. Setting a process as critical will cause the bug-check once the process has been terminated, and setting a thread as critical will cause the bug-check once the thread has been terminated. Usually, the former is more appropriate because threads come and go regularly (e.g. spawn a new thread to handle an operation simultaneously and then the thread will be terminated once it returns back it’s status from the operation). Windows does not set “threads” as critical as far as I am aware, although it will set specific processes as critical (processes like csrss.exe).

We’re going to take a look at how the process protection mechanism which is built-into Windows actually works very briefly using Interactive Disassembler and WinDbg. 

We can easily check using the following routines.

  1. PsIsProtectedProcess (NTOSKRNL)
  2. PsIsProtectedProcessLight (NTOSKRNL)

Both of the above routines are undocumented but they are still exported by the Windows Kernel.

11

Disassembly for PsIsProtectedProcess (NTOSKRNL).

Looking at the disassembly of PsIsProtectedProcess, we can see that the TEST instruction is being used. The TEST instruction is used for a “bitwise operation”. However, we can also see that [RCX+6CAh] is the target. The PsIsProtectedProcess routine takes in one parameter only and it returns a BOOLEAN (UCHAR) – the parameter’s data-type should be a pointer to the EPROCESS structure for the target process being checked on. This tells us that the value stored in the RCX register will be the address of the PEPROCESS (EPROCESS*) for the target process, and it’s accessing the structure to read the value stored under an unknown field which symbolises if the process is or is not protected. The offset for where the field under the EPROCESS structure is located is 6CAh. This means that if you add on 0x6CA from the base address of the EPROCESS* for a process, you will land yourself at the address in which the value being checked in this routine is located at (for this environment only because the offsets regularly shift around and will vary between environment – due to patch updates and separate OS versions).

We can check with WinDbg which field is for the 0xC6A offset.

12

WinDbg command (dt) for the _EPROCESS structure, showing the Protection field.

Nice! The field in the EPROCESS structure which holds data regarding process protection is named Protection and has a data-type of _PS_PROTECTION (which is a structure) – at-least for the standard process protection mechanism, we are yet to check on the Light variant. We can take a look at the _PS_PROTECTION structure with the dt instruction.

WinDbg command (dt) for the _PS_PROTECTION structure.

Now if we check the disassembly of the PsIsProtectedProcessLight routine, we can see if it uses the same mechanism to query the status.

14

Disassembly for PsIsProtectedProcessLight (NTOSKRNL).

It’s targeting the Protection field of the EPROCESS structure as well – the same field of the structure too. The only difference here is that PsIsProtectedProcess is and PsIsProtectedProcessLight are doing some different checks.

In the PEB structure, there’s an entry named Ldr which has a data-type of _PEB_LDR_DATA. Within this structure, we have a field named InMemoryOrderModuleList which has a data-type of _LIST_ENTRY. Double linked lists are very common in Windows components such as in the Windows Kernel or lower-level user-mode components.

There’s an instruction in WinDbg named !peb which can be used to enumerate data for the PEB of the currently debugged process. Below is an image of what the output will look like, focus only on the non-highlighted parts.

15

WinDbg command (!peb) output.

If we go through the InMemoryOrderModuleList, we can extract each entry and assign to a pointer of the LDR_DATA_TABLE_ENTRY structure using the CONTAINING_RECORD macro. Then we could view details about the current module enumerated using the linked lists… We will do this during the practical code section which is right about now.

We’re going to be using the PEB for practical use in the next section.

User-Mode


In this section we’re going to be re-writing a few Win32 API routines in user-mode which rely on the Process Environment Block.

  1. GetModuleHandle – using the Ldr field of the PEB structure
  2. GetModuleFileName – using the ProcessParameters field of the PEB structure

We need to make sure we’ve declared some structures. Depending on the header files you’re using, you may not need them. However if you do need them…

typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    WCHAR *Buffer;
} UNICODE_STRING, PUNICODE_STRING;

typedef const UNICODE_STRING
              *PCUNICODE_STRING;

typedef struct _CLIENT_ID {
    PVOID UniqueProcess;
    PVOID UniqueThread;
} CLIENT_ID, *PCLIENT_ID;

typedef struct _RTL_USER_PROCESS_PARAMETERS {
    BYTE Reserved1[16];
    PVOID Reserved2[10];
    UNICODE_STRING ImagePathName;
    UNICODE_STRING CommandLine;
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;

typedef struct _PEB_LDR_DATA {
    BYTE Reserved1[8];
    PVOID Reserved2[3];
    LIST_ENTRY InMemoryOrderModuleList;
} PEB_LDR_DATA, *PPEB_LDR_DATA;

typedef struct _LDR_DATA_TABLE_ENTRY {
    PVOID Reserved1[2];
    LIST_ENTRY InMemoryOrderLinks;
    PVOID Reserved2[2];
    PVOID BaseAddress;
    PVOID Reserved3[2];
    UNICODE_STRING FullDllName;
    UNICODE_STRING BaseDllName;
    BYTE Reserved4[8];
    PVOID Reserved5[3];
#pragma warning(push)
#pragma warning(disable: 4201) // we'll always use the Microsoft compiler
    union {
        ULONG CheckSum;
        PVOID Reserved6;
    } DUMMYUNIONNAME;
#pragma warning(pop)
    ULONG TimeDateStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;

typedef struct _PEB {
    BYTE Reserved1[2];
    BYTE BeingDebugged;
    BYTE Reserved2[1];
    PVOID Reserved3[2];
    PPEB_LDR_DATA Ldr;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
    PVOID Reserved4[3];
    PVOID AtlThunkSListPtr;
    PVOID Reserved5;
    ULONG Reserved6;
    PVOID Reserved7;
    ULONG Reserved8;
} PEB, *PPEB;

typedef struct _TEB {
    NT_TIB NtTib;
    PVOID EnvironmentPointer;
    CLIENT_ID ClientId;
    PVOID ActiveRpcHandle;
    PVOID ThreadLocalStoragePointer;
    PPEB ProcessEnvironmentBlock;
} TEB, *PTEB;

The next thing you might want is a global definition for NtCurrentPeb(). This isn’t mandatory but it can be a bit helpful if you’d prefer to type NtCurrentPeb() instead of NtCurrentTeb()->ProcessEnvironmentBlock every-time you need to gain access to the PEB. I always preferred to type NtCurrentPeb() but that’s just me.

#define NtCurrentPeb() \
        NtCurrentTeb()->ProcessEnvironmentBlock

What is NtCurrentTeb()?

NtCurrentTeb() is a function which is packed within winnt.h, and it’ll return a pointer to the TEB structure at the correct address of where the TEB is located.

NtCurrentTeb() will change depending on the configuration however for a 32-bit compilation, it will locate the TEB by using the __readfsdword macro, targeting 0x18 as the location. This means that the target location is actually FS:[0x18]. For a 64-bit compilation, __readgsqword will be used and the target location will be different.

GetModuleHandle replacement

HMODULE GetModuleHandleWrapper(
    WCHAR *ModuleName
)
{
    PPEB ProcessEnvironmentBlock = NtCurrentPeb();
    PPEB_LDR_DATA PebLdrData = { 0 };
    PLDR_DATA_TABLE_ENTRY LdrDataTableEntry = { 0 };
    PLIST_ENTRY ModuleList = { 0 },
                ForwardLink = { 0 };

    if (ProcessEnvironmentBlock)
    {
        PebLdrData = ProcessEnvironmentBlock->Ldr;

        if (PebLdrData)
        {
            ModuleList = &PebLdrData->InMemoryOrderModuleList;
            ForwardLink = ModuleList->Flink;

            while (ModuleList != ForwardLink)
            {
                LdrDataTableEntry = CONTAINING_RECORD(ForwardLink,
                    LDR_DATA_TABLE_ENTRY,
                    InMemoryOrderLinks);

                if (LdrDataTableEntry)
                {
                    if (LdrDataTableEntry->BaseDllName.Buffer)
                    {
                        if (!_wcsicmp(LdrDataTableEntry->BaseDllName.Buffer,
                            ModuleName))
                        {
                            return (HMODULE)LdrDataTableEntry->BaseAddress;
                        } 
                     }
                 }

                 ForwardLink = ForwardLink->Flink;
             }
         }
    }

    return 0;
}

The above routine does the following.

  1. Retrieves the PPEB
  2. Checks if the PPEB could be acquired or not
  3. Enumerates the InMemoryOrderModuleList
  4. Retrieves a pointer to the LDR_DATA_TABLE_ENTRY structure for each entry
  5. Returns the BaseAddress of the module if its a match based on module name buffer comparison with the parameter passed in

GetModuleFileName wrapper

WCHAR *GetModuleFileNameWrapper()
{
    PPEB ProcessEnvironmentBlock = NtCurrentPeb();
    
    if (ProcessEnvironmentBlock)if (ProcessEnvironmentBlock)
    {
        if (ProcessEnvironmentBlock->ProcessParameters)
        {
            if (ProcessEnvironmentBlock->ProcessParameters->ImagePathName.Buffer)
            {
                if (ProcessEnvironmentBlock->ProcessParameters->ImagePathName.Buffer)
                {
                    return ProcessEnvironmentBlock->ProcessParameters->ImagePathName.Buffer;
                }
            }
        }
    }

    return NULL;
}

The above routine does the following.

  1. Retrieves the PPEB (pointer to the PEB)
  2. Checks if the PPEB could be acquired or not
  3. Checks if it can access the ProcessParameters field
  4. Returns the ImagePathName buffer (it’s a UNICODE_STRING so the Buffer field is a wchar_t*)

All of this has been known for an extremely long time now but for those of you which have only just got into Windows Internals and started studying areas like the Process Environment Block, this could help clear things up for you quickly and put an end to some confusion.

As always, thanks for reading.

NtOpcode

The Process Environment Block is a critical structure in the Windows OS, most of its fields are not intended to be used by other than the operating system. It contains data structures that apply across a whole process and is stored in user-mode memory, which makes it accessible for the corresponding process. The structure contains valuable information about the running process, including:

  • whether the process is being debugged or not
  • which modules are loaded into memory
  • the command line used to invoke the process

Installation of WinDbg (Microsoft Store)

Download and install WinDbg, then attach it to the running process as the example I will be using notepad.exe.

WINDBG

Navigate to your installation directory, and open WinDbg.exe.
On the File menu, choose 1) Open Executable or 2) Attach to process.

1) In the Open Executable dialog box, navigate to the folder that contains notepad.exe (typically, C:\Windows\System32). For the File name, enter notepad.exe. Select Open.

2) In the second option just pick the running process in our case it’s notepad.exe.

ATTACH

PREVIEW

You should end up with something like this, near the bottom of the WinDbg window, in the command line, enter these commands.

Overview of PEB structure

First, based on MSDN documentation the PEB structure

typedef struct _PEB {
  BYTE                          Reserved1[2];
  BYTE                          BeingDebugged;
  BYTE                          Reserved2[1];
  PVOID                         Reserved3[2];
  PPEB_LDR_DATA                 Ldr;
  PRTL_USER_PROCESS_PARAMETERS  ProcessParameters;
  PVOID                         Reserved4[3];
  PVOID                         AtlThunkSListPtr;
  PVOID                         Reserved5;
  ULONG                         Reserved6;
  PVOID                         Reserved7;
  ULONG                         Reserved8;
  ULONG                         AtlThunkSListPtr32;
  PVOID                         Reserved9[45];
  BYTE                          Reserved10[96];
  PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine;
  BYTE                          Reserved11[128];
  PVOID                         Reserved12[1];
  ULONG                         SessionId;
} PEB, *PPEB;

The PEB isn’t fully documented, so you must use WinDbg to see its full structure or use sites like !NirSoft.

typedef struct _PEB
{
     UCHAR InheritedAddressSpace;
     UCHAR ReadImageFileExecOptions;
     UCHAR BeingDebugged;
     UCHAR BitField;
     ULONG ImageUsesLargePages: 1;
     ULONG IsProtectedProcess: 1;
     ULONG IsLegacyProcess: 1;
     ULONG IsImageDynamicallyRelocated: 1;
     ULONG SpareBits: 4;
     PVOID Mutant;
     PVOID ImageBaseAddress;
     PPEB_LDR_DATA Ldr;
     PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
     PVOID SubSystemData;
     PVOID ProcessHeap;
     PRTL_CRITICAL_SECTION FastPebLock;
     PVOID AtlThunkSListPtr;
     PVOID IFEOKey;
     ULONG CrossProcessFlags;
     ULONG ProcessInJob: 1;
     ULONG ProcessInitializing: 1;
     ULONG ReservedBits0: 30;
     union
     {
          PVOID KernelCallbackTable;
          PVOID UserSharedInfoPtr;
     };
     ULONG SystemReserved[1];
     ULONG SpareUlong;
     PPEB_FREE_BLOCK FreeList;
     ULONG TlsExpansionCounter;
     PVOID TlsBitmap;
     ULONG TlsBitmapBits[2];
     PVOID ReadOnlySharedMemoryBase;
     PVOID HotpatchInformation;
     VOID * * ReadOnlyStaticServerData;
     PVOID AnsiCodePageData;
     PVOID OemCodePageData;
     PVOID UnicodeCaseTableData;
     ULONG NumberOfProcessors;
     ULONG NtGlobalFlag;
     LARGE_INTEGER CriticalSectionTimeout;
     ULONG HeapSegmentReserve;
     ULONG HeapSegmentCommit;
     ULONG HeapDeCommitTotalFreeThreshold;
     ULONG HeapDeCommitFreeBlockThreshold;
     ULONG NumberOfHeaps;
     ULONG MaximumNumberOfHeaps;
     VOID * * ProcessHeaps;
     PVOID GdiSharedHandleTable;
     PVOID ProcessStarterHelper;
     ULONG GdiDCAttributeList;
     PRTL_CRITICAL_SECTION LoaderLock;
     ULONG OSMajorVersion;
     ULONG OSMinorVersion;
     WORD OSBuildNumber;
     WORD OSCSDVersion;
     ULONG OSPlatformId;
     ULONG ImageSubsystem;
     ULONG ImageSubsystemMajorVersion;
     ULONG ImageSubsystemMinorVersion;
     ULONG ImageProcessAffinityMask;
     ULONG GdiHandleBuffer[34];
     PVOID PostProcessInitRoutine;
     PVOID TlsExpansionBitmap;
     ULONG TlsExpansionBitmapBits[32];
     ULONG SessionId;
     ULARGE_INTEGER AppCompatFlags;
     ULARGE_INTEGER AppCompatFlagsUser;
     PVOID pShimData;
     PVOID AppCompatInfo;
     UNICODE_STRING CSDVersion;
     _ACTIVATION_CONTEXT_DATA * ActivationContextData;
     _ASSEMBLY_STORAGE_MAP * ProcessAssemblyStorageMap;
     _ACTIVATION_CONTEXT_DATA * SystemDefaultActivationContextData;
     _ASSEMBLY_STORAGE_MAP * SystemAssemblyStorageMap;
     ULONG MinimumStackCommit;
     _FLS_CALLBACK_INFO * FlsCallback;
     LIST_ENTRY FlsListHead;
     PVOID FlsBitmap;
     ULONG FlsBitmapBits[4];
     ULONG FlsHighIndex;
     PVOID WerRegistrationData;
     PVOID WerShipAssertPtr;
} PEB, *PPEB;

Usage and useful commands when exploring the PEB.

Dump _PEB structure: dt ntdll!_PEB.
“dt” stands for “Display Type” and can be used to display information about a specific data-type

PEB

PEB address of the process: r $peb.

PEB_Addr

The _PEB structure can now be overlaid on the memory pointed to by the $peb to see what values the structure members are holding/pointing to: dt ntdll!_PEB @$peb.

PEB_overview

BeingDebugged

+0x002 BeingDebugged : 0x1 ''

The most obvious flag to identify is whether a debugger is attached to the process or not. By reading the variable directly from memory instead of using usual suspects like NtQueryInformationProcess or IsDebuggerPresent, malware can prevent noisy WINAPI calls. This makes it harder to spot this technique.

Ldr (Getting a list of loaded modules)

+0x018 Ldr : 0x00007ffd5ed1a4c0 _PEB_LDR_DATA

Is one of the most important fields in the PEB. This is a pointer to a structure that contains information about the process’s loaded modules, and to the Head node of a doubly-linked list.
The linked list can help us find the addresses of structures that represent the loaded DLLs.

We can get InMemoryOrderModuleList by dt _PEB_LDR_DATA 0x00007ffd5ed1a4c0

inmodule

Or more fancy way dt _peb @$peb Ldr->InMemoryOrderModuleList

inmodule

Go go over linked list we can use !list -x "dt _LDR_DATA_TABLE_ENTRY FullDllName->Buffer" 0x00000257b19a4210 where 0x00000257b19a4210 is our InMemoryOrderModuleList.

list

ImageBaseAddress

+0x010 ImageBaseAddress : 0x00007ff7f45b0000 Void

Is it actually the valid address of the executable image in process memory we can try to inspect it using our PEB dump
db 0x00007ff7f45b0000 L100

PEB_overview

ProcessParameters

Is a pointer to RTL_USER_PROCESS_PARAMETERS structure. To inspect it we are going to find ProcessParameters address.

dt _peb @$peb ProcessParameters

Params1

Now we can dump it using dt _RTL_USER_PROCESS_PARAMETERS 0x00000257b19a37b0

Params

Or we can forget about all of the above and just use: !peb

PEB!

How the Process Environment Block (PEB) is actually found.

On the user mode basis of a 32-bit window, the FS register points to a structure called a Thread Environment Block (TEB) or Thread Information Block (TIB). This structure stores information about the currently running thread. This is mainly used because information can be obtained without calling API functions. Note that the FS register points to the first address of the TEB, so you can add values by position to access the desired fields. In the x64 environment, the GS register is used instead of the FS register.

TEB Structure for x86/x64

teb!

The PEB can be found at fs:[0x30] in the Thread Environment Block (TEB)/Thread Information Block (TIB) for x86 processes as well as at gs:[0x60] for x64 processes.

x64 ASM

GetPEB proc
mov rax, qword ptr gs:[00000060h] // move PEB from TEB into rax (64 bit process  gs : [0x60]);
ret                               // return rax
GetPEB endp

x86 ASM

__declspec(naked) PEB* __stdcall get_peb() 
{
  __asm mov eax, dword ptr fs : [0x30] ; // move PEB from TEB into eax (32 bit process fs : [0x30])
  __asm ret;                             // return eax
}

You do not need to use ASM for this, you can use intrinsic functions like so:
__readfsdword/__readgsqword are compiler intrinsic functions that will generate more optimized code, there is no reason to use inline assembly. Inline assembly is not even supported by Microsoft’s compilers for 64-bit targets.

PEB *GetPeb() 
{
#ifdef _M_X64
  return reinterpret_cast<PEB*>(__readgsqword(0x60));
#elif _M_IX86
  return reinterpret_cast<PEB*>(__readfsdword(0x30));
#else
  #error "PEB Architecture Unsupported"
#endif  
}

Support non-ARM systems

Structure defined inside winnt.h. It’s the staring point for the algorithm. It includes self-referencing field — Self pointer, offset of which is used on non-ARM systems to read Thread Environment Block data.

typedef struct _NT_TIB {
    struct _EXCEPTION_REGISTRATION_RECORD *ExceptionList;
    PVOID StackBase;
    PVOID StackLimit;
    PVOID SubSystemTib;
#if defined(_MSC_EXTENSIONS)
    union {
        PVOID FiberData;
        DWORD Version;
    };
#else
    PVOID FiberData;
#endif
    PVOID ArbitraryUserPointer;
    struct _NT_TIB *Self;
} NT_TIB;
typedef NT_TIB *PNT_TIB;

After the executable is loaded by the Windows PE loader and before the thread starts running, TEB is saved to fs(x86) or gs(x64) processor register. ARM systems use different technique which utilize coprocessors scheme (it’s unclear whether the coprocessor is real hardware component or emulated). Self field of NT_TIB is the TEB pointer for the current thread.

Even not officially documented, this behavior is observed on/for all available Windows operating systems with NT kernel.

Acquiring pointer to the TEB is done using Microsoft specific compiler intrinsics:

#include <winnt.h>
#include <winternl.h>

#if defined(_M_X64) // x64
    auto pTeb = reinterpret_cast<PTEB>(__readgsqword(reinterpret_cast<DWORD>(&static_cast<NT_TIB*>(nullptr)->Self)));
#elif defined(_M_ARM) // ARM
    auto pTeb = reinterpret_cast<PTEB>(_MoveFromCoprocessor(15, 0, 13, 0, 2)); // CP15_TPIDRURW
#else // x86
    auto pTeb = reinterpret_cast<PTEB>(__readfsdword(reinterpret_cast<DWORD>(&static_cast<NT_TIB*>(nullptr)->Self)));
#endif

Among others, one of the fields inside the TEB is pointer to the PEB (Process Environment Block).

Access TEB the Windows way

User-mode code can easily find its own process’s PEB, albeit only by using undocumented or semi-documented behavior. While a thread executes in user mode, its fs or gs register, for 32-bit and 64-bit code respectively, addresses the thread’s TEB. That structure’s ProcessEnvironmentBlock member holds the address of the current process’s PEB. In NTDLL version 5.1 and higher, this simple work is available more neatly as an exported function, named RtlGetCurrentPeb, but it too is undocumented. Its implementation is something very like

PEB *RtlGetCurrentPeb(VOID)
{
    return NtCurrentTeb()->ProcessEnvironmentBlock;
}

// For its own low-level user-mode programming, Microsoft has long had a macro or inlined 
// routine, apparently named NtCurrentPeb, which reads directly from fs or gs, e.g.
PEB *NtCurrentPeb (VOID)
{
    return (PEB *) __readfsdword (FIELD_OFFSET (TEB, ProcessEnvironmentBlock));
}

To use NtCurrentTeb() without Windows header files declare the function prototype and link against ntdll.dll.

What’s next?

In second part we’ll put the described how to manually write functions like IsDebuggerPresent or GetModuleHandle to see how a program can parse the PEB to recover Kernel32.dll address, and then load any other library. Not a single import is needed!

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Appearance settings

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Сбрасывается расположение иконок на рабочем столе windows 10
  • Отключить автоматическую перезагрузку windows server 2019
  • Windows 7 memes edition
  • Windows server 2003 доклад
  • Kaspersky security для windows server key