Upload via GUI (94 Dateien)
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
// Eingebaute Dateianalyse des Virenscans: braucht nichts auf dem Server, führt nie etwas aus und liest nur die ersten Megabytes.
|
||||
// Sie erkennt gefährliche Dateitypen und Tricks, keine neuen Viren (dafür gibt es ClamAV und die Hash-Abfrage).
|
||||
|
||||
/** Dateiendungen, die Programme oder Skripte starten können. */
|
||||
const VIRENSCAN_BAD_EXT = ['exe', 'scr', 'com', 'pif', 'bat', 'cmd', 'vbs', 'vbe', 'js', 'jse', 'wsf', 'wsh', 'ps1', 'psm1', 'msi', 'msp', 'hta', 'jar', 'cpl', 'dll', 'sys', 'lnk', 'reg', 'inf', 'sh', 'apk', 'iso', 'img', 'vhd', 'vhdx', 'gadget', 'application', 'appx', 'msix', 'settingcontent-ms', 'chm'];
|
||||
/** Office-Dateien mit eingebauten Makros. */
|
||||
const VIRENSCAN_MACRO_EXT = ['docm', 'xlsm', 'pptm', 'dotm', 'xltm', 'potm', 'ppam', 'ppsm', 'sldm', 'xlam'];
|
||||
/** Archive, die sich nicht öffnen lassen. */
|
||||
const VIRENSCAN_OTHER_ARCHIVES = ['rar', '7z', 'ace', 'arj', 'cab', 'z', 'zipx'];
|
||||
|
||||
function virenscan_file_ext(string $name): string
|
||||
{
|
||||
return strtolower(pathinfo(rtrim($name, '. '), PATHINFO_EXTENSION));
|
||||
}
|
||||
|
||||
/** Art des Programms nach den ersten Bytes, oder null. */
|
||||
function virenscan_exec_magic(string $head): ?string
|
||||
{
|
||||
if (str_starts_with($head, 'MZ')) return 'Windows-Programm (EXE/DLL)';
|
||||
if (str_starts_with($head, "\x7fELF")) return 'Linux-Programm (ELF)';
|
||||
foreach (["\xCF\xFA\xED\xFE", "\xCE\xFA\xED\xFE", "\xFE\xED\xFA\xCE", "\xFE\xED\xFA\xCF"] as $m) if (str_starts_with($head, $m)) return 'macOS-Programm (Mach-O)';
|
||||
if (str_starts_with($head, "\xCA\xFE\xBA\xBE")) return 'Java-Programm oder Universalprogramm';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Namenstricks: umgekehrte Schreibrichtung, doppelte Endung. @return list<array{0:string,1:string}> */
|
||||
function virenscan_name_findings(string $name): array
|
||||
{
|
||||
$out = [];
|
||||
if (preg_match('/[\x{202A}-\x{202E}\x{2066}-\x{2069}]/u', $name)) $out[] = ['exec', 'Verschleierter Dateiname (Zeichen zur Umkehr der Schreibrichtung)'];
|
||||
$ext = virenscan_file_ext($name);
|
||||
if (in_array($ext, VIRENSCAN_BAD_EXT, true)) $out[] = ['exec', 'Gefährlicher Dateityp (.' . $ext . ')'];
|
||||
elseif (preg_match('/\.(' . implode('|', array_map('preg_quote', VIRENSCAN_BAD_EXT)) . ')\s*\.[a-z0-9]{2,5}$/i', $name, $m)) $out[] = ['exec', 'Doppelte Endung (.' . strtolower($m[1]) . ' versteckt)'];
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Untersucht eine Datei. @return list<array{0:string,1:string}> Funde als [Kategorie, Text]. Kategorien: exec (Programme, Skripte, Tricks),
|
||||
* macro (Office-Makros), script (Skripte in HTML/SVG/RTF/PDF), archive (auffällige Archive), encrypted (passwortgeschützt), unscannable (nicht prüfbare Archive), eicar.
|
||||
*/
|
||||
function virenscan_analyze(string $path, string $name, int $depth = 0): array
|
||||
{
|
||||
$f = [];
|
||||
$size = (int) @filesize($path);
|
||||
$head = (string) @file_get_contents($path, false, null, 0, 4096);
|
||||
if ($head === '' && $size === 0) return $f;
|
||||
$ext = virenscan_file_ext($name);
|
||||
|
||||
if (str_contains((string) @file_get_contents($path, false, null, 0, 2 * 1024 * 1024), virenscan_eicar())) return [['eicar', 'Eicar-Test-Signature']];
|
||||
foreach (virenscan_name_findings($name) as $x) $f[] = $x;
|
||||
if (($kind = virenscan_exec_magic($head)) !== null) $f[] = ['exec', $kind . ($ext !== '' && !in_array($ext, VIRENSCAN_BAD_EXT, true) ? ', getarnt als .' . $ext : '')];
|
||||
if (in_array($ext, VIRENSCAN_MACRO_EXT, true)) $f[] = ['macro', 'Office-Datei mit Makros (.' . $ext . ')'];
|
||||
if (in_array($ext, VIRENSCAN_OTHER_ARCHIVES, true)) $f[] = ['unscannable', 'Archiv, das nicht geöffnet werden kann (.' . $ext . ')'];
|
||||
|
||||
// ZIP (auch Office-Dateien): Inhalt prüfen
|
||||
if (str_starts_with($head, "PK\x03\x04") && class_exists('ZipArchive')) {
|
||||
$za = new ZipArchive();
|
||||
if ($za->open($path) === true) {
|
||||
$n = $za->numFiles;
|
||||
if ($n > 2000) $f[] = ['archive', 'Archiv mit sehr vielen Dateien (' . $n . ')'];
|
||||
$total = 0; $encrypted = false; $macro = false; $bad = [];
|
||||
for ($i = 0; $i < min($n, 2000); $i++) {
|
||||
$st = $za->statIndex($i);
|
||||
if (!$st) continue;
|
||||
$total += (int) $st['size'];
|
||||
$en = (string) $st['name'];
|
||||
if (!empty($st['encryption_method'])) { $encrypted = true; continue; }
|
||||
if (str_ends_with(strtolower($en), 'vbaproject.bin')) $macro = true;
|
||||
foreach (virenscan_name_findings(basename($en)) as $x) { $bad[] = basename($en); break; }
|
||||
if ($i < 300 && (int) $st['size'] > 0 && virenscan_exec_magic((string) $za->getFromIndex($i, 8)) !== null) $bad[] = basename($en);
|
||||
}
|
||||
if ($total > 1024 * 1024 * 1024 || ($size > 0 && $total / max(1, $size) > 2000 && $total > 100 * 1024 * 1024)) $f[] = ['archive', 'Archiv entpackt sich auf ein Vielfaches (Zip-Bombe)'];
|
||||
if ($macro) $f[] = ['macro', 'Office-Datei mit Makros (VBA)'];
|
||||
if ($bad) $f[] = ['exec', 'Archiv enthält ' . implode(', ', array_slice(array_values(array_unique($bad)), 0, 3))];
|
||||
if ($encrypted) $f[] = ['encrypted', 'Passwortgeschütztes Archiv (Inhalt nicht prüfbar)'];
|
||||
$za->close();
|
||||
} elseif (!in_array($ext, ['docx', 'xlsx', 'pptx', 'odt', 'ods', 'jar', 'apk'], true)) {
|
||||
$f[] = ['unscannable', 'Archiv lässt sich nicht öffnen'];
|
||||
}
|
||||
}
|
||||
|
||||
// Altes Office-Format (OLE): Makros erkennen
|
||||
if (str_starts_with($head, "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1")) {
|
||||
$body = (string) @file_get_contents($path, false, null, 0, 4 * 1024 * 1024);
|
||||
if (str_contains($body, '_VBA_PROJECT') || str_contains($body, "_\0V\0B\0A\0_\0P\0R\0O\0J\0E\0C\0T") || str_contains($body, "M\0a\0c\0r\0o\0s\0")) $f[] = ['macro', 'Office-Datei mit Makros (VBA)'];
|
||||
}
|
||||
|
||||
// PDF: startende Programme oder automatisches JavaScript
|
||||
if (str_contains(substr($head, 0, 1024), '%PDF')) {
|
||||
$body = (string) @file_get_contents($path, false, null, 0, 4 * 1024 * 1024);
|
||||
if (preg_match('/\/Launch\b/', $body)) $f[] = ['script', 'PDF startet Programme (/Launch)'];
|
||||
if (preg_match('/\/(JavaScript|JS)\b/', $body) && preg_match('/\/(OpenAction|AA)\b/', $body)) $f[] = ['script', 'PDF mit automatisch startendem JavaScript'];
|
||||
if (preg_match('/\/EmbeddedFile\b/', $body) && preg_match('/\.(exe|scr|bat|cmd|vbs|js|jar|ps1|msi)\b/i', $body)) $f[] = ['exec', 'PDF mit eingebetteter ausführbarer Datei'];
|
||||
}
|
||||
|
||||
// Webseiten und Bilder mit Skriptcode
|
||||
if (in_array($ext, ['html', 'htm', 'xhtml', 'shtml', 'svg', 'mht', 'mhtml', 'xml'], true)) {
|
||||
$body = (string) @file_get_contents($path, false, null, 0, 1024 * 1024);
|
||||
if (preg_match('/<script\b|javascript:|\bon(load|error|click|mouseover)\s*=/i', $body)) $f[] = ['script', 'Enthält ausführbaren Skriptcode'];
|
||||
}
|
||||
// RTF mit eingebetteten Objekten
|
||||
if (str_starts_with($head, '{\\rtf')) {
|
||||
$body = (string) @file_get_contents($path, false, null, 0, 4 * 1024 * 1024);
|
||||
if (preg_match('/\\\\(objdata|objupdate|objautlink)\b/', $body)) $f[] = ['exec', 'RTF mit eingebettetem Objekt'];
|
||||
}
|
||||
return $f;
|
||||
}
|
||||
|
||||
/** Entscheidet nach den Einstellungen, welche Funde zum Sperren führen. @return list<string> Gründe, leer = sauber */
|
||||
function virenscan_block_reasons(array $findings, array $cfg): array
|
||||
{
|
||||
$reasons = [];
|
||||
foreach ($findings as [$cat, $text]) {
|
||||
$on = match ($cat) {
|
||||
'exec', 'archive', 'script', 'eicar' => true,
|
||||
'macro' => $cfg['block_macros'],
|
||||
'encrypted' => $cfg['block_encrypted'],
|
||||
'unscannable' => $cfg['block_unscannable'],
|
||||
default => true,
|
||||
};
|
||||
if ($on) $reasons[] = $text;
|
||||
}
|
||||
return array_values(array_unique($reasons));
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
<?php
|
||||
// Virenscan-Plugin: Prüfung, Quarantäne und Verwaltung. Alle Funktionen beginnen mit virenscan_.
|
||||
|
||||
const VIRENSCAN = 'virenscan';
|
||||
|
||||
require_once __DIR__ . '/analyse.php';
|
||||
|
||||
/** Einstellungen mit Standardwerten. */
|
||||
/**
|
||||
* Selbstheilung: Fehlt nach einem Update eine Datenbank-Änderung des Plugins (ältere DeskHub-Dateien spielen sie nicht von selbst ein),
|
||||
* wird sie hier nachgeholt, statt dass das Plugin mit Datenbankfehlern abgeschaltet wird.
|
||||
*/
|
||||
function virenscan_ensure_schema(bool $force = false): void
|
||||
{
|
||||
static $done = false;
|
||||
if ($done && !$force) return;
|
||||
$done = true;
|
||||
try {
|
||||
get_db()->query('SELECT rep, sha256 FROM plugin_virenscan_files LIMIT 1');
|
||||
} catch (Throwable $e) {
|
||||
try {
|
||||
plugin_run_migrations(get_db(), VIRENSCAN);
|
||||
} catch (Throwable $e2) {
|
||||
error_log('virenscan schema: ' . $e2->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function virenscan_config(): array
|
||||
{
|
||||
$key = '';
|
||||
$enc = (string) plugin_setting(VIRENSCAN, 'vt_key', '');
|
||||
if ($enc !== '') { try { $key = decrypt_secret($enc); } catch (Throwable $e) { $key = ''; } }
|
||||
return [
|
||||
'analysis' => plugin_setting(VIRENSCAN, 'analysis', '1') === '1',
|
||||
'block_macros' => plugin_setting(VIRENSCAN, 'block_macros', '1') === '1',
|
||||
'block_encrypted' => plugin_setting(VIRENSCAN, 'block_encrypted', '1') === '1',
|
||||
'block_unscannable' => plugin_setting(VIRENSCAN, 'block_unscannable', '0') === '1',
|
||||
'vt_key' => $key,
|
||||
'vt_threshold' => max(1, min(30, (int) plugin_setting(VIRENSCAN, 'vt_threshold', '3'))),
|
||||
] + virenscan_config_base();
|
||||
}
|
||||
|
||||
function virenscan_config_base(): array
|
||||
{
|
||||
return [
|
||||
'mode' => in_array(plugin_setting(VIRENSCAN, 'mode', 'auto'), ['auto', 'clamdscan', 'clamscan', 'builtin'], true) ? plugin_setting(VIRENSCAN, 'mode', 'auto') : 'auto',
|
||||
'binary' => trim((string) plugin_setting(VIRENSCAN, 'binary', '')),
|
||||
'timeout' => max(5, min(300, (int) plugin_setting(VIRENSCAN, 'timeout', '60'))),
|
||||
'max_mb' => max(1, min(500, (int) plugin_setting(VIRENSCAN, 'max_mb', '25'))),
|
||||
'block_on_error' => plugin_setting(VIRENSCAN, 'block_on_error', '0') === '1',
|
||||
'notify' => plugin_setting(VIRENSCAN, 'notify', '1') === '1',
|
||||
];
|
||||
}
|
||||
|
||||
function virenscan_uploads_dir(): string
|
||||
{
|
||||
return rtrim(str_replace('\\', '/', (string) (config()['uploads']['path'] ?? dirname(__DIR__, 2) . '/uploads')), '/');
|
||||
}
|
||||
|
||||
function virenscan_quarantine_dir(): string
|
||||
{
|
||||
$dir = virenscan_uploads_dir() . '/quarantaene';
|
||||
if (!is_dir($dir)) {
|
||||
@mkdir($dir, 0750, true);
|
||||
@file_put_contents($dir . '/.htaccess', "Require all denied\nDeny from all\n");
|
||||
@file_put_contents($dir . '/index.html', '');
|
||||
}
|
||||
return $dir;
|
||||
}
|
||||
|
||||
/** Die Standard-Testzeichenfolge (EICAR), in Teilen geschrieben, damit Virenscanner diese Quelldatei nicht selbst melden. */
|
||||
function virenscan_eicar(): string
|
||||
{
|
||||
return 'X5O!P%@AP[4\\PZX54(P^)7CC)7}$' . 'EICAR-STANDARD-ANTIVIRUS-TEST-FILE!' . '$H+H*';
|
||||
}
|
||||
|
||||
/**
|
||||
* Führt ein Programm mit Zeitlimit aus (ohne Shell). Die Ausgabe geht in Temp-Dateien statt in Pipes, damit das Zeitlimit auch unter Windows greift
|
||||
* (dort lassen sich Pipes nicht nicht-blockierend lesen). @return array{0:int,1:string,2:string} Exit-Code, Ausgabe, Fehlerausgabe
|
||||
*/
|
||||
function virenscan_run(array $cmd, int $timeout): array
|
||||
{
|
||||
$outFile = tempnam(sys_get_temp_dir(), 'vso');
|
||||
$errFile = tempnam(sys_get_temp_dir(), 'vse');
|
||||
$proc = @proc_open($cmd, [1 => ['file', $outFile, 'w'], 2 => ['file', $errFile, 'w']], $pipes);
|
||||
if (!is_resource($proc)) {
|
||||
@unlink($outFile); @unlink($errFile);
|
||||
return [-1, '', 'Das Programm konnte nicht gestartet werden.'];
|
||||
}
|
||||
$end = microtime(true) + $timeout;
|
||||
$exit = null;
|
||||
$timedOut = false;
|
||||
while (true) {
|
||||
$status = proc_get_status($proc);
|
||||
if (!$status['running']) { $exit = (int) $status['exitcode']; break; }
|
||||
if (microtime(true) > $end) { proc_terminate($proc); $timedOut = true; break; }
|
||||
usleep(40000);
|
||||
}
|
||||
proc_close($proc);
|
||||
$out = (string) @file_get_contents($outFile, false, null, 0, 1048576);
|
||||
$err = (string) @file_get_contents($errFile, false, null, 0, 1048576);
|
||||
@unlink($outFile); @unlink($errFile);
|
||||
if ($timedOut) return [-1, $out, "Zeitüberschreitung nach {$timeout} Sekunden."];
|
||||
return [$exit, $out, $err];
|
||||
}
|
||||
/** Welches Prüfprogramm wird benutzt? @return array{mode:string,binary:string} mode: clamdscan, clamscan oder builtin */
|
||||
function virenscan_resolve(): array
|
||||
{
|
||||
$cfg = virenscan_config();
|
||||
if ($cfg['mode'] === 'builtin') return ['mode' => 'builtin', 'binary' => ''];
|
||||
if ($cfg['binary'] !== '') {
|
||||
$m = $cfg['mode'] === 'auto' ? (str_contains(strtolower(basename($cfg['binary'])), 'clamdscan') ? 'clamdscan' : 'clamscan') : $cfg['mode'];
|
||||
return ['mode' => $m, 'binary' => $cfg['binary']];
|
||||
}
|
||||
$candidates = static fn(string $name) => ["/usr/bin/{$name}", "/usr/local/bin/{$name}", "/opt/clamav/bin/{$name}", "C:/Program Files/ClamAV/{$name}.exe"];
|
||||
foreach ($cfg['mode'] === 'auto' ? ['clamdscan', 'clamscan'] : [$cfg['mode']] as $m) {
|
||||
foreach ($candidates($m) as $path) if (is_file($path) && is_executable($path)) return ['mode' => $m, 'binary' => $path];
|
||||
}
|
||||
return ['mode' => 'builtin', 'binary' => ''];
|
||||
}
|
||||
/** Zustand des Prüfprogramms für die Einstellungsseite. @return array{mode:string,binary:string,version:?string,ok:bool,message:string} */
|
||||
function virenscan_status(): array
|
||||
{
|
||||
$r = virenscan_resolve();
|
||||
if ($r['mode'] === 'builtin') {
|
||||
return $r + ['version' => null, 'ok' => false, 'message' => 'ClamAV ist auf diesem Server nicht installiert. Es läuft die eingebaute Dateianalyse' . (virenscan_config()['vt_key'] !== '' ? ' mit Hash-Abfrage bei VirusTotal.' : '. Mit einem VirusTotal-Schlüssel (kostenlos) werden Dateien zusätzlich gegen bekannte Schadsoftware abgeglichen.')];
|
||||
}
|
||||
[$code, $out, $err] = virenscan_run([$r['binary'], '--version'], 15);
|
||||
if ($code !== 0) return $r + ['version' => null, 'ok' => false, 'message' => 'Das Prüfprogramm antwortet nicht: ' . trim($err !== '' ? $err : $out)];
|
||||
return $r + ['version' => trim(strtok($out, "\n")), 'ok' => true, 'message' => 'Bereit.'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft eine Datei: zuerst ClamAV (falls auf dem Server vorhanden), dann die eingebaute Dateianalyse.
|
||||
* @return array{status:string,signature:?string,message:?string} status: clean, infected oder error
|
||||
*/
|
||||
function virenscan_scan_file(string $path, string $name = ''): array
|
||||
{
|
||||
if (!is_file($path)) return ['status' => 'error', 'signature' => null, 'message' => 'Datei nicht gefunden.'];
|
||||
$cfg = virenscan_config();
|
||||
$r = virenscan_resolve();
|
||||
$clam = null;
|
||||
if ($r['mode'] !== 'builtin') {
|
||||
$cmd = [$r['binary'], '--no-summary'];
|
||||
if ($r['mode'] === 'clamdscan') $cmd[] = '--fdpass';
|
||||
$cmd[] = $path;
|
||||
[$code, $out, $err] = virenscan_run($cmd, $cfg['timeout']);
|
||||
$clam = virenscan_interpret($code, $out, $err);
|
||||
if ($clam['status'] === 'infected') return $clam;
|
||||
}
|
||||
// Eingebaute Analyse (läuft auch mit ClamAV zusätzlich: erkennt Dateitypen und Tricks, die ein Virenscanner durchlässt)
|
||||
$findings = $cfg['analysis'] ? virenscan_analyze($path, $name !== '' ? $name : basename($path)) : [];
|
||||
if (!$cfg['analysis']) {
|
||||
$head = (string) @file_get_contents($path, false, null, 0, 2 * 1024 * 1024);
|
||||
if (str_contains($head, virenscan_eicar())) $findings = [['eicar', 'Eicar-Test-Signature']];
|
||||
}
|
||||
$reasons = virenscan_block_reasons($findings, $cfg);
|
||||
if ($reasons) {
|
||||
$sig = in_array('Eicar-Test-Signature', $reasons, true) ? 'Eicar-Test-Signature' : 'Dateianalyse: ' . implode('; ', $reasons);
|
||||
return ['status' => 'infected', 'signature' => mb_substr($sig, 0, 250), 'message' => null];
|
||||
}
|
||||
if ($clam !== null) return $clam;
|
||||
return ['status' => 'clean', 'signature' => null, 'message' => $cfg['analysis'] ? 'Dateianalyse' : 'Nur Testprüfung (Dateianalyse ausgeschaltet)'];
|
||||
}
|
||||
|
||||
/** Wertet die Ausgabe von clamscan/clamdscan aus: Exit-Code 0 = sauber, 1 = Fund ("Datei: Name FOUND"), sonst Fehler. */
|
||||
function virenscan_interpret(int $code, string $out, string $err): array
|
||||
{
|
||||
if ($code === 0) return ['status' => 'clean', 'signature' => null, 'message' => null];
|
||||
if ($code === 1) {
|
||||
$sig = preg_match('/:\s*(.+?)\s+FOUND/i', $out, $m) ? $m[1] : 'unbekannt';
|
||||
return ['status' => 'infected', 'signature' => mb_substr($sig, 0, 250), 'message' => null];
|
||||
}
|
||||
return ['status' => 'error', 'signature' => null, 'message' => mb_substr(trim($err !== '' ? $err : $out) ?: 'Prüfung fehlgeschlagen (Code ' . $code . ').', 0, 250)];
|
||||
}
|
||||
|
||||
function virenscan_start_id(PDO $pdo): int
|
||||
{
|
||||
$v = plugin_setting(VIRENSCAN, 'start_id', null);
|
||||
if ($v === null) {
|
||||
// Erster Lauf: Bestand nicht nachträglich prüfen, nur neue Anhänge (über die Seite lässt sich der Bestand nachholen)
|
||||
$v = (string) (int) $pdo->query('SELECT COALESCE(MAX(id), 0) FROM ticket_attachments')->fetchColumn();
|
||||
plugin_set_setting(VIRENSCAN, 'start_id', $v);
|
||||
}
|
||||
return (int) $v;
|
||||
}
|
||||
|
||||
/** Noch ungeprüfte Anhänge (optional nur eines Tickets). */
|
||||
function virenscan_pending(PDO $pdo, int $limit = 25, ?int $ticketId = null): array
|
||||
{
|
||||
$sql = "SELECT a.id, a.original_name, a.stored_name, a.filesize, t.ticket_id FROM ticket_attachments a JOIN ticket_threads t ON t.id = a.thread_id
|
||||
WHERE a.id > ? AND a.stored_name <> 'gesperrt' AND a.id NOT IN (SELECT attachment_id FROM plugin_virenscan_files)";
|
||||
$params = [virenscan_start_id($pdo)];
|
||||
if ($ticketId !== null) { $sql .= ' AND t.ticket_id = ?'; $params[] = $ticketId; }
|
||||
$stmt = $pdo->prepare($sql . ' ORDER BY a.id LIMIT ' . max(1, $limit));
|
||||
$stmt->execute($params);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function virenscan_record(PDO $pdo, array $att, string $status, ?string $signature, ?string $message, bool $quarantined = false): void
|
||||
{
|
||||
$pdo->prepare('INSERT INTO plugin_virenscan_files (attachment_id, ticket_id, original_name, stored_name, status, signature, message, quarantined, scanned_at) VALUES (?,?,?,?,?,?,?,?,?)')
|
||||
->execute([(int) $att['id'], $att['ticket_id'] ?? null, mb_substr((string) $att['original_name'], 0, 255), mb_substr((string) $att['stored_name'], 0, 255), $status, $signature, $message !== null ? mb_substr($message, 0, 250) : null, $quarantined ? 1 : 0, db_now()]);
|
||||
}
|
||||
|
||||
/** Prüft einen Anhang und sperrt ihn, wenn er verseucht ist. @return string clean, infected, error, skipped oder blocked */
|
||||
function virenscan_scan_attachment(PDO $pdo, array $att): string
|
||||
{
|
||||
$cfg = virenscan_config();
|
||||
$path = virenscan_uploads_dir() . '/' . basename((string) $att['stored_name']);
|
||||
if (!is_file($path)) { virenscan_record($pdo, $att, 'error', null, 'Datei nicht gefunden.'); return 'error'; }
|
||||
if (filesize($path) > $cfg['max_mb'] * 1024 * 1024) { virenscan_record($pdo, $att, 'skipped', null, 'Größer als ' . $cfg['max_mb'] . ' MB, nicht geprüft.'); return 'skipped'; }
|
||||
$res = virenscan_scan_file($path, (string) $att['original_name']);
|
||||
if ($res['status'] === 'infected') {
|
||||
virenscan_record($pdo, $att, 'infected', $res['signature'], null);
|
||||
virenscan_quarantine($pdo, (int) $att['id'], (string) $res['signature']);
|
||||
return 'infected';
|
||||
}
|
||||
if ($res['status'] === 'error') {
|
||||
if ($cfg['block_on_error']) {
|
||||
virenscan_record($pdo, $att, 'blocked', null, $res['message']);
|
||||
virenscan_quarantine($pdo, (int) $att['id'], 'Prüfung fehlgeschlagen');
|
||||
return 'blocked';
|
||||
}
|
||||
virenscan_record($pdo, $att, 'error', null, $res['message']);
|
||||
return 'error';
|
||||
}
|
||||
virenscan_record($pdo, $att, 'clean', null, $res['message']);
|
||||
return 'clean';
|
||||
}
|
||||
|
||||
/** Verschiebt die Datei in die Quarantäne, benennt den Anhang um (nicht mehr herunterladbar) und vermerkt es im Ticket. */
|
||||
function virenscan_quarantine(PDO $pdo, int $attachmentId, string $reason): bool
|
||||
{
|
||||
$stmt = $pdo->prepare('SELECT a.*, t.ticket_id FROM ticket_attachments a JOIN ticket_threads t ON t.id = a.thread_id WHERE a.id = ?');
|
||||
$stmt->execute([$attachmentId]);
|
||||
$att = $stmt->fetch();
|
||||
if (!$att || $att['stored_name'] === 'gesperrt') return false;
|
||||
$from = virenscan_uploads_dir() . '/' . basename((string) $att['stored_name']);
|
||||
$to = virenscan_quarantine_dir() . '/' . basename((string) $att['stored_name']);
|
||||
if (is_file($from) && !@rename($from, $to)) {
|
||||
if (!@copy($from, $to) || !@unlink($from)) return false;
|
||||
}
|
||||
$pdo->prepare("UPDATE ticket_attachments SET stored_name = 'gesperrt', original_name = ? WHERE id = ?")->execute([mb_substr('[GESPERRT] ' . $att['original_name'], 0, 255), $attachmentId]);
|
||||
$pdo->prepare('UPDATE plugin_virenscan_files SET quarantined = 1 WHERE attachment_id = ?')->execute([$attachmentId]);
|
||||
$ticketId = (int) $att['ticket_id'];
|
||||
$text = 'Der Anhang „' . $att['original_name'] . '“ wurde vom Virenscan gesperrt (' . $reason . '). Er liegt in der Quarantäne und lässt sich unter Virenscan prüfen oder freigeben.';
|
||||
$pdo->prepare("INSERT INTO ticket_threads (ticket_id, author_type, message, is_internal_note, created_at) VALUES (?, 'system', ?, 1, ?)")->execute([$ticketId, $text, db_now()]);
|
||||
log_activity($pdo, $ticketId, null, 'Anhang vom Virenscan gesperrt: ' . $att['original_name'] . ' (' . $reason . ')');
|
||||
if (function_exists('apply_tag_to_ticket')) apply_tag_to_ticket($pdo, $ticketId, 'Virus-Verdacht');
|
||||
if (virenscan_config()['notify']) virenscan_notify($pdo, $ticketId, (string) $att['original_name'], $reason);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Mail an die Adresse des Administrators (Einstellung der Installation). */
|
||||
function virenscan_notify(PDO $pdo, int $ticketId, string $name, string $reason): void
|
||||
{
|
||||
$to = (string) (get_setting('admin_email', '') ?: (config()['site']['admin_email'] ?? ''));
|
||||
if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) return;
|
||||
$t = $pdo->prepare('SELECT ticket_number FROM tickets WHERE id = ?');
|
||||
$t->execute([$ticketId]);
|
||||
$number = (string) $t->fetchColumn();
|
||||
try {
|
||||
send_mail($to, "Virenscan: Anhang in Ticket #{$number} gesperrt", '<p>Der Anhang <strong>' . e($name) . '</strong> in Ticket <strong>#' . e($number) . '</strong> wurde gesperrt (' . e($reason) . ').</p><p>Er liegt in der Quarantäne. Prüfen, freigeben oder löschen kannst du ihn unter <strong>Virenscan</strong> im Mitarbeiterbereich.</p>');
|
||||
} catch (Throwable $e) {
|
||||
// Mailfehler dürfen das Sperren nie verhindern
|
||||
}
|
||||
}
|
||||
|
||||
/** Gibt eine gesperrte Datei wieder frei (zum Beispiel bei Fehlalarm). */
|
||||
function virenscan_release(PDO $pdo, int $rowId): bool
|
||||
{
|
||||
$stmt = $pdo->prepare('SELECT * FROM plugin_virenscan_files WHERE id = ? AND quarantined = 1');
|
||||
$stmt->execute([$rowId]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) return false;
|
||||
$from = virenscan_quarantine_dir() . '/' . basename((string) $row['stored_name']);
|
||||
$to = virenscan_uploads_dir() . '/' . basename((string) $row['stored_name']);
|
||||
if (is_file($from) && !@rename($from, $to)) return false;
|
||||
$pdo->prepare('UPDATE ticket_attachments SET stored_name = ?, original_name = ? WHERE id = ?')->execute([$row['stored_name'], $row['original_name'], (int) $row['attachment_id']]);
|
||||
$pdo->prepare("UPDATE plugin_virenscan_files SET quarantined = 0, status = 'released', message = ? WHERE id = ?")->execute(['Freigegeben am ' . db_now(), $rowId]);
|
||||
if ($row['ticket_id']) log_activity($pdo, (int) $row['ticket_id'], null, 'Gesperrter Anhang freigegeben: ' . $row['original_name']);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Löscht eine gesperrte Datei endgültig (der Anhang bleibt als „gelöscht“ im Ticket vermerkt). */
|
||||
function virenscan_delete(PDO $pdo, int $rowId): bool
|
||||
{
|
||||
$stmt = $pdo->prepare('SELECT * FROM plugin_virenscan_files WHERE id = ? AND quarantined = 1');
|
||||
$stmt->execute([$rowId]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) return false;
|
||||
$file = virenscan_quarantine_dir() . '/' . basename((string) $row['stored_name']);
|
||||
if (is_file($file)) @unlink($file);
|
||||
$pdo->prepare("UPDATE ticket_attachments SET original_name = ? WHERE id = ?")->execute([mb_substr('[GELÖSCHT] ' . $row['original_name'], 0, 255), (int) $row['attachment_id']]);
|
||||
$pdo->prepare("UPDATE plugin_virenscan_files SET quarantined = 0, status = 'deleted', message = ? WHERE id = ?")->execute(['Gelöscht am ' . db_now(), $rowId]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Prüft die noch ungeprüften Anhänge eines Tickets (nach neuer Nachricht oder neuem Ticket). */
|
||||
function virenscan_scan_ticket(PDO $pdo, int $ticketId): int
|
||||
{
|
||||
$n = 0;
|
||||
foreach (virenscan_pending($pdo, 10, $ticketId) as $att) { virenscan_scan_attachment($pdo, $att); $n++; }
|
||||
return $n;
|
||||
}
|
||||
|
||||
/** Hintergrundlauf (etwa alle 5 Minuten): ungeprüfte Anhänge nachholen, zum Beispiel aus E-Mails. */
|
||||
function virenscan_tick(PDO $pdo): int
|
||||
{
|
||||
$n = 0;
|
||||
foreach (virenscan_pending($pdo, 25) as $att) { virenscan_scan_attachment($pdo, $att); $n++; }
|
||||
$n += virenscan_reputation_tick($pdo);
|
||||
if ($n > 0) plugin_set_setting(VIRENSCAN, 'last_run', db_now());
|
||||
return $n;
|
||||
}
|
||||
|
||||
/** Zahlen für die Seite: Anzahl je Status. @return array<string,int> */
|
||||
function virenscan_stats(PDO $pdo): array
|
||||
{
|
||||
$out = ['clean' => 0, 'infected' => 0, 'error' => 0, 'skipped' => 0, 'blocked' => 0, 'released' => 0, 'deleted' => 0, 'quarantined' => 0];
|
||||
foreach ($pdo->query('SELECT status, COUNT(*) AS n FROM plugin_virenscan_files GROUP BY status')->fetchAll() as $r) $out[$r['status']] = (int) $r['n'];
|
||||
$out['quarantined'] = (int) $pdo->query('SELECT COUNT(*) FROM plugin_virenscan_files WHERE quarantined = 1')->fetchColumn();
|
||||
return $out;
|
||||
}
|
||||
|
||||
// ── Hash-Abfrage bei VirusTotal ────────────────────────────────────────────
|
||||
// Es wird nur der SHA-256-Wert der Datei gesendet, nie die Datei selbst. Kostenloser Schlüssel: 4 Abfragen pro Minute, 500 pro Tag.
|
||||
|
||||
/** HTTP-Aufruf (für Tests austauschbar über $GLOBALS['virenscan_http']). @return array{status:int,body:string} */
|
||||
function virenscan_http(string $url, array $headers): array
|
||||
{
|
||||
if (isset($GLOBALS['virenscan_http']) && is_callable($GLOBALS['virenscan_http'])) return ($GLOBALS['virenscan_http'])($url, $headers);
|
||||
$ctx = stream_context_create(['http' => ['method' => 'GET', 'header' => implode("\r\n", $headers), 'timeout' => 8, 'ignore_errors' => true]]);
|
||||
$res = @file_get_contents($url, false, $ctx);
|
||||
$status = 0;
|
||||
foreach ($http_response_header ?? [] as $h) if (preg_match('#^HTTP/\S+\s+(\d+)#', $h, $m)) $status = (int) $m[1];
|
||||
return ['status' => $status, 'body' => $res === false ? '' : (string) $res];
|
||||
}
|
||||
|
||||
/** @return array{result:string,detail:?string} result: bad, clean, unknown, limit, key oder error */
|
||||
function virenscan_vt_lookup(string $sha256, string $key, int $threshold): array
|
||||
{
|
||||
$r = virenscan_http('https://www.virustotal.com/api/v3/files/' . $sha256, ['x-apikey: ' . $key, 'Accept: application/json']);
|
||||
if ($r['status'] === 404) return ['result' => 'unknown', 'detail' => null];
|
||||
if ($r['status'] === 429) return ['result' => 'limit', 'detail' => null];
|
||||
if ($r['status'] === 401 || $r['status'] === 403) return ['result' => 'key', 'detail' => 'Der VirusTotal-Schlüssel wird abgelehnt.'];
|
||||
if ($r['status'] !== 200) return ['result' => 'error', 'detail' => 'VirusTotal nicht erreichbar (Status ' . $r['status'] . ').'];
|
||||
$j = json_decode($r['body'], true);
|
||||
$stats = $j['data']['attributes']['last_analysis_stats'] ?? null;
|
||||
if (!is_array($stats)) return ['result' => 'error', 'detail' => 'Unerwartete Antwort von VirusTotal.'];
|
||||
$bad = (int) ($stats['malicious'] ?? 0);
|
||||
if ($bad >= $threshold) {
|
||||
$label = (string) ($j['data']['attributes']['popular_threat_classification']['suggested_threat_label'] ?? '');
|
||||
return ['result' => 'bad', 'detail' => 'VirusTotal: ' . $bad . ' Scanner melden Schadsoftware' . ($label !== '' ? ' (' . mb_substr($label, 0, 60) . ')' : '')];
|
||||
}
|
||||
return ['result' => 'clean', 'detail' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hintergrundlauf der Hash-Abfrage: prüft saubere Dateien nachträglich gegen VirusTotal, höchstens 4 pro Lauf und 450 pro Tag.
|
||||
* Findet VirusTotal Schadsoftware, wird die Datei gesperrt. @return int Zahl der abgefragten Dateien
|
||||
*/
|
||||
function virenscan_reputation_tick(PDO $pdo): int
|
||||
{
|
||||
$cfg = virenscan_config();
|
||||
if ($cfg['vt_key'] === '') return 0;
|
||||
$today = date('Y-m-d');
|
||||
if (plugin_setting(VIRENSCAN, 'vt_day', '') !== $today) { plugin_set_setting(VIRENSCAN, 'vt_day', $today); plugin_set_setting(VIRENSCAN, 'vt_count', '0'); }
|
||||
$used = (int) plugin_setting(VIRENSCAN, 'vt_count', '0');
|
||||
$rows = $pdo->query("SELECT * FROM plugin_virenscan_files WHERE status = 'clean' AND rep IS NULL AND quarantined = 0 ORDER BY id LIMIT 4")->fetchAll();
|
||||
$done = 0;
|
||||
foreach ($rows as $row) {
|
||||
if ($used >= 450) break;
|
||||
$path = virenscan_uploads_dir() . '/' . basename((string) $row['stored_name']);
|
||||
if (!is_file($path) || filesize($path) > $cfg['max_mb'] * 1024 * 1024) {
|
||||
$pdo->prepare("UPDATE plugin_virenscan_files SET rep = 'skipped' WHERE id = ?")->execute([$row['id']]);
|
||||
continue;
|
||||
}
|
||||
$hash = hash_file('sha256', $path);
|
||||
$res = virenscan_vt_lookup($hash, $cfg['vt_key'], $cfg['vt_threshold']);
|
||||
if ($res['result'] === 'limit') break;
|
||||
if ($res['result'] === 'key' || $res['result'] === 'error') { plugin_set_setting(VIRENSCAN, 'vt_error', db_now() . ': ' . $res['detail']); break; }
|
||||
plugin_set_setting(VIRENSCAN, 'vt_error', '');
|
||||
$used++; $done++;
|
||||
plugin_set_setting(VIRENSCAN, 'vt_count', (string) $used);
|
||||
if ($res['result'] === 'bad') {
|
||||
$pdo->prepare("UPDATE plugin_virenscan_files SET rep = 'bad', sha256 = ?, status = 'infected', signature = ? WHERE id = ?")->execute([$hash, mb_substr((string) $res['detail'], 0, 250), $row['id']]);
|
||||
virenscan_quarantine($pdo, (int) $row['attachment_id'], (string) $res['detail']);
|
||||
} else {
|
||||
$pdo->prepare('UPDATE plugin_virenscan_files SET rep = ?, sha256 = ? WHERE id = ?')->execute([$res['result'], $hash, $row['id']]);
|
||||
}
|
||||
}
|
||||
return $done;
|
||||
}
|
||||
/** Adresse eines Reiters der Plugin-Seite. */
|
||||
function virenscan_tab_url(string $tab, array $extra = []): string
|
||||
{
|
||||
$q = ['p' => VIRENSCAN, 'page' => 'virenscan', 'tab' => $tab] + array_filter($extra, fn($v) => $v !== '' && $v !== null && $v !== 1);
|
||||
return '/staff/plugin.php?' . http_build_query($q);
|
||||
}
|
||||
|
||||
/** Reiterleiste. @param array<string,array{0:string,1:int}> $tabs Schlüssel => [Beschriftung, Anzahl (0 = keine Anzeige)] */
|
||||
function virenscan_tabs(string $active, array $tabs): string
|
||||
{
|
||||
$html = '<div class="plugin-tabs" style="display:flex;gap:4px;flex-wrap:wrap;border-bottom:1px solid var(--border,#e3e9ee);margin:0 0 18px">';
|
||||
foreach ($tabs as $key => [$label, $count]) {
|
||||
$on = $key === $active;
|
||||
$html .= '<a href="' . htmlspecialchars(virenscan_tab_url($key), ENT_QUOTES) . '" style="padding:8px 16px;border-radius:8px 8px 0 0;text-decoration:none;font-size:.9rem;'
|
||||
. ($on ? 'background:var(--card-bg,#fff);border:1px solid var(--border,#e3e9ee);border-bottom-color:var(--card-bg,#fff);font-weight:600;color:inherit;position:relative;top:1px' : 'color:var(--muted,#64748b);border:1px solid transparent') . '">'
|
||||
. htmlspecialchars($label)
|
||||
. ($count > 0 ? ' <span style="background:#dc2626;color:#fff;border-radius:20px;padding:1px 8px;font-size:.72rem;font-weight:700">' . (int) $count . '</span>' : '')
|
||||
. '</a>';
|
||||
}
|
||||
return $html . '</div>';
|
||||
}
|
||||
|
||||
/** Deinstallation mit „Daten löschen“: Quarantäne-Dateien bleiben liegen, nur die Tabelle verschwindet. */
|
||||
plugin_add_hook('plugin.uninstall.' . VIRENSCAN, function () {
|
||||
try {
|
||||
get_db()->exec('DROP TABLE IF EXISTS plugin_virenscan_files');
|
||||
} catch (Throwable $e) {
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS plugin_virenscan_files (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
attachment_id INT NOT NULL,
|
||||
ticket_id INT NULL,
|
||||
original_name VARCHAR(255) NOT NULL,
|
||||
stored_name VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL,
|
||||
signature VARCHAR(255) NULL,
|
||||
message VARCHAR(255) NULL,
|
||||
quarantined TINYINT(1) NOT NULL DEFAULT 0,
|
||||
scanned_at DATETIME NOT NULL,
|
||||
UNIQUE KEY idx_plugin_virenscan_attachment (attachment_id),
|
||||
KEY idx_plugin_virenscan_status (status, quarantined)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS plugin_virenscan_files (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
attachment_id INTEGER NOT NULL,
|
||||
ticket_id INTEGER NULL,
|
||||
original_name VARCHAR(255) NOT NULL,
|
||||
stored_name VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL,
|
||||
signature VARCHAR(255) NULL,
|
||||
message VARCHAR(255) NULL,
|
||||
quarantined INTEGER NOT NULL DEFAULT 0,
|
||||
scanned_at DATETIME NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_plugin_virenscan_attachment ON plugin_virenscan_files (attachment_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_plugin_virenscan_status ON plugin_virenscan_files (status, quarantined)
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE plugin_virenscan_files ADD COLUMN rep VARCHAR(12) NULL, ADD COLUMN sha256 VARCHAR(64) NULL
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE plugin_virenscan_files ADD COLUMN rep TEXT NULL;
|
||||
ALTER TABLE plugin_virenscan_files ADD COLUMN sha256 TEXT NULL
|
||||
@@ -0,0 +1,210 @@
|
||||
<?php
|
||||
// Seite des Virenscan-Plugins mit Reitern (Übersicht, Quarantäne, Geprüft, Einstellungen). Verfügbar: $staff, $pdo.
|
||||
$isAdmin = ($staff['role'] ?? '') === 'admin';
|
||||
if (!$isAdmin) { echo '<h1>Virenscan</h1><div class="flash error">Der Virenscan ist nur für Administratoren zugänglich.</div>'; return; }
|
||||
$message = null;
|
||||
$error = null;
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
verify_csrf();
|
||||
if (!$isAdmin) {
|
||||
$error = 'Änderungen sind Administratoren vorbehalten.';
|
||||
} else {
|
||||
$action = $_POST['action'] ?? '';
|
||||
if ($action === 'save') {
|
||||
$mode = in_array($_POST['mode'] ?? '', ['auto', 'clamdscan', 'clamscan', 'builtin'], true) ? $_POST['mode'] : 'auto';
|
||||
$binary = trim((string) ($_POST['binary'] ?? ''));
|
||||
if ($binary !== '' && (preg_match('/[\r\n\0]/', $binary) || !is_file($binary) || !is_executable($binary))) {
|
||||
$error = 'Der angegebene Pfad ist keine ausführbare Datei.';
|
||||
} else {
|
||||
plugin_set_setting(VIRENSCAN, 'mode', $mode);
|
||||
plugin_set_setting(VIRENSCAN, 'binary', $binary);
|
||||
plugin_set_setting(VIRENSCAN, 'timeout', (string) max(5, min(300, (int) ($_POST['timeout'] ?? 60))));
|
||||
plugin_set_setting(VIRENSCAN, 'max_mb', (string) max(1, min(500, (int) ($_POST['max_mb'] ?? 25))));
|
||||
plugin_set_setting(VIRENSCAN, 'block_on_error', !empty($_POST['block_on_error']) ? '1' : '0');
|
||||
plugin_set_setting(VIRENSCAN, 'notify', !empty($_POST['notify']) ? '1' : '0');
|
||||
foreach (['analysis', 'block_macros', 'block_encrypted', 'block_unscannable'] as $k) plugin_set_setting(VIRENSCAN, $k, !empty($_POST[$k]) ? '1' : '0');
|
||||
plugin_set_setting(VIRENSCAN, 'vt_threshold', (string) max(1, min(30, (int) ($_POST['vt_threshold'] ?? 3))));
|
||||
$newKey = trim((string) ($_POST['vt_key'] ?? ''));
|
||||
if (!empty($_POST['vt_clear'])) plugin_set_setting(VIRENSCAN, 'vt_key', '');
|
||||
elseif ($newKey !== '') {
|
||||
if (!preg_match('/^[a-f0-9]{64}$/i', $newKey)) $error = 'Der VirusTotal-Schlüssel besteht aus 64 Zeichen (0–9, a–f).';
|
||||
else { plugin_set_setting(VIRENSCAN, 'vt_key', encrypt_secret($newKey)); plugin_set_setting(VIRENSCAN, 'vt_error', ''); }
|
||||
}
|
||||
if (!$error) $message = 'Einstellungen gespeichert.';
|
||||
}
|
||||
} elseif ($action === 'test') {
|
||||
$tmp = tempnam(sys_get_temp_dir(), 'vsc');
|
||||
file_put_contents($tmp, virenscan_eicar());
|
||||
$res = virenscan_scan_file($tmp);
|
||||
@unlink($tmp);
|
||||
$message = $res['status'] === 'infected'
|
||||
? 'Test bestanden: Die Standard-Testdatei (EICAR) wurde erkannt' . ($res['signature'] ? ' (' . $res['signature'] . ')' : '') . '.'
|
||||
: null;
|
||||
if ($message === null) $error = 'Test nicht bestanden: Die Testdatei wurde nicht erkannt (' . ($res['message'] ?? $res['status']) . ').';
|
||||
} elseif ($action === 'backlog') {
|
||||
plugin_set_setting(VIRENSCAN, 'start_id', '0');
|
||||
$message = 'Der gesamte Bestand wird jetzt nach und nach geprüft (jeweils bis zu 25 Dateien alle paar Minuten).';
|
||||
} elseif ($action === 'release') {
|
||||
$message = virenscan_release($pdo, (int) ($_POST['id'] ?? 0)) ? 'Datei freigegeben. Sie ist im Ticket wieder herunterladbar.' : null;
|
||||
if ($message === null) $error = 'Die Datei konnte nicht freigegeben werden.';
|
||||
} elseif ($action === 'delete') {
|
||||
$message = virenscan_delete($pdo, (int) ($_POST['id'] ?? 0)) ? 'Datei endgültig gelöscht.' : null;
|
||||
if ($message === null) $error = 'Die Datei konnte nicht gelöscht werden.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$cfg = virenscan_config();
|
||||
$status = virenscan_status();
|
||||
$stats = virenscan_stats($pdo);
|
||||
$labels = ['clean' => 'Sauber', 'infected' => 'Verseucht', 'error' => 'Fehler', 'skipped' => 'Übersprungen', 'blocked' => 'Gesperrt (Fehler)', 'released' => 'Freigegeben', 'deleted' => 'Gelöscht'];
|
||||
|
||||
// Reiter: Übersicht, Quarantäne (mit Anzahl), Geprüft, Einstellungen
|
||||
$tabs = ['uebersicht' => ['Übersicht', 0], 'quarantaene' => ['Quarantäne', (int) $stats['quarantined']], 'geprueft' => ['Geprüft', 0], 'einstellungen' => ['Einstellungen', 0]];
|
||||
$tab = isset($tabs[$_GET['tab'] ?? '']) ? (string) $_GET['tab'] : 'uebersicht';
|
||||
|
||||
// Geprüft: Filter und Seiten
|
||||
$filter = isset($labels[$_GET['status'] ?? '']) ? (string) $_GET['status'] : '';
|
||||
$perPage = 50;
|
||||
$pageNo = max(1, (int) ($_GET['seite'] ?? 1));
|
||||
if ($tab === 'geprueft') {
|
||||
$cnt = $pdo->prepare('SELECT COUNT(*) FROM plugin_virenscan_files' . ($filter !== '' ? ' WHERE status = ?' : ''));
|
||||
$cnt->execute($filter !== '' ? [$filter] : []);
|
||||
$totalChecked = (int) $cnt->fetchColumn();
|
||||
$pages = max(1, (int) ceil($totalChecked / $perPage));
|
||||
$pageNo = min($pageNo, $pages);
|
||||
$q = $pdo->prepare('SELECT f.*, t.ticket_number FROM plugin_virenscan_files f LEFT JOIN tickets t ON t.id = f.ticket_id' . ($filter !== '' ? ' WHERE f.status = ?' : '') . ' ORDER BY f.id DESC LIMIT ' . $perPage . ' OFFSET ' . (($pageNo - 1) * $perPage));
|
||||
$q->execute($filter !== '' ? [$filter] : []);
|
||||
$checked = $q->fetchAll();
|
||||
}
|
||||
if ($tab === 'quarantaene') {
|
||||
$quarantine = $pdo->query('SELECT f.*, t.ticket_number FROM plugin_virenscan_files f LEFT JOIN tickets t ON t.id = f.ticket_id WHERE f.quarantined = 1 ORDER BY f.id DESC LIMIT 200')->fetchAll();
|
||||
}
|
||||
?>
|
||||
<h1>Virenscan</h1>
|
||||
<?php if ($message): ?><div class="flash success"><?= e($message) ?></div><?php endif; ?>
|
||||
<?php if ($error): ?><div class="flash error"><?= e($error) ?></div><?php endif; ?>
|
||||
<?= virenscan_tabs($tab, $tabs) ?>
|
||||
|
||||
<?php if ($tab === 'uebersicht'): ?>
|
||||
<div class="card" style="max-width:820px;margin-bottom:16px">
|
||||
<h3>Zustand</h3>
|
||||
<p>
|
||||
<?php if ($cfg['analysis']): ?><strong style="color:#15803d">✓ Dateianalyse aktiv</strong><?php else: ?><strong style="color:#b45309">Dateianalyse ausgeschaltet</strong><?php endif; ?>
|
||||
· <?php if ($status['ok']): ?><strong style="color:#15803d">ClamAV bereit</strong> (<?= e($status['mode']) ?>, <?= e((string) $status['version']) ?>)<?php else: ?><span class="muted">ClamAV nicht vorhanden (optional)</span><?php endif; ?>
|
||||
· <?php if ($cfg['vt_key'] !== ''): ?><strong style="color:#15803d">✓ Hash-Abfrage aktiv</strong> (heute <?= plugin_setting(VIRENSCAN, 'vt_day', '') === date('Y-m-d') ? (int) plugin_setting(VIRENSCAN, 'vt_count', '0') : 0 ?> von 450 Abfragen)<?php else: ?><span class="muted">Hash-Abfrage aus (kein Schlüssel)</span><?php endif; ?>
|
||||
</p>
|
||||
<p class="muted" style="font-size:.88rem"><?= e($status['message']) ?></p>
|
||||
<?php if ($cfg['vt_key'] !== '' && plugin_setting(VIRENSCAN, 'vt_error', '') !== ''): ?><p style="color:#b91c1c;font-size:.88rem">Hash-Abfrage: <?= e((string) plugin_setting(VIRENSCAN, 'vt_error', '')) ?></p><?php endif; ?>
|
||||
<p style="font-size:.9rem">Geprüft: <strong><?= (int) $stats['clean'] ?></strong> sauber · <strong style="color:#b91c1c"><?= (int) $stats['infected'] ?></strong> verseucht · <strong><?= (int) $stats['error'] ?></strong> Fehler · <strong><?= (int) $stats['skipped'] ?></strong> übersprungen · in Quarantäne: <strong><?= (int) $stats['quarantined'] ?></strong></p>
|
||||
<p class="muted" style="font-size:.82rem">Letzter Hintergrundlauf: <?= e(plugin_setting(VIRENSCAN, 'last_run', '') ?: 'noch nicht') ?></p>
|
||||
<?php if ((int) $stats['quarantined'] > 0): ?><p><a class="btn" href="<?= e(virenscan_tab_url('quarantaene')) ?>"><?= (int) $stats['quarantined'] ?> Datei(en) in Quarantäne prüfen</a></p><?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="card" style="max-width:820px;margin-bottom:16px;display:flex;gap:10px;flex-wrap:wrap;align-items:center">
|
||||
<form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="test"><button type="submit" class="btn secondary">Prüfung testen (EICAR-Testdatei)</button></form>
|
||||
<form method="post" onsubmit="return confirm('Alle bisherigen Anhänge nachträglich prüfen? Das läuft im Hintergrund und kann etwas dauern.')"><?= csrf_field() ?><input type="hidden" name="action" value="backlog"><button type="submit" class="btn secondary">Bestand nachträglich prüfen</button></form>
|
||||
<span class="muted" style="font-size:.82rem">Ohne diesen Knopf werden nur Anhänge geprüft, die nach dem Einschalten des Plugins eingehen.</span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($tab === 'quarantaene'): ?>
|
||||
<div class="card" style="margin-bottom:16px">
|
||||
<h3>Quarantäne</h3>
|
||||
<?php if (!$quarantine): ?><p class="muted">Keine gesperrten Dateien. Alles in Ordnung.</p><?php else: ?>
|
||||
<table style="width:100%">
|
||||
<thead><tr><th>Datei</th><th>Fund</th><th>Ticket</th><th>Wann</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($quarantine as $q): ?>
|
||||
<tr>
|
||||
<td><?= e($q['original_name']) ?></td>
|
||||
<td><?= e((string) ($q['signature'] ?: $q['message'])) ?></td>
|
||||
<td><?php if ($q['ticket_number']): ?><a href="/staff/ticket_view.php?n=<?= e(urlencode((string) $q['ticket_number'])) ?>">#<?= e((string) $q['ticket_number']) ?></a><?php endif; ?></td>
|
||||
<td class="muted"><?= e((string) $q['scanned_at']) ?></td>
|
||||
<td style="white-space:nowrap">
|
||||
<form method="post" style="display:inline" onsubmit="return confirm('Diese Datei wirklich freigeben? Sie war als verseucht erkannt.')"><?= csrf_field() ?><input type="hidden" name="action" value="release"><input type="hidden" name="id" value="<?= (int) $q['id'] ?>"><button class="btn secondary" type="submit">Freigeben</button></form>
|
||||
<form method="post" style="display:inline" onsubmit="return confirm('Datei endgültig löschen?')"><?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int) $q['id'] ?>"><button class="btn danger" type="submit">Löschen</button></form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($tab === 'geprueft'): ?>
|
||||
<div class="card">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:8px">
|
||||
<h3 style="margin:0">Geprüfte Dateien <span class="muted" style="font-weight:400;font-size:.85rem">(<?= (int) $totalChecked ?><?= $filter !== '' ? ' mit Ergebnis „' . e($labels[$filter]) . '“' : '' ?>)</span></h3>
|
||||
<form method="get" style="display:flex;gap:6px;align-items:center">
|
||||
<input type="hidden" name="p" value="<?= e(VIRENSCAN) ?>"><input type="hidden" name="page" value="virenscan"><input type="hidden" name="tab" value="geprueft">
|
||||
<select name="status" onchange="this.form.submit()">
|
||||
<option value="">Alle Ergebnisse</option>
|
||||
<?php foreach ($labels as $k => $l): ?><option value="<?= e($k) ?>" <?= $filter === $k ? 'selected' : '' ?>><?= e($l) ?> (<?= (int) ($stats[$k] ?? 0) ?>)</option><?php endforeach; ?>
|
||||
</select>
|
||||
<noscript><button class="btn secondary" type="submit">Filtern</button></noscript>
|
||||
</form>
|
||||
</div>
|
||||
<?php if (!$checked): ?><p class="muted">Keine Einträge.</p><?php else: ?>
|
||||
<table style="width:100%"><thead><tr><th>Datei</th><th>Ergebnis</th><th>Hinweis</th><th>Ticket</th><th>Wann</th></tr></thead><tbody>
|
||||
<?php foreach ($checked as $r): ?>
|
||||
<tr>
|
||||
<td><?= e($r['original_name']) ?></td>
|
||||
<td><?= e($labels[$r['status']] ?? $r['status']) ?></td>
|
||||
<td class="muted"><?= e((string) ($r['signature'] ?: $r['message'])) ?></td>
|
||||
<td><?php if ($r['ticket_number']): ?><a href="/staff/ticket_view.php?n=<?= e(urlencode((string) $r['ticket_number'])) ?>">#<?= e((string) $r['ticket_number']) ?></a><?php endif; ?></td>
|
||||
<td class="muted"><?= e((string) $r['scanned_at']) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody></table>
|
||||
<?php if ($pages > 1): ?>
|
||||
<div style="display:flex;gap:6px;align-items:center;margin-top:12px;font-size:.88rem">
|
||||
<?php if ($pageNo > 1): ?><a class="btn secondary" href="<?= e(virenscan_tab_url('geprueft', ['status' => $filter, 'seite' => $pageNo - 1])) ?>">← Neuere</a><?php endif; ?>
|
||||
<span class="muted">Seite <?= (int) $pageNo ?> von <?= (int) $pages ?></span>
|
||||
<?php if ($pageNo < $pages): ?><a class="btn secondary" href="<?= e(virenscan_tab_url('geprueft', ['status' => $filter, 'seite' => $pageNo + 1])) ?>">Ältere →</a><?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($tab === 'einstellungen'): ?>
|
||||
<form method="post" class="card" style="max-width:820px;margin-bottom:16px">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="save">
|
||||
<h3>Einstellungen</h3>
|
||||
<h4 style="margin:6px 0 4px">Dateianalyse (braucht nichts auf dem Server)</h4>
|
||||
<p class="muted" style="font-size:.82rem">Sperrt Programme und Skripte (.exe, .js, .bat …), getarnte Dateien (zum Beispiel ein Programm als .pdf), doppelte Endungen, PDFs mit automatischem JavaScript, HTML/SVG mit Skripten und Archive mit solchen Dateien. Sie erkennt keine <em>neuen</em> Viren, die wie normale Dokumente aussehen; dafür dient die Hash-Abfrage unten oder ClamAV.</p>
|
||||
<label style="display:block"><input type="checkbox" name="analysis" value="1" <?= $cfg['analysis'] ? 'checked' : '' ?>> Dateianalyse einschalten</label>
|
||||
<label style="display:block"><input type="checkbox" name="block_macros" value="1" <?= $cfg['block_macros'] ? 'checked' : '' ?>> Office-Dateien mit Makros sperren (Word, Excel, PowerPoint)</label>
|
||||
<label style="display:block"><input type="checkbox" name="block_encrypted" value="1" <?= $cfg['block_encrypted'] ? 'checked' : '' ?>> Passwortgeschützte ZIP-Dateien sperren (Inhalt lässt sich nicht prüfen)</label>
|
||||
<label style="display:block"><input type="checkbox" name="block_unscannable" value="1" <?= $cfg['block_unscannable'] ? 'checked' : '' ?>> RAR-, 7z- und ähnliche Archive sperren (lassen sich nicht öffnen)</label>
|
||||
|
||||
<h4 style="margin:16px 0 4px">Hash-Abfrage bei VirusTotal (optional, kostenlos)</h4>
|
||||
<p class="muted" style="font-size:.82rem">Es wird nur der Fingerabdruck (SHA-256) einer Datei gesendet, nie die Datei selbst oder Ticketinhalte. So werden bekannte Schadprogramme auch erkannt, wenn sie wie ein normales Dokument aussehen. Läuft im Hintergrund (höchstens 4 Abfragen pro Lauf, 450 pro Tag), die Sperre kann also einige Minuten nach dem Eingang kommen. Den kostenlosen Schlüssel gibt es nach der Anmeldung bei virustotal.com unter „API key“; die kostenlose Nutzung ist laut VirusTotal nicht für den gewerblichen Einsatz gedacht.</p>
|
||||
<label for="vt_key">API-Schlüssel <?= $cfg['vt_key'] !== '' ? '– gespeichert, leer lassen zum Behalten' : '' ?></label>
|
||||
<input type="password" id="vt_key" name="vt_key" value="" autocomplete="new-password">
|
||||
<?php if ($cfg['vt_key'] !== ''): ?><label style="font-size:.82rem"><input type="checkbox" name="vt_clear" value="1"> Schlüssel entfernen und Abfrage ausschalten</label><?php endif; ?>
|
||||
<div style="margin-top:8px"><label for="vt_threshold">Sperren ab so vielen Scannern, die Schadsoftware melden</label><input type="number" id="vt_threshold" name="vt_threshold" min="1" max="30" value="<?= (int) $cfg['vt_threshold'] ?>" style="max-width:120px"></div>
|
||||
|
||||
<h4 style="margin:16px 0 4px">ClamAV (optional, nur wenn schon auf dem Server vorhanden)</h4>
|
||||
<label for="mode">Prüfprogramm</label>
|
||||
<select id="mode" name="mode">
|
||||
<option value="auto" <?= $cfg['mode'] === 'auto' ? 'selected' : '' ?>>Automatisch (clamdscan, sonst clamscan, sonst nur Dateianalyse)</option>
|
||||
<option value="clamdscan" <?= $cfg['mode'] === 'clamdscan' ? 'selected' : '' ?>>clamdscan (ClamAV-Dienst, schnell)</option>
|
||||
<option value="clamscan" <?= $cfg['mode'] === 'clamscan' ? 'selected' : '' ?>>clamscan (einzelnes Programm, langsamer)</option>
|
||||
<option value="builtin" <?= $cfg['mode'] === 'builtin' ? 'selected' : '' ?>>Kein ClamAV verwenden</option>
|
||||
</select>
|
||||
<label for="binary" style="margin-top:10px">Eigener Pfad zum Programm (optional)</label>
|
||||
<input type="text" id="binary" name="binary" value="<?= e($cfg['binary']) ?>" placeholder="/usr/bin/clamdscan">
|
||||
<div style="display:flex;gap:14px;margin-top:10px;flex-wrap:wrap">
|
||||
<div><label for="timeout">Zeitlimit je Datei (Sekunden)</label><input type="number" id="timeout" name="timeout" min="5" max="300" value="<?= (int) $cfg['timeout'] ?>" style="max-width:140px"></div>
|
||||
<div><label for="max_mb">Größere Dateien nicht prüfen (MB)</label><input type="number" id="max_mb" name="max_mb" min="1" max="500" value="<?= (int) $cfg['max_mb'] ?>" style="max-width:140px"></div>
|
||||
</div>
|
||||
<label style="display:block;margin-top:10px"><input type="checkbox" name="block_on_error" value="1" <?= $cfg['block_on_error'] ? 'checked' : '' ?>> Datei sperren, wenn die Prüfung fehlschlägt (sicherer, kann aber auch saubere Dateien sperren)</label>
|
||||
<label style="display:block"><input type="checkbox" name="notify" value="1" <?= $cfg['notify'] ? 'checked' : '' ?>> E-Mail an den Administrator, wenn eine Datei gesperrt wird</label>
|
||||
<div class="btn-row"><button type="submit" class="btn">Speichern</button></div>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"slug": "virenscan",
|
||||
"name": "Anhänge-Virenscan",
|
||||
"version": "1.2.0",
|
||||
"description": "Prüft Anhänge von Tickets und sperrt gefährliche Dateien, bevor ein Mitarbeiter sie öffnet. Eingebaute Dateianalyse ohne Installation auf dem Server (Programme, Skripte, getarnte Dateien, Makros, PDF-Tricks, Archive), optionale Hash-Abfrage bei VirusTotal und ClamAV, falls vorhanden. Gesperrte Dateien liegen in Quarantäne und lassen sich freigeben oder löschen. Nur für Administratoren.",
|
||||
"author": "DeskHub",
|
||||
"requires": "1.0.0",
|
||||
"permissions": ["hooks.tickets", "hooks.cron", "ui.menu", "db.migrations"]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
// Virenscan-Plugin: prüft Anhänge neuer Tickets und Antworten mit ClamAV, den Rest nebenbei im Hintergrund.
|
||||
require_once __DIR__ . '/lib.php';
|
||||
virenscan_ensure_schema();
|
||||
|
||||
foreach (['ticket.created', 'ticket.replied'] as $hook) {
|
||||
plugin_add_hook($hook, function (array $payload) {
|
||||
if (!empty($payload['ticketId'])) virenscan_scan_ticket(get_db(), (int) $payload['ticketId']);
|
||||
});
|
||||
}
|
||||
plugin_add_hook('cron.run', function () {
|
||||
virenscan_tick(get_db());
|
||||
});
|
||||
|
||||
// Seite im Adminportal, nur für Administratoren (die Seite prüft das zusätzlich selbst)
|
||||
plugin_register_menu('Virenscan', 'virenscan', null, 'admin');
|
||||
Reference in New Issue
Block a user