#!/bin/bash
#
# capture_and_analyze.sh - Capture and analyze covert channel traffic
#
# Usage: sudo ./capture_and_analyze.sh [capture|analyze|live]
#

INTERFACE="docker0"
PCAP_FILE="covert_channel_$(date +%Y%m%d_%H%M%S).pcap"
SYNC_PORT=31337

case "$1" in
    capture)
        echo "╔══════════════════════════════════════════════════════════╗"
        echo "║  Capturing Covert Channel Traffic                        ║"
        echo "╚══════════════════════════════════════════════════════════╝"
        echo
        echo "Interface: $INTERFACE"
        echo "Output: $PCAP_FILE"
        echo "Filter: tcp port $SYNC_PORT"
        echo
        echo "Press Ctrl+C to stop capture"
        echo
        
        tcpdump -i $INTERFACE -w $PCAP_FILE \
            "tcp port $SYNC_PORT or (ip6 and tcp)"
        
        echo
        echo "Capture saved to: $PCAP_FILE"
        echo "Run: $0 analyze $PCAP_FILE"
        ;;
        
    analyze)
        PCAP="${2:-covert_channel.pcap}"
        
        if [ ! -f "$PCAP" ]; then
            echo "Error: File not found: $PCAP"
            exit 1
        fi
        
        echo "╔══════════════════════════════════════════════════════════╗"
        echo "║  Analyzing Covert Channel Traffic                        ║"
        echo "╚══════════════════════════════════════════════════════════╝"
        echo
        echo "File: $PCAP"
        echo
        
        # Basic statistics
        echo "=== Packet Statistics ==="
        tshark -r "$PCAP" -q -z io,stat,1,"COUNT(frame)frame","AVG(frame.time_delta)frame"
        echo
        
        # IPv6 traffic
        echo "=== IPv6 SYN Packets (Sync Channel) ==="
        tshark -r "$PCAP" -Y "ipv6 && tcp.flags.syn==1 && tcp.flags.ack==0" \
            -T fields -e frame.time_relative -e ipv6.src -e ipv6.dst -e tcp.dstport \
            | head -20
        echo "..."
        echo
        
        # Packet rate over time
        echo "=== Packet Rate (packets/100ms) ==="
        tshark -r "$PCAP" -q -z io,stat,0.1,"COUNT(frame)frame" \
            | grep -E "^[|<]" | head -30
        echo
        
        # Unique source addresses
        echo "=== Unique IPv6 Source Addresses ==="
        tshark -r "$PCAP" -Y "ipv6 && tcp.flags.syn==1" \
            -T fields -e ipv6.src | sort -u | head -10
        echo
        
        # Connection attempts over time (for plotting)
        echo "=== Generating timing data for visualization ==="
        tshark -r "$PCAP" -Y "tcp.flags.syn==1" \
            -T fields -e frame.time_relative \
            > timing_data.txt
        
        # Generate gnuplot script
        cat > plot_timing.gnuplot << 'EOF'
set terminal png size 1600,600 enhanced font 'Arial,12'
set output 'covert_channel_timing.png'

set title 'CVE-2023-1206 Covert Sync Channel - Packet Timing'
set xlabel 'Time (seconds)'
set ylabel 'Packet Count (per 100ms bin)'

set style fill solid 0.5
set boxwidth 0.08

# Histogram of packet times
binwidth = 0.1
bin(x, width) = width * floor(x/width)

plot 'timing_data.txt' using (bin($1, binwidth)):(1.0) smooth frequency \
    with boxes lc rgb '#4040ff' title 'SYN Packets (Sync Channel)'
EOF
        
        if command -v gnuplot &> /dev/null; then
            gnuplot plot_timing.gnuplot
            echo "Visualization saved to: covert_channel_timing.png"
        else
            echo "Install gnuplot for visualization: apt install gnuplot"
        fi
        echo
        
        # Detect potential covert channel patterns
        echo "=== Pattern Detection ==="
        
        # Count packets per 100ms window
        WINDOWS=$(tshark -r "$PCAP" -Y "tcp.flags.syn==1" \
            -T fields -e frame.time_relative \
            | awk '{printf "%.1f\n", $1}' | sort | uniq -c | sort -k2 -n)
        
        HIGH_COUNT=$(echo "$WINDOWS" | awk '$1 > 50 {count++} END {print count+0}')
        LOW_COUNT=$(echo "$WINDOWS" | awk '$1 < 10 {count++} END {print count+0}')
        
        echo "High-activity windows (>50 pkts): $HIGH_COUNT"
        echo "Low-activity windows (<10 pkts): $LOW_COUNT"
        
        if [ "$HIGH_COUNT" -gt 5 ] && [ "$LOW_COUNT" -gt 5 ]; then
            echo
            echo "⚠️  POTENTIAL COVERT CHANNEL DETECTED!"
            echo "    Alternating high/low packet rate pattern observed."
            echo "    This matches CVE-2023-1206 sync channel signature."
        fi
        ;;
        
    live)
        echo "╔══════════════════════════════════════════════════════════╗"
        echo "║  Live Traffic Monitor                                    ║"
        echo "╚══════════════════════════════════════════════════════════╝"
        echo
        echo "Monitoring for covert channel patterns..."
        echo "Press Ctrl+C to stop"
        echo
        
        # Live packet rate display
        tshark -i $INTERFACE -f "tcp port $SYNC_PORT" \
            -q -z io,stat,1,"COUNT(frame)frame" 2>/dev/null &
        TSHARK_PID=$!
        
        # Also show live packets
        tcpdump -i $INTERFACE -n -l "tcp port $SYNC_PORT and tcp[tcpflags] & tcp-syn != 0" 2>/dev/null | \
        while read line; do
            echo "$line"
        done
        
        kill $TSHARK_PID 2>/dev/null
        ;;
        
    *)
        echo "Usage: $0 [capture|analyze|live]"
        echo
        echo "Commands:"
        echo "  capture           Start packet capture"
        echo "  analyze [file]    Analyze pcap file"
        echo "  live              Live traffic monitor"
        echo
        echo "Examples:"
        echo "  sudo $0 capture"
        echo "  sudo $0 analyze covert_channel.pcap"
        echo "  sudo $0 live"
        ;;
esac
