Sicherheitsupdate nach Audit (0.29.0)
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 7m50s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 7m34s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 5m45s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 5m30s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 7m7s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 7m9s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 6m8s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 6m5s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 48s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m5s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 11:34:54 +00:00
parent a37895a16a
commit f1202bea08
226 changed files with 1952 additions and 450 deletions

View file

@ -19,6 +19,11 @@ class Audit
{
$userId ??= auth()->id();
// Bei „Als Person anmelden“: wer tatsächlich gehandelt hat
if (app()->bound('session') && session()->isStarted() && ($impersonator = session()->get(Impersonation::SESSION))) {
$data['impersonator_id'] = (int) $impersonator;
}
Log::info("audit: {$action}", [...$data, 'user_id' => $userId]);
try {

View file

@ -0,0 +1,16 @@
<?php
namespace App\Support;
/**
* Dateitypen, die nirgends hochgeladen werden dürfen (ausführbar, Skripte, Webseiten).
* Eine Liste für alle Upload-Stellen (Seiten, Downloads …).
*/
final class BlockedFiles
{
public const EXTENSIONS = [
'php', 'phtml', 'phar', 'php3', 'php4', 'php5', 'php7', 'php8', 'pht', 'shtml', 'htaccess',
'exe', 'bat', 'cmd', 'com', 'sh', 'msi', 'ps1', 'psm1', 'vbs', 'vbe', 'wsf', 'wsh', 'scr', 'hta', 'jar', 'lnk', 'reg', 'cpl',
'js', 'mjs', 'html', 'htm', 'svg', 'xhtml', 'jsp', 'asp', 'aspx', 'cgi', 'pl', 'py',
];
}

29
app/Support/Csv.php Normal file
View file

@ -0,0 +1,29 @@
<?php
namespace App\Support;
/**
* Hilfen für CSV-Exporte, die in Excel/LibreOffice geöffnet werden.
*/
final class Csv
{
/**
* Zelle gegen Formel-Einschleusung schützen: Werte, die mit = + - @ Tab oder
* Zeilenumbruch beginnen, würden sonst als Formel ausgeführt.
*/
public static function cell(mixed $value): string
{
$value = (string) ($value ?? '');
return preg_match('/^[=+\-@\t\r]/', $value) ? "'".$value : $value;
}
/**
* @param list<mixed> $row
* @return list<string>
*/
public static function row(array $row): array
{
return array_map(self::cell(...), $row);
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Support;
use RuntimeException;
/**
* Bild mit zu vielen Pixeln – wird vor dem Entpacken abgelehnt (Schutz vor
* „Dekompressionsbomben“, die den Arbeitsspeicher des Servers füllen).
*/
class ImageTooLarge extends RuntimeException
{
public function __construct()
{
parent::__construct('Das Bild ist zu groß (höchstens '.(Images::MAX_PIXELS / 1_000_000).' Megapixel). Bitte verkleinern und erneut hochladen.');
}
}

View file

@ -19,6 +19,12 @@ use Throwable;
*/
class Images
{
/** Höchstens so viele Pixel (50 MP ≈ 8.660 × 5.770) – größere Bilder werden abgelehnt */
public const MAX_PIXELS = 50_000_000;
/** Obergrenze für das angehobene Speicherlimit der Bildverarbeitung */
private const MAX_MEMORY = 1024 * 1024 * 1024;
public const VARIANTS = [
'thumb' => [480, 270],
'large' => [1600, 900],
@ -206,6 +212,12 @@ class Images
public static function raiseMemoryLimitFor(string $file): void
{
$size = @getimagesize($file);
// Pixelzahl aus dem Dateikopf prüfen, bevor GD das Bild entpackt
if ($size && $size[0] * $size[1] > self::MAX_PIXELS) {
throw new ImageTooLarge;
}
$needed = $size ? (int) ($size[0] * $size[1] * 4 * 1.8) : 0;
$current = self::bytes((string) ini_get('memory_limit'));
@ -213,7 +225,7 @@ class Images
return;
}
$target = max(256 * 1024 * 1024, memory_get_usage() + $needed);
$target = min(self::MAX_MEMORY, max(256 * 1024 * 1024, memory_get_usage() + $needed));
if ($current < $target) {
@ini_set('memory_limit', (string) $target);

View file

@ -45,6 +45,14 @@ class Impersonation
return null;
}
// Zwischenzeitlich deaktiviert? Dann nicht zurückwechseln, sondern ganz abmelden.
if (! $original->is_active) {
session()->forget(self::SESSION);
Auth::guard('web')->logout();
return null;
}
$target = Auth::user();
session()->forget(self::SESSION);
$this->switchTo($original);

View file

@ -2,7 +2,10 @@
namespace App\Support;
use App\Models\Role;
use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Installationsstatus und Vorbereitung für den Web-Installer.
@ -17,7 +20,28 @@ class Installation
return filter_var($forced, FILTER_VALIDATE_BOOL);
}
return is_file(storage_path('.installed')) || app()->environment('local');
if (is_file(storage_path('.installed')) || app()->environment('local')) {
return true;
}
// Markierung verloren (z. B. storage/ nach einem Umzug nicht mitkopiert)? Gibt es bereits
// ein Administrationskonto, ist das Portal eingerichtet – der Installer darf nie wieder öffnen.
static $checked = null;
if ($checked === null) {
try {
$checked = Schema::hasTable('role_user')
&& DB::table('role_user')->join('roles', 'roles.id', '=', 'role_user.role_id')->where('roles.slug', Role::ADMINISTRATION)->exists();
} catch (\Throwable) {
$checked = false; // noch keine Datenbank eingerichtet
}
if ($checked) {
@self::markInstalled();
}
}
return $checked;
}
public static function markInstalled(): void

View file

@ -4,6 +4,7 @@ namespace App\Support;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\ValidationException;
use Throwable;
/**
@ -57,7 +58,15 @@ class MailSettings
'mail.from_name' => $values['from_name'] ?? null,
];
// Leeres Passwortfeld = gespeichertes behalten.
// Leeres Passwortfeld = gespeichertes behalten – aber nur, solange Server und Benutzer gleich bleiben.
// Sonst könnte, wer die Einstellungen ändern darf, das gespeicherte Passwort an einen eigenen Server schicken.
$destinationChanged = collect(['host' => 'mail.host', 'port' => 'mail.port', 'username' => 'mail.username'])
->contains(fn ($key, $field) => (string) ($values[$field] ?? '') !== (string) ($this->settings->get($key) ?? ''));
if (blank($values['password'] ?? null) && $destinationChanged && $this->settings->get('mail.password') && ($values['mailer'] ?? null) === 'smtp') {
throw ValidationException::withMessages(['data.password' => 'Server oder Benutzer wurden geändert – bitte das Passwort erneut eingeben.']);
}
if (filled($values['password'] ?? null)) {
$data['mail.password'] = Crypt::encryptString($values['password']);
}

View file

@ -0,0 +1,44 @@
<?php
namespace App\Support\Permissions;
use App\Models\Role;
use App\Models\User;
/**
* Schutz vor Rechte-Ausweitung: Wer keinen Vollzugriff hat, darf nur Rollen vergeben
* bzw. Rechte eintragen, die er selbst besitzt – nie „Administration“.
*/
final class RoleGuard
{
public static function canAssign(?User $actor, Role $role): bool
{
if (! $actor) {
return false;
}
if ($actor->permissions()->isSuperuser()) {
return true;
}
if ($role->isAdministration() || $role->grants()->where('ability', '*')->exists()) {
return false;
}
return $role->grants()->whereNull('resource_type')->pluck('ability')
->every(fn (string $ability) => $actor->can($ability));
}
public static function canGrant(?User $actor, string $ability): bool
{
return $actor !== null && ($actor->permissions()->isSuperuser() || ($ability !== '*' && $actor->can($ability)));
}
/**
* Konten mit Vollzugriff bearbeiten (Passwort, E-Mail, Rollen, Löschen) nur mit eigenem Vollzugriff.
*/
public static function canManageUser(?User $actor, User $target): bool
{
return $actor !== null && ($actor->permissions()->isSuperuser() || ! $target->permissions()->isSuperuser());
}
}

View file

@ -14,6 +14,9 @@ use Throwable;
*/
class ProfileFields
{
/** Dürfen Mitarbeitende Abteilung und Standort selbst ändern? (Standard: nein – steuern Sichtbarkeit) */
public const SELF_EDIT_ORG = 'profile.self_edit_org';
private const CACHE_KEY = 'profile-fields';
/** @var Collection<int, ProfileField>|null */

View file

@ -0,0 +1,94 @@
<?php
namespace App\Support;
use Psr\Http\Message\UriInterface;
use RuntimeException;
/**
* Ausgehende Anfragen an Adressen, die aus Inhalten oder Einstellungen stammen:
* nie an interne Ziele (localhost, private Netze, Link-Local, Metadaten-Dienste) –
* auch nicht über Weiterleitungen (Schutz vor SSRF).
*/
final class SafeOutbound
{
/** @var array<string, list<string>> nur für Tests: feste Auflösung statt DNS */
private static array $fakeHosts = [];
/**
* @param array<string, string|list<string>> $hosts
*/
public static function fakeResolve(array $hosts): void
{
self::$fakeHosts = array_map(fn ($ips) => (array) $ips, $hosts);
}
/**
* @param list<string> $schemes
*/
public static function isPublicUrl(string $url, array $schemes = ['https', 'http']): bool
{
$parts = parse_url($url);
$scheme = strtolower((string) ($parts['scheme'] ?? ''));
$host = strtolower(trim((string) ($parts['host'] ?? ''), '[]'));
if (! in_array($scheme, $schemes, true) || $host === '' || isset($parts['user']) || in_array($host, ['localhost', 'localhost.localdomain'], true) || str_ends_with($host, '.localhost') || str_ends_with($host, '.internal') || str_ends_with($host, '.local')) {
return false;
}
$ips = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : self::resolve($host);
if ($ips === []) {
return false;
}
foreach ($ips as $ip) {
if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return false;
}
}
return true;
}
/**
* Optionen für den HTTP-Client: höchstens 3 Weiterleitungen, jede wird erneut geprüft.
*
* @param list<string> $schemes
* @return array<string, mixed>
*/
public static function options(array $schemes = ['https', 'http']): array
{
return [
'allow_redirects' => [
'max' => 3,
'protocols' => $schemes,
'on_redirect' => function ($request, $response, UriInterface $uri) use ($schemes) {
if (! self::isPublicUrl((string) $uri, $schemes)) {
throw new RuntimeException('Weiterleitung auf eine nicht erlaubte Adresse.');
}
},
],
];
}
/**
* @return list<string>
*/
private static function resolve(string $host): array
{
if (isset(self::$fakeHosts[$host])) {
return self::$fakeHosts[$host];
}
$ips = [];
foreach ([DNS_A, DNS_AAAA] as $type) {
foreach (@dns_get_record($host, $type) ?: [] as $record) {
$ips[] = $record['ip'] ?? $record['ipv6'] ?? null;
}
}
return array_values(array_filter($ips));
}
}

View file

@ -41,17 +41,20 @@ final class SvgSanitizer
$xpath = new DOMXPath($dom);
foreach (iterator_to_array($xpath->query('//*[local-name()="script" or local-name()="foreignObject" or local-name()="iframe" or local-name()="object" or local-name()="embed"]')) as $node) {
// Auch Animationen (set/animate) – sie können Links nachträglich auf javascript: setzen.
foreach (iterator_to_array($xpath->query('//*[local-name()="script" or local-name()="foreignObject" or local-name()="iframe" or local-name()="object" or local-name()="embed" or local-name()="set" or starts-with(local-name(), "animate") or local-name()="handler" or local-name()="listener"]')) as $node) {
$node->parentNode->removeChild($node);
}
foreach (iterator_to_array($xpath->query('//*')) as $element) {
/** @var DOMElement $element */
foreach (iterator_to_array($element->attributes) as $attribute) {
$name = strtolower($attribute->nodeName);
$name = strtolower($attribute->localName ?? $attribute->nodeName);
$value = strtolower(preg_replace('/\s+/', '', $attribute->nodeValue));
if (str_starts_with($name, 'on') || (in_array($name, ['href', 'xlink:href', 'src'], true) && ! str_starts_with($value, '#') && ! str_starts_with($value, 'data:image/'))) {
$dangerous = str_contains($value, 'javascript:') || str_contains($value, 'vbscript:') || str_contains($value, 'data:text') || str_contains($value, 'expression(');
if (str_starts_with($name, 'on') || $dangerous || (in_array($name, ['href', 'src'], true) && ! str_starts_with($value, '#') && ! str_starts_with($value, 'data:image/'))) {
$element->removeAttributeNode($attribute);
}
}

View file

@ -2,6 +2,7 @@
namespace App\Support\Theme;
use App\Pagebuilder\Field;
use App\Support\Settings;
use Illuminate\Support\Arr;
@ -106,8 +107,9 @@ class Theme
{
$theme = self::normalize([...$this->working(), ...$values]);
foreach (['logo_light', 'logo_dark', 'logo_mark'] as $logo) {
SvgSanitizer::sanitizeFile($theme[$logo]);
// Alle Bildfelder – jedes könnte eine SVG-Datei sein
foreach (['logo_light', 'logo_dark', 'logo_mark', 'app_icon', 'login_image', 'profile_cover', 'avatar_placeholder'] as $image) {
SvgSanitizer::sanitizeFile($theme[$image]);
}
$this->settings->set(self::DRAFT, $theme);
@ -161,8 +163,9 @@ class Theme
$theme['profile_cover_overlay'] = array_key_exists((int) $theme['profile_cover_overlay'], self::COVER_OVERLAYS) ? (int) $theme['profile_cover_overlay'] : 70;
$theme['login_layout'] = array_key_exists($theme['login_layout'], self::LOGIN_LAYOUTS) ? $theme['login_layout'] : 'split';
$theme['footer_links'] = array_values(array_filter(array_map(
fn ($link) => is_array($link) && filled($link['label'] ?? null) && filled($link['url'] ?? null)
? ['label' => mb_substr(trim($link['label']), 0, 60), 'url' => mb_substr(trim($link['url']), 0, 500)]
// Nur sichere Adressen (kein javascript:, auch nicht aus importierten Themes)
fn ($link) => is_array($link) && filled($link['label'] ?? null) && ($url = Field::safeUrl(mb_substr(trim((string) ($link['url'] ?? '')), 0, 500))) !== ''
? ['label' => mb_substr(trim($link['label']), 0, 60), 'url' => $url]
: null,
(array) $theme['footer_links'],
)));

View file

@ -29,6 +29,7 @@ class ZipExtractor
}
try {
self::checkLimits($zip);
$this->recreate($targetDir);
$root = realpath($targetDir);
$prefix = $this->commonPrefix($zip);
@ -143,4 +144,35 @@ class ZipExtractor
throw new RuntimeException("Verzeichnis {$dir} kann nicht angelegt werden. Bitte Schreibrechte prüfen.");
}
}
/** Grenzen gegen „ZIP-Bomben“ (ein Inhaus-Update entpackt heute ~17.000 Dateien, ~70 MB) */
public const MAX_ENTRIES = 60_000;
public const MAX_TOTAL_BYTES = 800 * 1024 * 1024;
public const MAX_RATIO = 200;
private static function checkLimits(ZipArchive $zip): void
{
if ($zip->numFiles > self::MAX_ENTRIES) {
throw new RuntimeException('Das Archiv enthält zu viele Dateien.');
}
$total = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
$size = (int) ($stat['size'] ?? 0);
$total += $size;
// Stark komprimierte große Einträge sind verdächtig
if ($size > 10 * 1024 * 1024 && $size > max(1, (int) ($stat['comp_size'] ?? 0)) * self::MAX_RATIO) {
throw new RuntimeException('Das Archiv enthält eine ungewöhnlich stark komprimierte Datei und wurde abgelehnt.');
}
if ($total > self::MAX_TOTAL_BYTES) {
throw new RuntimeException('Das Archiv ist entpackt zu groß.');
}
}
}
}