Threads and the TEB (Thread Environment Block)

Objective: Understand the internal workings of threads on Windows, the lifecycle of a thread from creation to termination, the critical role of the Thread Environment Block (TEB), and fundamentals of thread injection techniques. This foundational knowledge is crucial for system developers, reverse engineers, malware analysts, and red teamers.


Introduction

A thread is the smallest execution unit within a process on Windows, scheduled independently by the OS kernel. Every process contains at least one thread, but often many more. Each thread maintains its own state, CPU registers, stack, and local storage.

Central to each thread’s operation is the Thread Environment Block (TEB), a user-mode structure containing thread-specific data critical for thread execution, error handling, exception handling, and system call interfacing.

TEB

Thread Lifecycle

A typical thread undergoes these stages:

Creation β†’ Scheduling β†’ Execution β†’ Waiting/Blocking β†’ Termination

Detailed Steps:

  • Creation:
    Initiated via APIs like:
    • CreateThread()
    • RtlCreateUserThread()
    • NtCreateThreadEx()
  • Scheduling (Kernel):
    Windows uses priority-based preemptive scheduling:
    • Quantum: Thread time-slice allocated for execution.
    • Threads can have different priority levels (0 to 31).
  • Execution (User-Mode):
    Execution starts at thread entry function (LPTHREAD_START_ROUTINE).
  • Waiting/Blocking:
    Threads often enter waiting states (WaitForSingleObject(), Sleep(), I/O waits).
  • Termination:
    Ends via:
    • Returning from thread function
    • Calling ExitThread()
    • Termination by another thread (TerminateThread() – unsafe)

Thread Environment Block (TEB)

Each thread has a unique TEB, accessed quickly via the FS:[0x18] register on x86 or GS:[0x30] on x64.

Key TEB fields:

typedef struct _TEB {
    NT_TIB NtTib;
    PVOID  EnvironmentPointer;
    CLIENT_ID ClientId;           // Unique Thread ID and Process ID
    PVOID  ActiveRpcHandle;
    PVOID  ThreadLocalStoragePointer;
    PPEB   ProcessEnvironmentBlock; // Pointer to the PEB
    ULONG  LastErrorValue;
    ULONG  CountOfOwnedCriticalSections;
    PVOID  Win32ThreadInfo;
    ULONG  CurrentLocale;
    ULONG  FpSoftwareStatusRegister;
    // ... (more fields)
} TEB;

Notable Fields Explained:

  • ClientId: Contains the thread’s TID and owning PID.
  • ProcessEnvironmentBlock (PEB): Points to the process-wide PEB structure.
  • ThreadLocalStoragePointer: Points to thread-local storage (TLS).
  • LastErrorValue: Stores the last error value (GetLastError()).
  • NtTib: Contains:
    • Stack Base (StackBase)
    • Stack Limit (StackLimit)
    • Exception handler list

Accessing the TEB (x64):

mov rax, gs:[0x30] ; RAX now contains TEB pointer


Thread Creation APIs (Detailed)

1. CreateThread()

Commonly used high-level API:

HANDLE CreateThread(
  LPSECURITY_ATTRIBUTES lpThreadAttributes,
  SIZE_T dwStackSize,
  LPTHREAD_START_ROUTINE lpStartAddress,
  LPVOID lpParameter,
  DWORD dwCreationFlags,
  LPDWORD lpThreadId
);

2. NtCreateThreadEx() (Native)

Lower-level, flexible NTAPI:

NTSTATUS NtCreateThreadEx(
  PHANDLE ThreadHandle,
  ACCESS_MASK DesiredAccess,
  POBJECT_ATTRIBUTES ObjectAttributes,
  HANDLE ProcessHandle,
  PVOID StartRoutine,
  PVOID Argument,
  ULONG CreateFlags,
  SIZE_T ZeroBits,
  SIZE_T StackSize,
  SIZE_T MaximumStackSize,
  PVOID AttributeList
);

  • Powerful for cross-process thread injection.

Thread Injection Basics

Thread injection is a fundamental technique in malware development and red teaming, allowing execution of code in a remote process.

Thread Injection Workflow:

  1. Obtain Handle:
    OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  2. Allocate Memory:
    VirtualAllocEx(hProc, ...)
  3. Write Payload:
    WriteProcessMemory(hProc, remoteMemory, ...)
  4. Create Remote Thread:
    CreateRemoteThread(hProc, ..., remoteMemory, ...)

Simplified Example (Remote Thread Injection):

// Open handle to target process
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

// Allocate memory
LPVOID remoteMemory = VirtualAllocEx(hProcess, NULL, payloadSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

// Write payload (shellcode or DLL loader)
WriteProcessMemory(hProcess, remoteMemory, payload, payloadSize, NULL);

// Start remote thread execution
CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remoteMemory, NULL, 0, NULL);


Common Thread Injection Techniques

TechniqueDescription
CreateRemoteThreadDirect injection of threads into another process
NtCreateThreadExMore advanced version of CreateRemoteThread
QueueUserAPCInjecting asynchronous procedure calls
SetThreadContextHijacking an existing thread’s execution context

Detection and Analysis of Thread Injection

Indicators:

  • Suspicious CreateRemoteThread() calls targeting unexpected processes
  • Memory allocated (VirtualAllocEx) with execute permissions (PAGE_EXECUTE_READWRITE)
  • Threads created by processes other than expected parent processes

Tools for Detection:

  • Sysmon (Event ID 8: CreateRemoteThread)
  • Process Hacker, Process Monitor
  • API hooking (EDR solutions)
  • Memory scanners (Volatility, Rekall)

Thread Hijacking via TEB Manipulation (Advanced)

Malware can directly manipulate the TEB to hijack threads:

  • Overwrite TEB’s stack pointers or exception handlers
  • Intercept thread execution flow

Example (x64 Assembly):

mov rax, gs:[0x30]    ; TEB base
mov [rax+0x8], myStackBase   ; overwrite StackBase
mov [rax+0x10], myStackLimit ; overwrite StackLimit

This is advanced and dangerous but illustrates TEB exploitation potential.


Forensics and Incident Response Tips

  • Collect thread information during IR investigations:
Get-Process -Id $PID | Select -Expand Threads

  • Dump TEB structures and thread contexts with WinDbg or volatility.
  • Watch for abnormal thread creations in unexpected processes or sudden thread terminations.

Summary

  • Threads are fundamental units of execution managed by Windows.
  • Each thread maintains critical data in the TEB structure.
  • Threads can be created, injected, and manipulated by advanced APIs.
  • Injection techniques are commonly abused by malware and red teams.
  • Detection relies on system-level monitoring (Sysmon, API hooks).

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments