Port Scanning Evasion

Understanding Port Scanning Evasion - Stealth Reconnaissance Techniques

What is Port Scanning Evasion?

Simple Definition: Port scanning evasion uses advanced techniques to discover open ports and services on target systems while avoiding detection by firewalls, intrusion detection systems, and network monitoring tools.

Technical Definition: Port scanning evasion employs various TCP and UDP manipulation techniques including fragmentation, timing delays, source spoofing, and protocol-specific methods to conduct network reconnaissance while circumventing security controls designed to detect and block scanning activities.

Why Port Scanning Evasion Works

Port scanning evasion succeeds by exploiting limitations in security monitoring and detection systems:

  • Signature-Based Detection: Simple pattern matching fails with modified scan techniques
  • Resource Limitations: Monitoring systems can’t analyze all traffic at line speed
  • Protocol Complexity: Advanced TCP/UDP features create evasion opportunities
  • Timing Windows: Slow scans fall below detection thresholds

Attack Process Breakdown

Normal Port Scanning

  1. Target Identification: Select IP addresses and port ranges for scanning
  2. Probe Generation: Send TCP SYN or UDP packets to target ports
  3. Response Analysis: Interpret responses to determine port states
  4. Service Enumeration: Identify services running on open ports
  5. Result Compilation: Document discovered attack surface

Evasive Scanning Process

  1. Detection Analysis: Understand target security monitoring capabilities
  2. Evasion Selection: Choose appropriate stealth techniques for environment
  3. Stealthy Probing: Use modified packets and timing to avoid signatures
  4. Response Correlation: Piece together results from distributed probes
  5. Covert Enumeration: Gather service information without triggering alerts

Real-World Impact

Reconnaissance Without Detection: Map network infrastructure while remaining undetected

Security Control Assessment: Test effectiveness of monitoring and detection systems

Attack Surface Discovery: Identify vulnerable services for subsequent exploitation

Network Topology Mapping: Understand target network architecture and defenses

Long-Term Persistence: Maintain ongoing reconnaissance without raising suspicion

Technical Concepts

TCP Scanning Evasion

SYN Scanning Variations: Modified SYN packets with unusual flags or options FIN Scanning: Use FIN packets to probe closed ports NULL Scanning: Send packets with no TCP flags set Xmas Scanning: Set FIN, PSH, and URG flags simultaneously

Timing-Based Evasion

Slow Scanning: Spread probes over extended time periods Random Intervals: Use unpredictable timing between probes Burst Limiting: Restrict number of simultaneous probes Adaptive Timing: Adjust speed based on target responsiveness

Fragmentation Techniques

IP Fragmentation: Split scan packets across multiple fragments Overlapping Fragments: Create confusing fragment patterns Tiny Fragments: Use minimum fragment sizes to evade inspection Fragment Ordering: Send fragments out of sequence

Source Manipulation

IP Spoofing: Use different source addresses for each probe Decoy Scanning: Hide real scans among decoy traffic Zombie Scanning: Use compromised hosts for indirect scanning Reflection Scanning: Bounce scans off third-party systems

Technical Implementation

Prerequisites

Network Requirements:

  • Understanding of target network security architecture
  • Knowledge of monitoring systems and their capabilities
  • Access to multiple source IP addresses (for advanced techniques)

Essential Tools:

  • Nmap: Advanced scanning with evasion options
  • Masscan: High-speed scanning with customization
  • Hping3: Custom packet crafting for evasion
  • Scapy: Advanced packet manipulation

Essential Command Sequence

Step 1: Baseline Detection Assessment

# Test normal scanning detection
nmap -sS -p 1-1000 192.168.1.100
# Standard SYN scan
# Likely to trigger most IDS systems
# Establishes baseline for evasion comparison

# Monitor for detection alerts
# Check target logs or SIEM systems
# Understand what scanning patterns trigger alerts
# Use this knowledge to craft evasive techniques

# Test scan response timing
time nmap -sS -p 80 192.168.1.100
# Measure normal scan timing
# Helps establish timing baselines for slow scans
# Identifies potential rate limiting

Purpose: Understand how target systems detect and respond to normal scanning activities.

Step 2: Timing-Based Evasion

# Extremely slow scanning to avoid rate-based detection
nmap -sS -T0 -p 1-1000 192.168.1.100
# -T0: Paranoid timing (5-minute delays between probes)
# Spreads scan over hours to avoid detection
# Very slow but highly stealthy

# Custom timing control
nmap -sS --max-rate 1 -p 1-1000 192.168.1.100
# --max-rate 1: Maximum 1 packet per second
# Precise control over scan speed
# Balances stealth with reasonable completion time

# Random timing intervals
nmap -sS --scan-delay 30s --max-scan-delay 60s -p 1-100 192.168.1.100
# Variable delays between 30-60 seconds
# Random patterns harder to detect
# Mimics irregular network activity

Step 3: Fragmentation Evasion

# IP fragmentation scanning
nmap -sS -f -p 1-1000 192.168.1.100
# -f: Fragment packets (8-byte fragments)
# Splits scan packets to evade inspection
# Many IDS systems don't reassemble fragments

# Tiny fragmentation
nmap -sS -ff -p 1-1000 192.168.1.100
# -ff: Use 16-byte fragments
# Even smaller fragments for maximum evasion
# More likely to bypass inspection systems

# Custom fragmentation with hping3
hping3 -S -p 80 -f --frag 8 192.168.1.100
# Custom fragment size and offset
# Manual control over fragmentation patterns
# Can create overlapping or malformed fragments

Step 4: Source Address Manipulation

# Decoy scanning
nmap -sS -D 192.168.1.10,192.168.1.20,ME,192.168.1.30 -p 80 192.168.1.100
# -D: Use decoy addresses
# ME: Include real IP among decoys
# Hides real scan among decoy traffic
# Target sees scans from multiple sources

# Random decoy generation
nmap -sS -D RND:10 -p 1-100 192.168.1.100
# RND:10: Generate 10 random decoy addresses
# Automatic decoy IP generation
# Reduces manual configuration effort

# Source port manipulation
nmap -sS --source-port 53 -p 1-1000 192.168.1.100
# Spoof source port as DNS (53)
# May bypass source port-based filtering
# Some firewalls allow DNS traffic unconditionally

Step 5: Advanced Scanning Techniques

FIN Scan for Firewall Bypass:

# FIN scan to bypass stateful firewalls
nmap -sF -p 1-1000 192.168.1.100
# -sF: FIN scan
# Sends FIN packets to probe ports
# May bypass SYN-flood protection

# NULL scan
nmap -sN -p 1-1000 192.168.1.100
# -sN: NULL scan (no flags set)
# Some systems respond differently to NULL packets
# Can identify firewall filtering behavior

# Xmas scan
nmap -sX -p 1-1000 192.168.1.100
# -sX: Sets FIN, PSH, URG flags
# Named for "lighting up like Christmas tree"
# Another firewall evasion technique

Custom Evasion with Scapy:

#!/usr/bin/env python3
from scapy.all import *
import random
import time

def stealth_port_scan(target_ip, port_list):
    """Custom stealth port scanning"""
    
    open_ports = []
    
    for port in port_list:
        # Random source port for each probe
        src_port = random.randint(1024, 65535)
        
        # Craft SYN packet with random options
        packet = IP(dst=target_ip)/\
                TCP(sport=src_port, dport=port, flags="S",
                    options=[('MSS', 1460), ('NOP', None), ('WScale', 7)])
        
        # Send packet and wait for response
        response = sr1(packet, timeout=2, verbose=0)
        
        if response and response.haslayer(TCP):
            if response[TCP].flags == 18:  # SYN-ACK
                open_ports.append(port)
                # Send RST to close connection
                rst = IP(dst=target_ip)/\
                     TCP(sport=src_port, dport=port, flags="R",
                         seq=response[TCP].ack)
                send(rst, verbose=0)
        
        # Random delay between probes
        time.sleep(random.uniform(0.5, 2.0))
    
    return open_ports

# Example usage
ports = [22, 80, 443, 3389, 5432]
open_ports = stealth_port_scan("192.168.1.100", ports)
print(f"Open ports: {open_ports}")

Step 6: Idle Scan (Zombie Scanning)

# Identify potential zombie hosts
nmap -O --script ipidseq 192.168.1.0/24
# Find hosts with predictable IP ID sequences
# Zombie hosts should have incremental IP IDs
# Avoid busy hosts (unpredictable sequences)

# Execute idle scan through zombie
nmap -sI 192.168.1.50 -p 1-1000 192.168.1.100
# -sI: Idle scan using zombie host
# 192.168.1.50: Zombie host with predictable IP IDs
# Scan appears to come from zombie, not attacker
# Extremely stealthy but requires suitable zombie

Attack Variations

Protocol-Specific Evasion

# UDP scanning with custom payloads
nmap -sU --data-string "DNS query simulation" -p 53 192.168.1.100
# Custom UDP payload for specific services
# May trigger service-specific responses
# Helps differentiate open vs filtered ports

# SCTP scanning for alternative protocols
nmap -sY -p 1-1000 192.168.1.100
# -sY: SCTP INIT scan
# Tests different protocol stack
# May bypass TCP-focused monitoring

Firewall-Specific Bypasses

# ACK scanning for firewall mapping
nmap -sA -p 1-1000 192.168.1.100
# -sA: ACK scan
# Identifies filtered vs unfiltered ports
# Maps firewall rule sets

# Window scanning for detailed firewall analysis
nmap -sW -p 1-1000 192.168.1.100
# -sW: Window scan
# Analyzes TCP window field responses
# Can identify specific firewall behaviors

Multi-Stage Evasion

# Combine multiple evasion techniques
nmap -sS -f -T1 -D RND:5 --source-port 53 --data-length 25 -p 1-100 192.168.1.100
# -f: Fragmentation
# -T1: Slow timing
# -D RND:5: Random decoys
# --source-port 53: DNS source port
# --data-length 25: Custom payload size
# Layered evasion approach

Common Issues and Solutions

Problem: Evasive scans taking too long to complete

  • Solution: Balance stealth with efficiency, use targeted port lists, parallelize different techniques

Problem: Fragmented packets being dropped

  • Solution: Test different fragment sizes, verify path MTU, use alternative evasion methods

Problem: Decoy scanning detected as coordinated attack

  • Solution: Use more realistic decoy addresses, vary timing between decoys, limit decoy count

Problem: Still triggering IDS alerts despite evasion

  • Solution: Analyze alert signatures, adjust techniques, combine with traffic analysis

Advanced Techniques

Covert Channel Scanning

#!/usr/bin/env python3
from scapy.all import *

def covert_channel_scan(target_ip, ports):
    """Use ICMP as covert channel for port information"""
    
    for port in ports:
        # Embed port number in ICMP payload
        payload = f"PORT:{port}".encode()
        icmp_packet = IP(dst=target_ip)/ICMP()/payload
        
        # Send covert probe
        send(icmp_packet)
        
        # Actual port probe (very delayed)
        time.sleep(30)
        tcp_packet = IP(dst=target_ip)/TCP(dport=port, flags="S")
        response = sr1(tcp_packet, timeout=1, verbose=0)
        
        # Process response covertly
        if response:
            # Signal result through DNS query or other covert method
            pass

Adaptive Scanning

# Adaptive timing based on target responses
#!/bin/bash
TARGET="192.168.1.100"
DELAY=1

for port in {1..1000}; do
    # Attempt scan
    nmap -sS -p $port $TARGET >/dev/null 2>&1
    
    # Check for RST packets (possible rate limiting)
    if tcpdump -c 1 -i eth0 "tcp[tcpflags] & tcp-rst != 0" 2>/dev/null; then
        # Increase delay if rate limiting detected
        DELAY=$((DELAY * 2))
        echo "Rate limiting detected, increasing delay to $DELAY"
    fi
    
    sleep $DELAY
done

Distributed Scanning

# Coordinate scanning from multiple sources
# Use different geographic locations
# Spread scan signatures across time and space
# Harder to correlate as single attack

# Example: Coordinate with remote systems
ssh user@scanner1.example.com "nmap -sS -p 1-333 192.168.1.100" &
ssh user@scanner2.example.com "nmap -sS -p 334-666 192.168.1.100" &
ssh user@scanner3.example.com "nmap -sS -p 667-1000 192.168.1.100" &

Detection and Prevention

Detection Indicators

  • Unusual packet timing patterns
  • Fragmented packets to non-standard services
  • Multiple source addresses scanning same targets
  • Scans using uncommon TCP flags or options
  • Correlation of scanning activity across time

Prevention Measures

Network Configuration:

# Rate limiting for scan detection
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

Monitoring Enhancement:

  • Deploy stateful packet inspection
  • Implement fragment reassembly in monitoring
  • Use behavioral analysis for scan detection
  • Correlate events across time and sources

Active Defense:

  • Deploy scan detection honeypots
  • Implement adaptive rate limiting
  • Use deceptive responses to mislead scanners
  • Block known scanner IP addresses

Professional Context

Legitimate Use Cases

  • Security Assessment: Testing detection capabilities of security systems
  • Network Mapping: Understanding network topology without triggering alerts
  • Compliance Testing: Verifying monitoring system effectiveness
  • Red Team Operations: Simulating advanced persistent threat reconnaissance

Legal and Ethical Requirements

Authorization: Even stealthy scanning requires explicit written permission

Scope Definition: Clearly identify which systems and networks are in-scope for testing

Detection Testing: Document whether scans should be detected or remain covert

Impact Assessment: Consider potential for triggering automated security responses


Port scanning evasion techniques demonstrate the ongoing arms race between attackers and defenders, highlighting the importance of comprehensive monitoring and the limitations of signature-based detection systems.