Monitoring and Auditing Port Forwarding

Monitoring and Auditing Port Forwarding

Visibility into port forwarding activity enables detection of unauthorized tunnels and abuse of legitimate access. Implement comprehensive monitoring to track forwarding usage and identify anomalies.

Configure detailed forwarding logs:

# Enhanced SSH logging for forwarding activity
# Add to sshd_config
LogLevel VERBOSE

# Parse logs for forwarding events
#!/bin/bash
# monitor-port-forwarding.sh

LOG_FILE="/var/log/auth.log"
ALERT_THRESHOLD=10

# Monitor for forwarding requests
tail -F "$LOG_FILE" | while read line; do
    # Detect local forwarding
    if echo "$line" | grep -q "Local forwarding listening on"; then
        USER=$(echo "$line" | grep -oP 'session opened for user \K\w+')
        PORT=$(echo "$line" | grep -oP 'listening on .+ port \K\d+')
        DEST=$(echo "$line" | grep -oP 'forwarding to \K[^ ]+')
        
        echo "[$(date)] Local forward: $USER -> localhost:$PORT -> $DEST"
        
        # Alert on high-numbered ports (potential backdoors)
        if [ "$PORT" -gt 10000 ]; then
            echo "ALERT: High port forwarding detected: $PORT" | \
                mail -s "SSH Forwarding Alert" [email protected]
        fi
    fi
    
    # Detect remote forwarding
    if echo "$line" | grep -q "Remote forward listening on"; then
        USER=$(echo "$line" | grep -oP 'session opened for user \K\w+')
        REMOTE_BIND=$(echo "$line" | grep -oP 'listening on \K[^ ]+')
        
        echo "[$(date)] Remote forward: $USER <- $REMOTE_BIND"
        
        # Alert on remote forwards (higher risk)
        echo "Remote forwarding detected: $USER binding $REMOTE_BIND" | \
            mail -s "SSH Remote Forward Alert" [email protected]
    fi
done

Implement netstat-based tunnel detection:

#!/bin/bash
# detect-ssh-tunnels.sh - Identify active SSH tunnels

# Find SSH processes with established connections
SSH_PIDS=$(pgrep -f "ssh.*-[LRD]")

for pid in $SSH_PIDS; do
    # Get process details
    PROCESS_INFO=$(ps -p "$pid" -o args= 2>/dev/null)
    
    if [ -n "$PROCESS_INFO" ]; then
        echo "SSH Process (PID $pid): $PROCESS_INFO"
        
        # Find associated network connections
        CONNECTIONS=$(lsof -p "$pid" -i -n | grep ESTABLISHED)
        
        if [ -n "$CONNECTIONS" ]; then
            echo "Active tunnels:"
            echo "$CONNECTIONS" | while read conn; do
                LOCAL=$(echo "$conn" | awk '{print $9}' | cut -d'>' -f1)
                REMOTE=$(echo "$conn" | awk '{print $9}' | cut -d'>' -f2)
                echo "  $LOCAL -> $REMOTE"
            done
        fi
        echo "---"
    fi
done

# Check for listening ports created by SSH
echo "SSH forwarding listeners:"
netstat -tlnp 2>/dev/null | grep ssh