Mit dem Sicherheits Scanner lassen sich auf deinem lokalen Rechner, öffentlich erreichbare Websites auf typische Sicherheitsprobleme und potenzielle Fehlkonfigurationen überprüfen. Das eigenständige PHP-CLI-Script führt einen strukturierten Sicherheitscheck durch und untersucht verschiedene Bereiche der Website, ohne aufwendige externe Tools oder zusätzliche Frameworks vorauszusetzen.
Im Mittelpunkt stehen häufige Schwachstellen, die bei der Absicherung von Websites leicht übersehen werden. Dazu gehören fehlende HTTP-Security-Header, problematische Cookie-Einstellungen, TLS-Zertifikate mit ablaufender Gültigkeit, öffentlich erreichbare Konfigurations- und Backup-Dateien sowie mögliche Hinweise auf XSS- und SQL-Injection-Probleme.
Funktionen im Überblick
- Security Header: Prüfung wichtiger HTTP-Sicherheitsheader wie HSTS, Content-Security-Policy, X-Frame-Options und Referrer-Policy.
- TLS-Zertifikat: Kontrolle der Zertifikatsgültigkeit, des Ausstellers und möglicher Ablaufprobleme.
- robots.txt und Sitemap: Prüfung der Erreichbarkeit sowie Hinweise auf möglicherweise sensible Pfadangaben.
- Pfad-Enumeration: Überprüfung typischer Speicherorte auf öffentlich erreichbare Konfigurationsdateien, Backups, Administrationsbereiche und weitere Endpunkte.
- XSS-Prüfung: Kontrollierte Tests auf reflektierte Cross-Site-Scripting-Muster.
- SQL Injection Prüfung: Suche nach typischen Datenbankfehlermeldungen und auffälligen Serverreaktionen.
- HTTP-Methoden: Kontrolle der Methoden OPTIONS, TRACE, PUT und DELETE.
- Directory Listing: Prüfung ausgewählter Verzeichnisse auf öffentlich sichtbare Dateilisten.
Drei Prüfmodi
Das Script bietet drei unterschiedliche Modi:
- Passive: Prüfung der grundlegenden Sicherheitsinformationen, Header und TLS-Konfiguration.
- Standard: Erweiterter Check mit Pfad-Enumeration und zusätzlichen Sicherheitstests.
- Full: Für die vollständige Prüfung vorgesehen, einschließlich aller aktivierten Testmodule.
Flexible Report-Ausgabe
Die Ergebnisse können direkt in der Konsole ausgegeben oder als strukturierter JSON- beziehungsweise HTML-Report gespeichert werden. Über verschiedene Kommandozeilenparameter lassen sich unter anderem das Request-Limit, die Wartezeit zwischen Anfragen, zusätzliche Prüfpfade und die zu untersuchenden URL-Parameter konfigurieren.
Voraussetzungen und Verwendung
Benötigt werden PHP CLI mit aktivierten cURL- und OpenSSL-Erweiterungen sowie eine erreichbare Zielwebsite.
Beispielaufruf:
php name.php --target=https://www.deine-domain.de
Erweiterter Aufruf mit HTML- und JSON-Report:
php name.php --target=https://www.deine-domain.de --mode=full --delay=300 --report=both --out=report
Optionen:
–target Ziel-URL inkl. Scheme (Pflicht)
–mode passive | standard (default) | full
–delay Wartezeit zwischen Requests in ms (default: 250)
–max-requests hartes Request-Budget (default: 220)
–params Komma-Sep. Parameter für XSS/SQLi-Probes, default: q,search,id,s,page,category,tag,view,url,redirect,next,return
–paths Zusätzliche Pfade zur Enumeration (komma-separiert)
–report console | json | html | both (default: console)
–out Ausgabepfad ohne Endung bei json/html (default: ./selftest-report)
Exit-Codes: 0 = keine Findings, 1 = Findings vorhanden, 2 = Fehler
Wichtiger Sicherheitshinweis: Das Script ist ausschließlich für eigene Websites oder Systeme mit ausdrücklicher Testfreigabe vorgesehen. Es verwendet überwiegend lesende GET-Anfragen und verzichtet auf Brute Force Angriffe sowie destruktive Payloads. Die HTTP-Methoden PUT und DELETE werden ebenfalls kontrolliert angefragt. Unser Sicherheits Scanner ist ein pragmatisches Prüfwerkzeug für eine erste Einschätzung der extern sichtbaren Angriffsfläche, ersetzt aber weder einen professionellen Penetrationstest noch eine manuelle Sicherheitsanalyse. Nutzung auf eigene Verantwortung.
Dieses Premium Tutorial ist exklusiv zum weiterlesen für unsere Newsletter Abonnenten!
<?php
declare(strict_types=1);
error_reporting(E_ALL);
// --------------------------------------------------------------------------
// Konfiguration & CLI
// --------------------------------------------------------------------------
$cfg = [
'target' => '',
'mode' => 'standard',
'delay' => 250,
'max_requests' => 220,
'params' => 'q,search,id,s,page,category,tag,view,url,redirect,next,return',
'extra_paths' => '',
'report' => 'console',
'out' => './selftest-report',
];
foreach ($argv as $arg) {
if (preg_match('/^--([a-z-]+)=(.*)$/', $arg, $m)) {
$key = str_replace('-', '_', $m[1]);
if (array_key_exists($key, $cfg)) {
$cfg[$key] = $m[2];
}
}
}
if ($cfg['target'] === '' || !preg_match('#^https?://#', $cfg['target'])) {
fwrite(STDERR, "Fehler: --target=https://deine-domain.tld angeben.\n\n");
fwrite(STDERR, "NUR auf eigenen Seiten oder mit ausdrücklicher Freigabe testen!\n");
exit(2);
}
$cfg['target'] = rtrim($cfg['target'], '/');
$cfg['delay'] = max(0, (int)$cfg['delay']);
$cfg['max_requests'] = max(10, (int)$cfg['max_requests']);
$base = parse_url($cfg['target']);
$origin = $base['scheme'] . '://' . $base['host'] . (isset($base['port']) ? ':' . $base['port'] : '');
// --------------------------------------------------------------------------
// Farben & Hilfsfunktionen
// --------------------------------------------------------------------------
$isTTY = function_exists('posix_isatty') && @posix_isatty(STDOUT);
$C = function (string $code) use ($isTTY): string {
return $isTTY ? "\033[" . $code . 'm' : '';
};
$red = $C('31'); $green = $C('32'); $yellow = $C('33');
$blue = $C('34'); $cyan = $C('36'); $bold = $C('1'); $reset = $C('0');
$requestCount = 0;
$findings = [];
function banner(string $t): void {
global $bold, $blue, $reset;
echo "\n{$bold}{$blue}=== {$t} ==={$reset}\n";
}
function http_request(string $method, string $url, array $headers = [], ?string $body = null): array {
global $requestCount, $cfg, $red, $reset;
if ($requestCount >= $cfg['max_requests']) {
return ['error' => 'REQUEST_BUDGET_EXCEEDED', 'code' => 0, 'headers' => [], 'body' => ''];
}
$requestCount++;
if ($cfg['delay'] > 0) {
usleep($cfg['delay'] * 1000);
}
$ch = curl_init($url);
$default = [
'User-Agent: SiteSelfTest/1.0 (+authorized self-test)',
'Accept: text/html,application/json,*/*',
'Accept-Language: de-DE,de;q=0.9',
];
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_MAXREDIRS => 0,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_ENCODING => '',
CURLOPT_HTTPHEADER => array_merge($default, $headers),
CURLOPT_HEADERFUNCTION => function ($ch, string $hdr) {
$len = strlen($hdr);
$line = trim($hdr);
if ($line !== '' && strpos($line, ':') !== false) {
[$k, $v] = explode(':', $line, 2);
$GLOBALS['_last_headers'][strtolower(trim($k))][] = trim($v);
}
return $len;
},
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$GLOBALS['_last_headers'] = [];
$raw = curl_exec($ch);
$err = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($raw === false) {
return ['error' => $err, 'code' => 0, 'headers' => [], 'body' => ''];
}
return [
'error' => null,
'code' => (int)$info['http_code'],
'headers' => $GLOBALS['_last_headers'],
'body' => (string)$raw,
'final_url' => $info['url'] ?? $url,
'primary_ip' => $info['primary_ip'] ?? '',
'time' => $info['total_time'] ?? 0,
];
}
function add_finding(string $severity, string $category, string $title, string $detail, string $evidence = ''): void {
global $findings;
$findings[] = [
'severity' => $severity, // critical | high | medium | low | info
'category' => $category,
'title' => $title,
'detail' => $detail,
'evidence' => substr($evidence, 0, 500),
];
}
function sev_color(string $sev): string {
global $red, $yellow, $green, $cyan, $reset;
return match ($sev) {
'critical' => $red, 'high' => $red,
'medium' => $yellow, 'low' => $cyan,
default => $green,
};
}
// --------------------------------------------------------------------------
// Modul 1: Security Header
// --------------------------------------------------------------------------
function check_headers(string $origin): void {
banner('Security Header');
$r = http_request('GET', $origin . '/');
if ($r['error']) { echo "Fehler: {$r['error']}\n"; return; }
$h = $r['headers'];
$get = fn(string $k): string => isset($h[$k]) ? implode('; ', $h[$k]) : '';
$checks = [
'strict-transport-security' => ['HSTS', 'medium'],
'content-security-policy' => ['Content-Security-Policy', 'high'],
'x-frame-options' => ['X-Frame-Options / frame-ancestors', 'medium'],
'x-content-type-options' => ['X-Content-Type-Options: nosniff', 'medium'],
'referrer-policy' => ['Referrer-Policy', 'low'],
'permissions-policy' => ['Permissions-Policy', 'low'],
'cross-origin-opener-policy'=> ['COOP', 'info'],
'cross-origin-resource-policy' => ['CORP', 'info'],
];
foreach ($checks as $header => [$label, $sev]) {
$val = $get($header);
$cspInMeta = false;
if ($header === 'content-security-policy' && $val === '') {
if (preg_match('/<meta[^>]+http-equiv=["\']Content-Security-Policy/i', $r['body'])) {
$cspInMeta = true; $val = '(im <meta>-Tag gesetzt)';
}
}
if ($val === '') {
add_finding($sev, 'header', $label . ' fehlt', "Der Header {$header} wird nicht gesendet.");
echo " [FEHLT] {$label}\n";
} else {
echo " [OK] {$label}: " . substr($val, 0, 80) . "\n";
if ($header === 'content-security-policy') {
if (str_contains($val, 'unsafe-inline') && !$cspInMeta) {
add_finding('medium', 'header', "CSP enthält 'unsafe-inline'", 'Inline-Skripte/Styles sind erlaubt — XSS-Schwächung der CSP.', $val);
}
if (!str_contains($val, 'default-src') && !$cspInMeta) {
add_finding('medium', 'header', 'CSP ohne default-src', 'Rückfallverhalten nicht definiert.', $val);
}
}
if ($header === 'strict-transport-security' && !str_contains($val, 'max-age')) {
add_finding('medium', 'header', 'HSTS ohne max-age', 'Wirkungslos ohne max-age.', $val);
}
}
}
$xpb = $get('x-powered-by');
if ($xpb !== '') {
add_finding('info', 'header', 'X-Powered-By vorhanden', 'Verbirgt Versionsdetails besser.', $xpb);
echo " [INFO] X-Powered-By: {$xpb}\n";
}
if (isset($h['server'])) {
$srv = implode('; ', $h['server']);
if (preg_match('/\d+\.\d+/', $srv)) {
add_finding('low', 'header', 'Server-Header mit Versionsnummer', 'Versionsangabe im Server-Header.', $srv);
}
}
// Cookie-Flags
if (isset($h['set-cookie'])) {
foreach ($h['set-cookie'] as $cookie) {
$name = strtok($cookie, '=');
$flags = [];
if (stripos($cookie, 'httponly') === false) $flags[] = 'kein HttpOnly';
if (stripos($cookie, 'secure') === false) $flags[] = 'kein Secure';
if (stripos($cookie, 'samesite') === false) $flags[] = 'kein SameSite';
if ($flags) {
add_finding('high', 'cookie', "Cookie {$name}: " . implode(', ', $flags), 'Session-Cookies ohne Schutzflags.', $cookie);
}
}
}
}
// --------------------------------------------------------------------------
// Modul 2: TLS-Zertifikat
// --------------------------------------------------------------------------
function check_tls(string $host, int $port = 443): void {
banner('TLS-Zertifikat');
$ctx = stream_context_create(['ssl' => ['capture_peer_cert' => true, 'verify_peer' => false, 'verify_peer_name' => false]]);
$client = @stream_socket_client("ssl://{$host}:{$port}", $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $ctx);
if (!$client) { echo " TLS-Handshake fehlgeschlagen: {$errstr}\n"; add_finding('high', 'tls', 'TLS-Handshake fehlgeschlagen', $errstr); return; }
$cert = stream_context_get_params($client)['options']['ssl']['peer_certificate'] ?? null;
fclose($client);
if (!$cert) { echo " Kein Zertifikat empfangen.\n"; return; }
$info = openssl_x509_parse($cert);
$validTo = $info['validTo_time_t'] ?? 0;
$days = (int)(($validTo - time()) / 86400);
$issuer = $info['issuer']['O'] ?? ($info['issuer']['CN'] ?? 'unbekannt');
echo " Aussteller: {$issuer}\n Gültig bis: " . date('Y-m-d', $validTo) . " (noch {$days} Tage)\n";
if ($days < 0) add_finding('critical', 'tls', 'Zertifikat abgelaufen', "Seit " . abs($days) . " Tagen abgelaufen.");
elseif ($days < 14) add_finding('high', 'tls', 'Zertifikat läuft bald ab', "Nur noch {$days} Tage gültig.");
if (in_array('SHA1', array_map('strtoupper', (array)($info['signatureTypeSN'] ?? [])), true)) {
add_finding('medium', 'tls', 'SHA-1-Signatur', 'Veraltete Signatur.');
}
}
// --------------------------------------------------------------------------
// Modul 3: robots.txt & Sitemap
// --------------------------------------------------------------------------
function check_robots(string $origin): void {
banner('robots.txt & Sitemap');
$r = http_request('GET', $origin . '/robots.txt');
if ($r['code'] === 200 && stripos($r['body'], 'user-agent') !== false) {
echo " robots.txt vorhanden (" . strlen($r['body']) . " Bytes)\n";
if (preg_match_all('#^Disallow:\s*(.+)$#mi', $r['body'], $m)) {
$paths = array_filter(array_map('trim', $m[1]));
echo " Disallow-Pfade (" . count($paths) . "): " . implode(', ', array_slice($paths, 0, 15)) . (count($paths) > 15 ? ' …' : '') . "\n";
foreach ($paths as $p) {
if (preg_match('#(admin|backend|intern|dev|staging|test|config|\.env|backup)#i', $p)) {
add_finding('info', 'info-disclosure', "robots.txt verrät sensiblen Pfad: {$p}", 'Kein echtes Loch, aber unnötige Information.');
}
}
}
} else {
echo " keine robots.txt (oder leer)\n";
}
$s = http_request('GET', $origin . '/sitemap.xml');
echo " sitemap.xml: HTTP " . $s['code'] . "\n";
}
// --------------------------------------------------------------------------
// Modul 4: Pfad-Enumeration
// --------------------------------------------------------------------------
function enumerate_paths(string $origin, string $extra): void {
banner('Pfad-Enumeration (sensitive Dateien & Endpunkte)');
$paths = [
'.env','.env.backup','.env.bak','.git/HEAD','.git/config','.svn/entries','.hg/store',
'config.php','config.php.bak','config.php~','config.yml','config.json','configuration.php',
'wp-config.php','wp-config.php.bak','settings.php','database.php','db.php','connect.php',
'phpinfo.php','info.php','i.php','test.php','debug.php','dev.php','status.php',
'backup.zip','backup.tar.gz','www.zip','site.zip','dump.sql','database.sql','db.sql',
'admin/','admin.php','administrator/','backend/','login/','login.php','dashboard/',
'wp-login.php','wp-admin/','xmlrpc.php','.well-known/security.txt','security.txt',
'server-status','nginx_status','metrics','health','api/','api/v1/','graphql',
'crossdomain.xml','composer.json','package.json','README.md','CHANGELOG.md','.htaccess',
'cgi-bin/','web.config','elmah.axd','.DS_Store','Thumbs.db',
];
foreach (array_filter(array_map('trim', explode(',', $extra))) as $p) {
$paths[] = ltrim($p, '/');
}
$paths = array_unique($paths);
$interesting = [];
foreach ($paths as $p) {
$r = http_request('GET', $origin . '/' . $p);
if ($r['error']) continue;
$code = $r['code'];
$len = strlen($r['body']);
if ($code === 200 && $len > 0) {
$interesting[] = [$p, $code, $len];
$sev = 'high';
if (preg_match('#\.(env|sql|bak|zip|gz|md|json|yml|HEAD|config)$#i', $p) || str_contains($p, 'wp-config')) $sev = 'critical';
add_finding($sev, 'path', "Zugänglich: /{$p}", "HTTP 200, {$len} Bytes — Inhalt prüfen!", substr($r['body'], 0, 300));
} elseif ($code === 301 || $code === 302) {
$loc = $r['headers']['location'][0] ?? '?';
echo " [{$code}] /{$p} → {$loc}\n";
} elseif ($code === 401 || $code === 403) {
echo " [{$code}] /{$p} (geschützt)\n";
} elseif ($code === 500) {
add_finding('medium', 'path', "Serverfehler auf /{$p}", 'HTTP 500 — existiert evtl., Fehler bei GET.');
}
}
if ($interesting) {
echo " {$red}ZUGÄNGLICH gefunden:{$reset}\n";
foreach ($interesting as [$p, $c, $l]) echo " /{$p} (HTTP {$c}, {$l} Bytes)\n";
} else {
echo " Nichts Zugängliches gefunden (" . count($paths) . " Pfade getestet).\n";
}
}
// --------------------------------------------------------------------------
// Modul 5: Reflected-XSS-Probes
// --------------------------------------------------------------------------
function xss_probes(string $origin, string $paramsCsv): void {
banner('Reflected-XSS-Probes');
$params = array_filter(array_map('trim', explode(',', $paramsCsv)));
$canary = 'x7sstest9';
$payloads = [
'<script>alert(' . $canary . ')</script>',
'\"><img src=x onerror=alert(' . $canary . ')>',
"'><svg onload=alert(" . $canary . ")>",
'<iframe src=javascript:alert(' . $canary . ')>',
$canary . '" onfocus=alert(' . $canary . ') autofocus="',
];
$hits = 0;
foreach ($params as $param) {
foreach ($payloads as $pl) {
$url = $origin . '/?' . urlencode($param) . '=' . urlencode($pl);
$r = http_request('GET', $url);
if ($r['error'] || $r['code'] === 0) continue;
if ($r['code'] >= 500) {
add_finding('medium', 'xss', "HTTP {$r['code']} bei ?{$param}=", 'Payload löst Serverfehler aus.');
continue;
}
$body = $r['body'];
if (stripos($body, $canary) === false) continue; // nicht reflektiert
// Rohes Tag vs. escaped?
$rawTags = ['<script>alert(' . $canary . ')', '<img src=x onerror=alert(' . $canary . ')>',
'<svg onload=alert(' . $canary . ')>', '<iframe src=javascript:alert(' . $canary . ')>'];
$raw = false;
foreach ($rawTags as $rt) {
if (stripos($body, $rt) !== false) { $raw = true; break; }
}
// HTML-Entities wären ein Zeichen von korrekter Kodierung
$encoded = (stripos($body, '<script>') !== false) || (stripos($body, '<') !== false);
if ($raw && !$encoded) {
add_finding('critical', 'xss', "Reflected XSS: ?{$param}=", 'Payload wird UNMASKIERT im HTML reflektiert.', $pl);
echo " {$red}[KRITISCH]{$reset} ?{$param}= → unmaskierte Reflexion von " . substr($pl, 0, 40) . "\n";
$hits++;
} elseif (!$encoded) {
add_finding('low', 'xss', "Teil-Reflexion: ?{$param}=", 'Canary reflektiert, aber Tags gefiltert — Kontext prüfen.', $pl);
}
break; // pro Param reicht ein Treffer
}
}
if ($hits === 0) echo " Keine unmaskierte Reflexion gefunden (" . count($params) . " Parameter × " . count($payloads) . " Payloads).\n";
}
// --------------------------------------------------------------------------
// Modul 6: SQLi-Error-Probes
// --------------------------------------------------------------------------
function sqli_probes(string $origin, string $paramsCsv): void {
banner('SQLi-Error-Probes');
$params = array_filter(array_map('trim', explode(',', $paramsCsv)));
$probes = ["'", "''", "' OR '1'='1", "\" OR \"1\"=\"1", "1' ORDER BY 1-- ", "1) UNION SELECT NULL-- "];
$dbSigs = [
'MySQL' => ['mysql_fetch', 'MySQL error', 'mysqli_', 'SQL syntax.*MySQL', 'Warning.*mysql'],
'MariaDB' => ['MariaDB server version'],
'PostgreSQL'=> ['pg_query', 'PostgreSQL.*ERROR', 'psql:', 'unterminated quoted string'],
'SQLite' => ['sqlite3?', 'SQLite/JDBCDriver', 'unrecognized token'],
'MSSQL' => ['Microsoft SQL Native Client', 'ODBC SQL Server Driver', 'Unclosed quotation mark'],
'Oracle' => ['ORA-\d{5}', 'Oracle error', 'quoted string not properly terminated'],
'PDO' => ['SQLSTATE\[', 'PDOException'],
'General' => ['SQL syntax', 'syntax error.*SQL', 'Database Error'],
];
$hits = 0;
foreach ($params as $param) {
foreach ($probes as $pl) {
$url = $origin . '/?' . urlencode($param) . '=' . urlencode($pl);
$r = http_request('GET', $url);
if ($r['error']) continue;
if ($r['code'] >= 500) {
add_finding('medium', 'sqli', "HTTP {$r['code']} bei ?{$param}={$pl}", 'Quote/Payload löst Serverfehler aus — Quotes erreichen evtl. SQL-Kontext.');
$hits++; break;
}
foreach ($dbSigs as $db => $sigs) {
foreach ($sigs as $sig) {
if (@preg_match('/' . $sig . '/i', $r['body'])) {
add_finding('critical', 'sqli', "SQL-Fehler freigegeben ({$db}): ?{$param}=", "Datenbank-Fehlermeldung im HTML: /{$sig}/", substr($r['body'], 0, 300));
echo " {$red}[KRITISCH]{$reset} {$db}-Fehlermeldung reflektiert bei ?{$param}={$pl}\n";
$hits++;
break 3;
}
}
}
}
}
if ($hits === 0) echo " Keine DB-Fehlersignaturen gefunden.\n";
}
// --------------------------------------------------------------------------
// Modul 7: HTTP-Methoden
// --------------------------------------------------------------------------
function method_checks(string $origin): void {
banner('HTTP-Methoden');
foreach (['OPTIONS', 'TRACE', 'PUT', 'DELETE'] as $m) {
$r = http_request($m, $origin . '/', [], $m === 'PUT' || $m === 'DELETE' ? 'selftest=1' : null);
$code = $r['code'] ?: 'ERR';
$allow = isset($r['headers']['allow']) ? ' (Allow: ' . implode(',', $r['headers']['allow']) . ')' : '';
echo " {$m}: HTTP {$code}{$allow}\n";
if ($m === 'TRACE' && $r['code'] === 200 && stripos($r['body'], 'TRACE') !== false) {
add_finding('medium', 'methods', 'TRACE aktiviert', 'XST-Angriffe möglich.');
}
if (($m === 'PUT' || $m === 'DELETE') && $r['code'] < 300) {
add_finding('critical', 'methods', "{$m} erlaubt", 'HTTP ' . $r['code'] . ' — Datei-Upload/Delete prüfen!');
}
}
}
// --------------------------------------------------------------------------
// Modul 8: Directory Listing & Zertifikats-Transparenz (Bonus)
// --------------------------------------------------------------------------
function dir_listing_check(string $origin): void {
banner('Directory Listing');
foreach (['/images/', '/uploads/', '/files/', '/assets/', '/wp-content/uploads/'] as $d) {
$r = http_request('GET', $origin . $d);
if ($r['code'] === 200 && preg_match('/Index of|<title>Index of/i', $r['body'])) {
add_finding('medium', 'dirlisting', "Directory Listing auf {$d}", 'Verzeichnisinhalt öffentlich sichtbar.');
echo " {$d} → LISTING AKTIV\n";
}
}
echo " Geprüft, keine Listings gefunden.\n";
}
// --------------------------------------------------------------------------
// Report-Generierung
// --------------------------------------------------------------------------
function write_reports(string $mode): void {
global $findings, $cfg, $origin, $requestCount;
if ($mode === 'console') return;
$order = ['critical' => 0, 'high' => 1, 'medium' => 2, 'low' => 3, 'info' => 4];
usort($findings, fn($a, $b) => $order[$a['severity']] <=> $order[$b['severity']]);
if ($mode === 'json' || $mode === 'both') {
file_put_contents($cfg['out'] . '.json', json_encode([
'target' => $cfg['target'], 'generated' => date('c'), 'requests' => $requestCount,
'findings' => $findings,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
echo "\nJSON-Report: {$cfg['out']}.json\n";
}
if ($mode === 'html' || $mode === 'both') {
$rows = '';
foreach ($findings as $f) {
$esc = fn(string $s): string => htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
$color = ['critical' => '#c0392b', 'high' => '#e74c3c', 'medium' => '#e67e22', 'low' => '#2980b9', 'info' => '#27ae60'][$f['severity']];
$rows .= "<tr><td><span style='background:{$color};color:#fff;padding:2px 8px;border-radius:3px'>{$f['severity']}</span></td>"
. "<td>{$esc($f['category'])}</td><td>{$esc($f['title'])}</td><td>{$esc($f['detail'])}</td>"
. "<td><code>{$esc($f['evidence'])}</code></td></tr>";
}
$html = "<!DOCTYPE html><html lang='de'><head><meta charset='utf-8'><title>Selftest-Report {$origin}</title>"
. "<style>body{font-family:sans-serif;margin:2rem}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccc;padding:6px;vertical-align:top}th{background:#f4f4f4}</style></head><body>"
. "<h1>Sicherheits-Selftest: {$origin}</h1><p>Erstellt: " . date('c') . " · Requests: {$requestCount} · Findings: " . count($findings) . "</p>"
. "<table><tr><th>Schwere</th><th>Kategorie</th><th>Titel</th><th>Detail</th><th>Beweis</th></tr>{$rows}</table></body></html>";
file_put_contents($cfg['out'] . '.html', $html);
echo "HTML-Report: {$cfg['out']}.html\n";
}
}
// --------------------------------------------------------------------------
// Main
// --------------------------------------------------------------------------
echo "{$bold}Site Self-Test 1.0{$reset} — Ziel: {$cfg['target']} (Modus: {$cfg['mode']})\n";
echo "{$yellow}Hinweis: Nur auf eigenen/freigegebenen Systemen einsetzen. Nur lesende Requests.{$reset}\n";
$host = $base['host'];
check_headers($origin);
check_tls($host);
check_robots($origin);
if ($cfg['mode'] !== 'passive') {
enumerate_paths($origin, $cfg['extra_paths']);
xss_probes($origin, $cfg['params']);
sqli_probes($origin, $cfg['params']);
method_checks($origin);
dir_listing_check($origin);
}
// Konsolen-Zusammenfassung
banner('Zusammenfassung');
$counts = array_count_values(array_column($findings, 'severity'));
foreach (['critical', 'high', 'medium', 'low', 'info'] as $sev) {
if (!empty($counts[$sev])) {
echo ' ' . sev_color($sev) . str_pad(strtoupper($sev), 9) . $reset . ": {$counts[$sev]}\n";
}
}
echo " Requests gesamt: {$requestCount}\n";
if ($findings) {
echo "\n{$bold}Findings (sortiert):{$reset}\n";
$order = ['critical' => 0, 'high' => 1, 'medium' => 2, 'low' => 3, 'info' => 4];
usort($findings, fn($a, $b) => $order[$a['severity']] <=> $order[$b['severity']]);
$i = 1;
foreach ($findings as $f) {
echo " " . sev_color($f['severity']) . "[{$f['severity']}]{$reset} {$f['category']}: {$f['title']}\n";
if ($f['detail'] !== '') echo " → {$f['detail']}\n";
$i++;
}
} else {
echo "\n{$green}Keine Findings — saubere Oberfläche (soweit von außen testbar).{$reset}\n";
}
write_reports($cfg['report']);
exit($findings ? 1 : 0);