🌵
Rotta
  • ☕General
    • About Me
    • Recently Added
  • ☣️Offensive Tool Development
    • Windows Internals
      • Registers
      • x64 Calling Convention
      • PE File Format
        • PE File Structure
        • DOS Header, DOS Stub, & Rich Header
        • NT Headers
        • Data Directories & Section Headers
        • Import Directory Table, ILT & IAT
        • Image Export Table
        • PE Base Relocations
      • Processes & PEB Structure
      • Threads & TEB Structure
      • Event Tracing for Windows (ETW)
        • Interacting with ETW
        • ETW Tools
    • Enumeration
      • Process Enumeration
        • CreateToolhelp32Snapshot
        • EnumProcesses (psapi.h)
        • NtQuerySystemInformation
        • NtQueryInformationProcess
      • Thread Enumeration
        • CreateToolhelp32Snapshot
        • NtQuerySystemInformation
      • DLL Enumeration
    • Memory Allocation
      • Private Memory Allocation
      • Memory Mapping
    • Access Tokens
      • Page 1
    • Techniques and Exploitation Methods
      • Thread Hijacking
      • DLL Injection
      • Shellcode Reflective DLL Injection
      • APC Injection
      • Callback Process Injection
      • Function Stomping
      • DLL Sideloading
      • Local PE Injection
      • Reflective DLL Injection
      • Process Hollowing
    • PE Tips & Tricks
      • Parsing PE Headers
      • Patching IAT
      • Patching Base Relocations
      • Fixing Memory Permissions
      • Embed an EXE inside a LNK
      • PE Infection
    • Staging
      • Fetch Payload from Web Server
      • Fetch DLL from Web Server
    • Bypassing AV
      • String Hashing
      • Hiding & Obfuscating IAT
      • Custom WINAPI Functions
        • GetProcAddressHash
      • File Bloating
    • Evading EDR
      • Payload Execution Control
      • Wrapping NTAPI Functions
        • NtCreateUserProcess
        • NtQuerySystemInformation
      • PPID Spoofing
      • Call Stack Spoofing
      • NTDLL Unhooking
        • NTDLL Unhooking - From Disk
        • NTDLL Unhooking - From KnownDlls
        • NTDLL Unhooking - From Suspended Process
        • NTDLL Unhooking - From Web Server
    • Anti-Analysis Techniques
      • Anti-Debugging Techniques
        • Check If Running In a Debugger
        • Self Deleting Malware
      • Anti-Virtual Environments (AVE) Techniques
        • Detecting Hardware Specs
        • Delaying Execution
        • API Hammering
      • Reducing Binary Entropy
      • Brute Forcing Decryption Key
      • Removing MSCRT
      • Hiding / Camouflaging IAT
    • API Hooking
      • Userland Hooking
      • Custom Hooking Function
      • Open-Source Hooking Libraries
        • Microsoft's Detours Library
        • MinHook Library
    • Syscalls
      • NTAPI Syscall Process Injection
      • Direct Syscalls
        • SysWhispers
      • Indirect Syscalls
    • C2 Development
      • Consensus & Design Patterns
      • Infrastructure
      • Teamserver
      • Listeners
      • Agent Stubs
      • Encrypting Communication
    • User Defined Reflective Loader (UDRL)
    • MalDev Environment Setup
      • Setting up Dev Box
      • Setting up Pwn Box
      • Setting up Dev Server
      • Commando VM
    • Maldev Checklist
  • 👺Red Teaming
    • Setting up Infrastructure
    • External Recon
    • Internal Recon & Enumeration
      • Host Reconnaissance
      • Host Enumeration
    • Password Attacks
      • Password Spraying OWA
    • Phishing / Initial Compromise
      • Setting up Infrastructure
      • Crafting the Email
      • EvilGinx
      • Browser In Browser Attack
      • MS Office Phishing
        • VBA Macro Beacon
        • Remote Template Injection
        • HTML Smuggling
    • Privilege Escalation
      • Windows Services
      • UAC Bypass
      • Elevated SYSTEM Persistence
    • Persistence
      • Scheduled Tasks
      • Registry AutoRun
      • Startup Folder
      • COM Hijacking
      • Elevated SYSTEM Persistence
    • Payload Delivery
      • MS Office Payloads
        • Mark of the Web (MOTW).
        • Visual Basic Macro (VBA)
        • Remote Template Injection
      • SCR File Attack
    • Stealing Credentials
      • MimiKatz
      • Rubeus
      • Page 2
    • Domain Reconnaissance
      • PowerView & SharpView
      • ADSearch
    • Lateral Movement
      • User Impersonation
        • Pass The Hash (PTH)
        • Pass The Ticket (PTT)
        • Overpass The Hash
        • Token Impersonation
        • Token Store
    • Kerberos & Active Directory Attacks
      • Kerberoasting
      • ASREP Roasting
      • Kerberos Relay Attacks
      • Shadow Credentials
      • Unconstrained Delegation
      • Constrained Delegation
    • Cobalt Strike
      • Start Team Server
      • Configure Listeners
      • Beacons
        • UDRLess Beacon
    • Cracking Passwords
    • Tools & Checklists
      • Commands Cheat Sheet
      • Tools
      • Red Team Checklist
  • 🪟Active Directory
    • Active Directory Toolkit
      • Windows Tools
        • ActiveDirectory PowerShell Module
        • PowerView
        • SharpHound/BloodHound
        • Snaffler
      • Kali Linux Tools
        • Windapsearch & Ldapsearch
        • CrackMapExec
        • SMBMap
        • rpcclient
        • Impacket Toolkit
        • Bloodhound
    • Enumerating Active Directory
      • net.exe
      • Powershell Active Directory Commands
      • Powershell & .NET Classes
      • PowerView / SharpView
      • Enumerating Service Accounts
      • Enumerating Object Permissions
      • Enumerating Objects
      • Active Directory Certificate Services (AD CS)
    • Attacking Active Directory Authentication
      • AS-REP Roasting
      • Kerberoasting
      • Silver Tickets
      • Domain Controller Synchronization (Dsync Attack)
      • Kerberos Relay Attack
      • NTLM Relay Attack
      • Attacking Service Accounts
    • Password Spraying
      • Enumeration & Retrieving Password Policy
      • Creating a Target User List
      • Brute Force / Password Spraying - Linux Tools
      • Internal Spraying - From Windows
    • Lateral Movement Techniques
      • WMI and WinRM
      • PsExec
      • Pass The Hash
      • Overpass The Hash
      • Pass The Ticket
      • DCOM
    • Persistence
      • Golden Ticket
      • Shadow Copies
    • God Access
      • GenericAll Abuse
      • NTDS Tom Foolery
    • Lab Environment Setup
      • Installing Forest
      • Adding Data to Active Directory
    • Templates & Cheat Sheets
  • 🦈Penetration Testing
    • Information Gathering / Reconnaisance
      • Client Fingerprinting
      • External Recon and Enumeration
      • Network Reconnaisance
        • Scanning for Hosts
        • Initial Enumeration of AD Network
        • SMB Network Shares
      • Vulnerability Scanning
        • Nessus
        • Nmap
      • Popped a Shell
    • Pivoting, Tunneling, and Port Forwarding
      • SSH
      • Socat
      • Pivoting
        • plink.exe
        • netsh
        • Web Server Pivoting with Rpivot
      • Tunneling
        • Chisel
        • sshuttle
        • Dnscat2
      • Double Pivots
        • RDP and SOCKS Tunneling with SocksOverRDP
    • Cracking Passwords
      • Password Cracking Prerequisites
      • Mutating Wordlists
        • Identifying & Building Rules
      • Password Managers
      • SSH Private Keys
      • NTLM Toolkit
      • NTLMv2
      • MS-Cachev2 (DCC2)
      • Password Protected Files
    • Windows Privilege Escalation
      • Initial Enumeration
      • Searching For Sensitive Files
      • Searching Logs & Event Viewer
      • Escalating Privilege
      • Leveraging Windows Services
        • Service Binary Hijacking
        • Service DLL Hijacking
        • Abusing Unquoted Paths
      • Scheduled Tasks
      • Enumerating Services & Tasks
      • Dumping Secrets
    • Linux Privilege Escalation
      • Initial Enumeration
      • Automated Enumeration
      • Searching For Sensitive Information
      • Insecure File Permissions
      • Insecure System Components
        • Abusing Setuid Binaries and Capabilities
        • Sudo Trickery
        • Kernel Vulnerabilities
      • Abusing Environment Variables
      • Escaping Jail
      • Wildcard Injection
    • Exploiting Microsoft Office
      • Phishing with Teams
      • Malicious Macros
      • Windows Library Files
    • Setting up Infrastructure
      • C2 Infrastructure
      • EvilGinx2 Phishing Infrastructure
    • Ex-filtrating Data
      • WebDAV
      • SMB
      • Converting files to Hex Strings
    • Phishing
      • OSCP Phishing Guide
    • Templates & Cheat Sheets
      • OSCP Cheat Sheet
      • Impacket Cheat Sheet
      • Useful Commands
      • Penetration Test Checklist
  • 🛡️Azure & M365
    • Information Gathering / Reconnaissance
      • Domain Enumeration
      • User Enumeration
      • AADInternals
    • Attacking Authentication
      • OWA Password Spraying
      • OAuth Abuse
    • Azure AD Killchain
    • Azure Lab Setup
    • Azure & M365 Checklist
  • 🥾Security Operation Center
    • Network Traffic Analysis
      • Tcpdump
      • Wireshark
    • Windows Event Logs
      • Sysmon
    • Event Tracing for Windows (ETW)
    • Microsoft 365 Defender
    • Splunk as SIEM
      • Using Splunk Applications
      • Search Processing Language (SPL) Commands
      • Hunting with Splunk
      • Intrusion Detection
    • Incident Response Process
    • MITRE ATT&CK Framework
      • Persistence
        • Registry Run Keys
    • Templates & Cheat Sheets
      • Interview Prep
  • 🔬Digital Forensics
    • Tools
  • 🔍Malware Analysis
    • Network Traffic Analysis
      • INetSim
    • Static Analysis
      • Signatures & Fingerprints
      • Pestudio
      • x64dbg
    • Dynamic Analysis
      • Noriben
    • Reverse Engineering / Code Analysis
      • IDA
      • x64dbg
      • Returning Source Code
        • .NET Binary
    • Creating Detection Rules
    • Tools
  • 🛠️Programming
    • MASM Assembly
    • Qt
      • Setting up Qt in CLion
    • Windows Development on MacOS
      • CLion Setup
    • Windows API
      • Deleting Files
      • Strings
      • wininet.h
      • Wrapping WinAPI Functions
      • code_seg
      • Locating WinAPI Functions - Tips
    • Visual Studio
      • Creating DLL's
      • Debug & Release Mode
    • Mingw
      • Windows Development
    • Position Independent Code (PIC)
      • Creating Shellcode
      • Debugging & Development Tips
      • Strings
      • Macros
      • PIC Checklist
  • 🏠Home Lab
    • Current Setup
Powered by GitBook
On this page
  • Introduction
  • Process Initialization and csrss.exe
  • PEB Structure
  • PEB_LDR_DATA
  • LIST_ENTRY
  • Access Local PEB (x64)
  • Getting a pointer to the PEB in C, for every architecture that NT was ported to
  • Get Local Base Address (NTDLL)
  • Access Remote PEB (x64)
  • Suspended Processes
  • Create Suspended Process
  • Additional
  • Iterate through LDR_DATA_TABLE_ENTY Linked List
  • LDR_DATA_TABLE_ENTRY
  1. Offensive Tool Development
  2. Windows Internals

Processes & PEB Structure

Processes & the Process Environment Block (PEB) is crucial to understand thoroughly. There's a lot to it, I'll try to cover most of it here.

Introduction

In short, a process is an instance of an executing program. It consists of various resources such as threads, handles, memory, and security contexts.

A process in Windows includes:

  • A Unique Process ID (PID)

  • Virtual Address Space (VAS): Every process is allocated it's own Virtual Address Space. This VAS is compartmentalized into PE sections (code, data, stack).

  • Executable Code (PE Image): The image of the file stored on disk.

  • Handle Table: Holds the handles that are opened.

  • Access Tokens (Security Context): Access tokens encapsulate information about the processes security privileges. Includes the user account and it's access rights.

  • Threads: Processes run atlest 1 or more threads. Threads enable concurrent execution.

Process Initialization and csrss.exe

Normally, a new process is created with CreateProcess (or one of it's variants). Here is the general flow:

  • NtCreateProcess is called.

    • The target exe file is opened and the .text section is called.

    • The initial thread and stack are created along with it's security context.

  • Windows subsystem initialization is performed

    • A message is sent to the Client/Server Runtime Subsystem (csrss.exe) to notify the creation of a new process.

    • csrss performs it's own initialization (such as allocating structures for new process)

  • The initial thread is resumed

  • Process initialization is performed in the security context of the new process.

The first thread that a process runs is LdrInitializeThunk. This is the initialization function before execution is transferred to the user-supplied thread entry point.

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;
  • BeingDebugged: Is the process in debugging mode.

PEB_LDR_DATA

The PEB_LDR_DATA structure contains informations about the loaded DLL's

typedef struct _PEB_LDR_DATA
{
     ULONG Length;
     UCHAR Initialized;
     PVOID SsHandle;
      InLoadOrderModuleList;
      InMemoryOrderModuleList;
      InInitializationOrderModuleList;
     PVOID EntryInProgress;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
  • InMemoryOrderModuleList: Doubly linked list of LIST_ENTRYs containing pointers to a loaded DLL.

  • Length: Length of the list.

LIST_ENTRY

typedef struct _LIST_ENTRY {
   struct _LIST_ENTRY *Flink;
   struct _LIST_ENTRY *Blink;
} LIST_ENTRY, *PLIST_ENTRY, *RESTRICTED_POINTER PRLIST_ENTRY;
  • Flink: points to the next entry in the list.

  • Blink: points to the previous entry in the list

  • IMPORTANT: Flink and Blink don't point to the start of the struct. They point to the InMemoryOrderModuleList member of the struct. To get the start ofLDR_DATA_TABLE_ENTRY from them, subtract InMemoryOrderModuleList offset (0x10). Or CONTAINING_RECORD macro.

  • Example: (->Flink - 0x10) Full example below.

Access Local PEB (x64)

#include <winternl.h>
// Get PEB structure
#ifdef _WIN64
	PPEB pPeb = (PPEB)__readgsqword(0x60);
#elif _WIN32
	PPEB pPeb = (PPEB)__readfsdword(0x30);
#endif // _WIN64

// HELPER FUNCTIONS
// Get of current process (call pLdr->DllBase to get base address)
PLDR_DATA_TABLE_ENTRY pLdr = (PLDR_DATA_TABLE_ENTRY)((PBYTE)(pPeb->Ldr->InMemoryOrderModuleList.Flink) - 0x10);
// pLdr->DllBase (Entrypoint to .exe)

Getting a pointer to the PEB in C, for every architecture that NT was ported to

inline PEB* NtCurrentPeb() {
#ifdef _M_X64
	return (PEB*)(__readgsqword(0x60));
#elif _M_IX86
	return (PEB*)(__readfsdword(0x30));
#elif _M_ARM
	return *(PEB**)(_MoveFromCoprocessor(15, 0, 13, 0, 2) + 0x30);
#elif _M_ARM64
	return *(PEB**)(__getReg(18) + 0x60); // TEB in x18
#elif _M_IA64
	return *(PEB**)((size_t)_rdteb() + 0x60); // TEB in r13
#elif _M_ALPHA
	return *(PEB**)((size_t)_rdteb() + 0x30); // TEB pointer returned from callpal 0xAB
#elif _M_MIPS
	return *(PEB**)((*(size_t*)(0x7ffff030)) + 0x30); // TEB pointer located at 0x7ffff000 (PCR in user-mode) + 0x30
#elif _M_PPC
	// winnt.h of the period uses __builtin_get_gpr13() or __gregister_get(13) depending on _MSC_VER
	return *(PEB**)(__gregister_get(13) + 0x30); // TEB in r13
#else
#error "This architecture is currently unsupported"
#endif
}

Get Local Base Address (NTDLL)

Flink actually returns the address of the end of the structure. Which is why we subtract 0x10 (size of entry) to get to the beginning.

PVOID FetchLocalNtdllAddress() {
    PPEB pPeb = (PPEB)__readgsqword(0x60);
        PLDR_DATA_TABLE_ENTRY pLdr = (PLDR_DATA_TABLE_ENTRY)((PBYTE)(pPeb->Ldr->InMemoryOrderModuleList.Flink->Flink) - 0x10);
    return pLdr->DllBase;
}

Access Remote PEB (x64)

To access a remote processes PEB structure & get the remote address of entry point we can use the following:

Suspended Processes

Suspended processes can be a nice trick when it comes to EDR since they can't load their hooks into a process that is suspended

Create Suspended Process

STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};

si->cb = sizeof(si);
// Just a POC: Update this with the dynamic filepath fetch for "svchost.exe"
if (CreateProcessW(L"C:\\Windows\\System32\\svchost.exe", 
 NULL,
 NULL, 
 NULL, 
 FALSE, 
 DEBUG_PROCESS, // Can use CREATE_SUSPENDED also both work fine. 
 NULL, 
 NULL, 
 si, 
 pi
) == 0) {
    wprintf(L"CreateProcessW Failed %d", GetLastError()) ;
    return FALSE;
};
// Modify suspended process

ResumeThread (pi.hThread);

Additional

Iterate through LDR_DATA_TABLE_ENTY Linked List

LDR_DATA_TABLE_ENTRY is an important data structure in the PEB. There's some important information here so strap in.

Iterate through linked list:

// Get PPEB
PPEB pPeb = (PPEB)__readgsqword(0x60);
PPEB_LDR_DATA          pLdr   = (PPEB_LDR_DATA)(pPeb->Ldr);

// Point to the first entry in linked list.
PLDR_DATA_TABLE_ENTRY   pDte   = (PLDR_DATA_TABLE_ENTRY)(pLdr->InMemoryOrderModuleList.Flink);

// Not null means there are more entrys in the list.
while (pDte) {
    if (pDte->FullDllName.Buffer == 0) {
        break;
    }
    wprintf(L"[+] %ls ", pDte->FullDllName.Buffer);
    wprintf(L"%p\n", pDte);
    
    // Dereference and advance
    pDte = *(PLDR_DATA_TABLE_ENTRY*)(pDte); 
}
  • The pDte = *(PLDR_DATA_TABLE_ENTRY*)(pDte); is a common method for advancing in linked lists in C.

  • In this linked list, the pointer to the next node is obtained by derefencing the current node. This is because the nodes embedded within a larger structure (PLDR_DATA_TABLE_ENTRY), and the linked list pointers are part of that structure.

To understand more how this works, let's examine the following code:.

pDte = *(PLDR_DATA_TABLE_ENTRY*)(pDte);

The above command derefernces the value stored at the address pointed to by pDte and then casting the result to a pointer to the PLDR_DATA_TABLE_ENTRY structure. This is simply how linked lists work. It looks like this:

LDR_DATA_TABLE_ENTRY

This is a node of the doubly linked list that contains loaded DLL information. Look above to enumerate.

This is the documented version of LDR_DATA_TABLE_ENTRY.

typedef struct _LDR_DATA_TABLE_ENTRY
{
      InLoadOrderLinks;
      InMemoryOrderLinks;
      InInitializationOrderLinks;
     PVOID DllBase;
     PVOID EntryPoint;
     ULONG SizeOfImage;
      FullDllName;
      BaseDllName;
     ULONG Flags;
     WORD LoadCount;
     WORD TlsIndex;
     union
     {
           HashLinks;
          struct
          {
               PVOID SectionPointer;
               ULONG CheckSum;
          };
     };
     union
     {
          ULONG TimeDateStamp;
          PVOID LoadedImports;
     };
     _ACTIVATION_CONTEXT * EntryPointActivationContext;
     PVOID PatchInformation;
      ForwarderLinks;
      ServiceTagLinks;
      StaticLinks;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
  • InInitializationOrderLinks.Flink: This is the base address of the DLL. It is Reserved2[0] in WinAPI. The name doesn't suggest it, but Microsoft likes to confuse people.

PreviousPE Base RelocationsNextThreads & TEB Structure

Last updated 7 months ago

Much of the PEB is undocumented. Use for more info.

Ldr: A pointer to a structure that contains information about the loaded DLL's

LIST_ENTRY contains pointers to (the loaded DLL).

☣️
http://undocumented.ntinternals.net/
PEB_LDR_DATA
LDR_DATA_TABLE_ENTRY