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.
Contents
- 1 Introduction
- 2 Thread Lifecycle
- 3 Thread Environment Block (TEB)
- 4 Thread Creation APIs (Detailed)
- 5 Thread Injection Basics
- 6 Common Thread Injection Techniques
- 7 Detection and Analysis of Thread Injection
- 8 Thread Hijacking via TEB Manipulation (Advanced)
- 9 Forensics and Incident Response Tips
- 10 Summary
- 11 Related Tutorials
- 12 References
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.

Thread Lifecycle
A typical thread undergoes these stages:
Creation → Scheduling → Execution → Waiting/Blocking → TerminationDetailed 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 (
0to31).
- 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
- Stack Base (
Accessing the TEB (x64):
mov rax, gs:[0x30] ; RAX now contains TEB pointerThread 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:
- Obtain Handle:
OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); - Allocate Memory:
VirtualAllocEx(hProc, ...) - Write Payload:
WriteProcessMemory(hProc, remoteMemory, ...) - 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
| Technique | Description |
|---|---|
CreateRemoteThread | Direct injection of threads into another process |
NtCreateThreadEx | More advanced version of CreateRemoteThread |
QueueUserAPC | Injecting asynchronous procedure calls |
SetThreadContext | Hijacking 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 StackLimitThis 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).
Related Tutorials
- Fibers: User-Mode Cooperative Threads
- Windows Scheduler Internals: Priority Levels, Quantum, and Thread Selection
- APCs: Asynchronous Procedure Calls and Thread Hijacking Surface
- Access Tokens and Privileges: The Kernel’s Security Context
- SIDs and Security Descriptors: Identity in Windows Security
References
- Thread Environment Block (Debugging Notes) – Win32 Apps | Microsoft Learn
- !teb (WinDbg Debugger Command) – Windows Drivers | Microsoft Learn
- TEB – Geoff Chappell, Software Analyst (Detailed Field-by-Field Reference)
- Win32 Thread Information Block (TIB / TEB) – Wikipedia
- Process Injection: Thread Local Storage (T1055.005) – MITRE ATT&CK
Get new drops in your inbox
Windows internals, exploit dev, and red-team write-ups — no spam, unsubscribe anytime.