Safe Testing Procedures

Safe Testing Procedures

Testing firewall changes in production requires careful procedures to avoid service disruption. Implement safe testing methods that verify changes without affecting users.

Staged Rollout Testing:

#!/bin/bash
# Safe firewall change testing script

BACKUP_FILE="/tmp/firewall-backup-$(date +%Y%m%d-%H%M%S).rules"
TEST_DURATION=300  # 5 minutes
ROLLBACK_SCRIPT="/tmp/firewall-rollback.sh"

# Create rollback script
create_rollback_script() {
    cat > "$ROLLBACK_SCRIPT" << EOF
#!/bin/bash
echo "Rolling back firewall changes..."
iptables-restore < $BACKUP_FILE
echo "Rollback completed."
EOF
    chmod +x "$ROLLBACK_SCRIPT"
}

# Backup current rules
echo "Backing up current firewall rules..."
iptables-save > "$BACKUP_FILE"
create_rollback_script

# Schedule automatic rollback
echo "Scheduling automatic rollback in $TEST_DURATION seconds..."
(sleep $TEST_DURATION && $ROLLBACK_SCRIPT) &
ROLLBACK_PID=$!

echo "Applying test rules..."
# Apply your test rules here

echo "Test rules applied. Testing for $TEST_DURATION seconds."
echo "To cancel rollback and keep changes, run: kill $ROLLBACK_PID"
echo "To rollback immediately, run: $ROLLBACK_SCRIPT"

# Monitor during test
echo -e "\nMonitoring connections..."
watch -n 1 'netstat -an | grep -c ESTABLISHED; echo "---"; iptables -L -n -v | grep DROP | head -5'

Canary Testing: Test changes on a subset of traffic:

# Canary firewall testing
class CanaryFirewallTester:
    def __init__(self, canary_percentage=10):
        self.canary_percentage = canary_percentage
        
    def apply_canary_rules(self):
        """Apply new rules to subset of traffic"""
        
        # Create ipset for canary IPs
        commands = [
            "ipset create canary_ips hash:ip",
            "ipset create production_ips hash:ip"
        ]
        
        # Add marking rules
        commands.extend([
            # Mark canary traffic
            "iptables -t mangle -A PREROUTING -m set --match-set canary_ips src -j MARK --set-mark 100",
            
            # Apply test rules to marked traffic
            "iptables -A INPUT -m mark --mark 100 -j CANARY_CHAIN",
            
            # Normal rules for other traffic
            "iptables -A INPUT -m mark ! --mark 100 -j PRODUCTION_CHAIN"
        ])
        
        for cmd in commands:
            subprocess.run(cmd.split())
    
    def add_to_canary(self, ip):
        """Add IP to canary test group"""
        subprocess.run(["ipset", "add", "canary_ips", ip])
    
    def monitor_canary_impact(self):
        """Monitor metrics for canary vs production"""
        
        metrics = {
            'canary': {'connections': 0, 'drops': 0},
            'production': {'connections': 0, 'drops': 0}
        }
        
        # Collect metrics
        # ... implementation ...
        
        return metrics