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

@ -21,6 +21,11 @@ class ResetUserPassword implements ResetsUserPasswords
*/
public function reset(User $user, array $input): void
{
// Konten, die sich nur über einen Anmeldedienst anmelden, bekommen kein lokales Passwort
if (! $user->is_active || ($user->password === null && $user->identities()->exists())) {
throw ValidationException::withMessages(['email' => trans('passwords.token')]);
}
Validator::make($input, [
'password' => $this->passwordRules(),
])->validate();
@ -28,5 +33,8 @@ class ResetUserPassword implements ResetsUserPasswords
$user->forceFill([
'password' => Hash::make($input['password']),
])->save();
// Bisherige Sitzungen und App-Zugänge beenden
$user->revokeAccess();
}
}

View file

@ -31,5 +31,8 @@ class UpdateUserPassword implements UpdatesUserPasswords
$user->forceFill([
'password' => Hash::make($input['password']),
])->save();
// Andere Geräte abmelden, App-Zugänge widerrufen – diese Sitzung bleibt
$user->revokeAccess(keepCurrentSession: true);
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace App\Filament\Components;
use Filament\Forms\Components\FileUpload;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
/**
* Uploads in den öffentlichen Ordner (public/uploads): nur bestimmte Dateitypen, und
* die Dateiendung ergibt sich aus dem geprüften Inhalt – nie aus dem Namen der
* hochgeladenen Datei (sonst ließe sich z. B. „bild.html“ oder „bild.php“ ablegen).
*/
final class SafeUpload
{
public const IMAGES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
public const EXTENSIONS = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
'image/gif' => 'gif',
'image/svg+xml' => 'svg',
'image/x-icon' => 'ico',
'image/vnd.microsoft.icon' => 'ico',
'font/woff2' => 'woff2',
'application/font-woff2' => 'woff2',
];
/**
* @param list<string> $types erlaubte MIME-Typen
*/
public static function apply(FileUpload $upload, array $types = self::IMAGES, ?string $forcedExtension = null): FileUpload
{
return $upload
->acceptedFileTypes($types)
->getUploadedFileNameForStorageUsing(fn (TemporaryUploadedFile $file) => self::name($file, $forcedExtension));
}
public static function name(TemporaryUploadedFile $file, ?string $forcedExtension = null): string
{
$extension = $forcedExtension ?? self::EXTENSIONS[strtolower((string) $file->getMimeType())] ?? 'bin';
return Str::ulid().'.'.$extension;
}
}

View file

@ -3,6 +3,7 @@
namespace App\Filament\Pages\Appearance;
use App\Filament\Clusters\AppearanceCluster;
use App\Filament\Components\SafeUpload;
use App\Support\Audit;
use App\Support\Branding;
use App\Support\Theme\Contrast;
@ -45,7 +46,7 @@ abstract class AppearancePage extends Page
protected static function image(string $name, string $label, string $help): FileUpload
{
return FileUpload::make($name)->label($label)->helperText($help)
return SafeUpload::apply(FileUpload::make($name), [...SafeUpload::IMAGES, 'image/svg+xml'])->label($label)->helperText($help)
->disk('uploads')->directory('theme')->visibility('public')->maxSize(4096);
}

View file

@ -2,6 +2,7 @@
namespace App\Filament\Pages\Appearance;
use App\Filament\Components\SafeUpload;
use App\Support\Theme\Fonts;
use App\Support\Theme\Theme;
use BackedEnum;
@ -32,6 +33,7 @@ class AppearanceTypography extends AppearancePage
->helperText('Z. B. die Hausschrift aus dem Corporate Design. Wird lokal ausgeliefert – keine Verbindung zu Google oder anderen Diensten. Bitte die Lizenz für die Nutzung im Web beachten.')
->disk('uploads')->directory('theme/fonts')->visibility('public')->maxSize(2048)
->acceptedFileTypes(['font/woff2', 'application/font-woff2', 'application/octet-stream'])
->getUploadedFileNameForStorageUsing(fn ($file) => SafeUpload::name($file, 'woff2'))
->rule('extensions:woff2')->live()->columnSpanFull(),
Radio::make('radius')->label('Ecken')->options(collect(Theme::RADII)->map(fn ($r) => $r[0])->all())->inline()->required(),
Radio::make('density')->label('Abstände')->options(collect(Theme::DENSITIES)->map(fn ($d) => $d[0])->all())->inline()->required(),

View file

@ -4,6 +4,7 @@ namespace App\Filament\Resources\DashboardTiles;
use App\Filament\Clusters\HomepageCluster;
use App\Filament\Components\AudienceSection;
use App\Filament\Components\SafeUpload;
use App\Filament\Resources\DashboardTiles\Pages\ManageDashboardTiles;
use App\Models\DashboardTile;
use BackedEnum;
@ -60,7 +61,7 @@ class DashboardTileResource extends Resource
->helperText('Die Reihenfolge innerhalb des Bereichs legen Sie unter „Startseite“ fest.'),
TextInput::make('title')->label(fn (Get $get) => $get('type') === 'image' ? 'Bildunterschrift (optional)' : 'Überschrift')->maxLength(150),
FileUpload::make('image_path')->label('Bild')->image()->disk('uploads')->directory('dashboard')->visibility('public')
SafeUpload::apply(FileUpload::make('image_path'))->label('Bild')->image()->disk('uploads')->directory('dashboard')->visibility('public')
->maxSize(8 * 1024)->required($type('image'))->visible($type('image'))->columnSpanFull()
->helperText('Für die Seitenleiste z. B. 800 × 600 Pixel, für „ganz oben“ ein breites Banner (z. B. 2400 × 500).'),
TextInput::make('alt')->label('Alternativtext')->maxLength(200)->visible($type('image'))->helperText('Beschreibt das Bild für Screenreader.'),

View file

@ -339,6 +339,9 @@ class IdentityProviderResource extends Resource
->schema([
Toggle::make('config.auto_provision')->label('Konto bei erster Anmeldung anlegen')->default(true),
Toggle::make('config.link_by_email')->label('Bestehende Konten über die E-Mail-Adresse verknüpfen')->default(true),
Toggle::make('config.trust_email')->label('E-Mail-Adressen dieses Anbieters sind geprüft')
->helperText('Nur einschalten, wenn niemand beim Anbieter seine E-Mail-Adresse selbst ändern kann. Sonst werden Konten mit Passwort oder Administrationsrechten nicht automatisch verknüpft (Schutz vor Kontoübernahme).')
->visible(fn ($get) => ($get('type') ?? null) !== 'entra'),
TagsInput::make('config.allowed_domains')->label('Erlaubte E-Mail-Domains')->placeholder('firma.de')
->helperText('Leer = alle Konten des Anbieters.'),
Select::make('config.default_role_id')->label('Standardrolle für alle')

View file

@ -9,6 +9,7 @@ use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Icons\Heroicon;
use Illuminate\Validation\ValidationException;
class EditIdentityProvider extends EditRecord
{
@ -38,8 +39,16 @@ class EditIdentityProvider extends EditRecord
*/
protected function mutateFormDataBeforeSave(array $data): array
{
$destinationChanged = collect($this->record->driver()?->destinationFields() ?? [])
->contains(fn (string $field) => (string) ($data['config'][$field] ?? '') !== (string) ($this->record->setting($field) ?? ''));
foreach ($this->secretFields() as $field) {
if (blank($data['config'][$field] ?? null)) {
// Gespeichertes Geheimnis nur für dasselbe Ziel weiterverwenden
if ($destinationChanged && filled($this->record->setting($field))) {
throw ValidationException::withMessages(["data.config.{$field}" => 'Server bzw. Aussteller wurden geändert – bitte das Geheimnis erneut eingeben.']);
}
$data['config'][$field] = $this->record->setting($field);
}
}

View file

@ -3,8 +3,15 @@
namespace App\Filament\Resources\ProfileFields\Pages;
use App\Filament\Resources\ProfileFields\ProfileFieldResource;
use App\Support\Audit;
use App\Support\ProfileFields;
use App\Support\Settings;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ManageRecords;
use Filament\Support\Icons\Heroicon;
class ManageProfileFields extends ManageRecords
{
@ -13,6 +20,18 @@ class ManageProfileFields extends ManageRecords
protected function getHeaderActions(): array
{
return [
Action::make('settings')->label('Selbst pflegen')->icon(Heroicon::OutlinedCog6Tooth)->color('gray')
->modalHeading('Was Mitarbeitende selbst ändern dürfen')
->fillForm(fn () => ['self_edit_org' => (bool) app(Settings::class)->get(ProfileFields::SELF_EDIT_ORG, false)])
->schema([
Toggle::make('self_edit_org')->label('Abteilung und Standort selbst ändern')
->helperText('Vorsicht: Abteilung und Standort bestimmen, wer welche Inhalte sieht (Zielgruppen). Wer sie selbst ändern darf, kann sich so Zugang zu Inhalten anderer Abteilungen verschaffen. Die E-Mail-Adresse ändert immer die Administration unter „Benutzer“.'),
])
->action(function (array $data) {
app(Settings::class)->set(ProfileFields::SELF_EDIT_ORG, (bool) $data['self_edit_org']);
Audit::log('profile.self_edit_org', ['enabled' => (bool) $data['self_edit_org']]);
Notification::make()->success()->title('Gespeichert')->send();
}),
CreateAction::make()->label('Profilfeld anlegen'),
];
}

View file

@ -10,6 +10,7 @@ use App\Models\Role;
use App\Models\User;
use App\Support\Abilities;
use App\Support\Permissions\Permissions;
use App\Support\Permissions\RoleGuard;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
@ -71,6 +72,19 @@ class RoleResource extends Resource
->options(fn () => collect($abilities->global())->map(fn (array $a) => $a['label'])->all())
->descriptions(fn () => collect($abilities->global())->map(fn (array $a) => $a['group'].($a['portal'] ? ' · im Portal' : ' · Backend'))->all())
->bulkToggleable()
// Nur Rechte eintragen, die man selbst besitzt
->disableOptionWhen(fn (string $value) => ! RoleGuard::canGrant(auth()->user(), $value))
->rule(fn (?Role $record) => function (string $attribute, mixed $value, \Closure $fail) use ($record) {
$before = $record?->grants()->whereNull('resource_type')->pluck('ability')->all() ?? [];
foreach (array_merge(array_diff((array) $value, $before), array_diff($before, (array) $value)) as $ability) {
if (! RoleGuard::canGrant(auth()->user(), (string) $ability)) {
$fail('Sie können nur Rechte vergeben oder entziehen, die Sie selbst haben.');
return;
}
}
})
->afterStateHydrated(fn (CheckboxList $component, ?Role $record) => $component->state(
$record?->grants()->whereNull('resource_type')->pluck('ability')->all() ?? []
))
@ -164,6 +178,12 @@ class RoleResource extends Resource
$record?->users()->wherePivot('source', 'manual')->pluck('users.id')->all() ?? []
))
->rule(fn (?Role $record) => function (string $attribute, mixed $value, \Closure $fail) use ($record) {
$before = $record?->users()->wherePivot('source', 'manual')->pluck('users.id')->all() ?? [];
if ($record && array_diff(array_map('intval', (array) $value), $before) && ! RoleGuard::canAssign(auth()->user(), $record)) {
$fail('Diese Rolle enthält Rechte, die Sie selbst nicht haben – Sie können keine Personen hinzufügen.');
}
if ($record?->isAdministration() && ! in_array(auth()->id(), array_map('intval', (array) $value), true)) {
$fail('Sie können sich nicht selbst aus der Rolle „Administration“ entfernen.');
}

View file

@ -5,6 +5,7 @@ namespace App\Filament\Resources\Users\Schemas;
use App\Models\ProfileField;
use App\Models\Role;
use App\Models\User;
use App\Support\Permissions\RoleGuard;
use App\Support\ProfileFields;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
@ -104,12 +105,23 @@ class UserForm
->multiple()
->preload()
->options(fn () => Role::query()->orderByDesc('is_system')->orderBy('name')->pluck('name', 'id')->all())
// Nur Rollen, deren Rechte man selbst besitzt (nie „Administration“ ohne Vollzugriff)
->disableOptionWhen(fn (string $value) => ! RoleGuard::canAssign(auth()->user(), Role::query()->findOrFail((int) $value)))
->afterStateHydrated(function (Select $component, ?User $record) {
$component->state($record?->roles()->wherePivot('source', 'manual')->pluck('roles.id')->all() ?? []);
})
->rule(function (?User $record) {
// Die eigene Administrationsrolle kann man sich nicht selbst entziehen.
return function (string $attribute, mixed $value, \Closure $fail) use ($record) {
$before = $record?->roles()->wherePivot('source', 'manual')->pluck('roles.id')->all() ?? [];
$changed = array_merge(array_diff(array_map('intval', (array) $value), $before), array_diff($before, array_map('intval', (array) $value)));
foreach (Role::query()->whereIn('id', $changed)->get() as $role) {
if (! RoleGuard::canAssign(auth()->user(), $role)) {
$fail("Die Rolle „{$role->name}“ enthält Rechte, die Sie selbst nicht haben.");
}
}
// Die eigene Administrationsrolle kann man sich nicht selbst entziehen.
if ($record?->is(auth()->user()) && $record->hasRole(Role::ADMINISTRATION)
&& ! in_array(Role::administration()->id, array_map('intval', (array) $value), true)) {
$fail('Die eigene Rolle „Administration“ kann nicht entfernt werden.');

View file

@ -4,10 +4,13 @@ namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\FortifyServiceProvider;
use App\Support\Audit;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
@ -24,12 +27,31 @@ class AuthController extends Controller
'device_name' => ['required', 'string', 'max:100'],
]);
$user = User::query()->where('email', $data['email'])->first();
// Je E-Mail-Adresse begrenzen (zusätzlich zur Begrenzung je IP) – gegen Durchprobieren von Passwörtern
$key = 'api-token:'.Str::lower($data['email']);
if (RateLimiter::tooManyAttempts($key, 5)) {
throw ValidationException::withMessages(['email' => 'Zu viele Versuche. Bitte in einigen Minuten erneut versuchen.']);
}
$user = User::query()->where('email', Str::lower($data['email']))->first();
$valid = Hash::check($data['password'], $user?->password ?? FortifyServiceProvider::dummyHash());
if (! $user || ! $user->is_active || $user->password === null || ! $valid) {
RateLimiter::hit($key, 300);
if (! $user || ! $user->is_active || $user->password === null || ! Hash::check($data['password'], $user->password)) {
throw ValidationException::withMessages(['email' => 'Diese Kombination aus Zugangsdaten wurde nicht gefunden.']);
}
RateLimiter::clear($key);
// Höchstens 20 Zugänge je Person – der älteste fällt weg
$excess = $user->tokens()->count() - 19;
if ($excess > 0) {
$user->tokens()->oldest()->limit($excess)->get()->each->delete();
}
$token = $user->createToken(trim($data['device_name']));
Audit::log('api.token_created', ['user' => $user->id, 'device' => $data['device_name']]);

View file

@ -38,7 +38,9 @@ class NotificationController extends Controller
$url = (string) ($notification->data['url'] ?? '');
// Nur Adressen innerhalb des Portals ansteuern.
return redirect()->to($url !== '' && (Str::startsWith($url, '/') && ! Str::startsWith($url, '//') || Str::startsWith($url, url('/'))) ? $url : '/');
$local = preg_match('#^/(?![/\\\\])#', $url) || Str::startsWith($url, url('/').'/');
return redirect()->to($local ? $url : '/');
}
public function markAllRead(Request $request): JsonResponse

View file

@ -8,6 +8,8 @@ use App\Profile\ProfileSections;
use App\Support\Audit;
use App\Support\Avatars;
use App\Support\Covers;
use App\Support\ImageTooLarge;
use App\Support\Impersonation;
use App\Support\ProfileFields;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
@ -30,6 +32,7 @@ class ProfileController extends Controller
{
$user = $request->user();
$managed = $user->managedFields();
$locked = $user->lockedProfileFields();
return Inertia::render('Profile/Edit', [
'profile' => [
@ -45,6 +48,8 @@ class ProfileController extends Controller
],
// Felder, die Microsoft Entra ID pflegt – im Portal nur lesbar.
'managed' => $managed,
// Nicht selbst änderbar (E-Mail, ggf. Abteilung/Standort): pflegt die Personalverwaltung
'locked' => $locked,
'customFields' => $profileFields->formFor($user, $managed),
'sections' => app(ProfileSections::class)->resolve($user),
// Apps & Geräte: persönliche Zugangs-Tokens für die REST-API
@ -60,7 +65,7 @@ class ProfileController extends Controller
public function update(UpdateProfileRequest $request, ProfileFields $profileFields): RedirectResponse
{
$user = $request->user();
$managed = $user->managedFields();
$managed = $user->lockedProfileFields();
$user->update(collect($request->validated())->except([...$managed, 'custom_fields'])->all());
if ($request->has('custom_fields')) {
@ -78,6 +83,8 @@ class ProfileController extends Controller
try {
$avatars->store($request->user(), $request->file('avatar'));
} catch (ImageTooLarge $e) {
throw ValidationException::withMessages(['avatar' => $e->getMessage()]);
} catch (Throwable $e) {
// Meist eine Server-Einschränkung (GD ohne WebP, Upload-Ordner schreibgeschützt,
// zu wenig Speicher) – verständliche Meldung statt „500 Interner Fehler“.
@ -105,6 +112,8 @@ class ProfileController extends Controller
public function createToken(Request $request): JsonResponse
{
// Während „Als Person anmelden“ keine dauerhaften Zugänge für die andere Person
abort_if(app(Impersonation::class)->active(), 403, 'Während „Als Person anmelden“ können keine App-Zugänge angelegt werden.');
$data = $request->validate(['name' => ['required', 'string', 'max:100']], [], ['name' => 'Name']);
abort_if($request->user()->tokens()->count() >= 20, 422, 'Höchstens 20 Apps und Geräte – bitte alte entfernen.');
@ -129,6 +138,8 @@ class ProfileController extends Controller
try {
$covers->store($request->user(), $request->file('cover'));
} catch (ImageTooLarge $e) {
throw ValidationException::withMessages(['cover' => $e->getMessage()]);
} catch (Throwable $e) {
report($e);

View file

@ -23,8 +23,17 @@ class PushController extends Controller
'keys.auth' => ['required', 'string', 'max:40'],
]);
abort_unless(WebPush::isAllowedEndpoint($data['endpoint']), 422, 'Dieser Push-Dienst wird nicht unterstützt.');
$hash = hash('sha256', $data['endpoint']);
$existing = PushSubscription::query()->where('endpoint_hash', $hash)->first();
// Fremde Abonnements nicht übernehmen; höchstens 10 Geräte je Person
abort_if($existing && $existing->user_id !== $request->user()->id, 409, 'Dieses Gerät ist einer anderen Person zugeordnet.');
abort_if(! $existing && PushSubscription::query()->where('user_id', $request->user()->id)->count() >= 10, 422, 'Höchstens 10 Geräte – bitte Push auf einem alten Gerät ausschalten.');
PushSubscription::query()->updateOrCreate(
['endpoint_hash' => hash('sha256', $data['endpoint'])],
['endpoint_hash' => $hash],
[
'user_id' => $request->user()->id,
'endpoint' => $data['endpoint'],

View file

@ -0,0 +1,31 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
/**
* Deaktivierte Konten werden sofort abgemeldet – auch bei offener Sitzung.
*/
class EnsureActiveUser
{
public function handle(Request $request, Closure $next): Response
{
$user = Auth::guard('web')->user();
if ($user && ! $user->is_active) {
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return $request->expectsJson()
? response()->json(['message' => 'Ihr Konto ist deaktiviert.'], 401)
: redirect('/login')->with('status', 'Ihr Konto ist deaktiviert.');
}
return $next($request);
}
}

View file

@ -3,6 +3,7 @@
namespace App\Http\Middleware;
use App\Support\Installation;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\Migrations;
use Closure;
use Illuminate\Http\Request;
@ -24,7 +25,8 @@ class RunPendingMigrations
public function handle(Request $request, Closure $next): Response
{
if (app()->runningUnitTests() || ! Installation::isInstalled()) {
// Nicht während eines laufenden Updates – dann sind die Dateien womöglich erst halb kopiert
if (app()->runningUnitTests() || ! Installation::isInstalled() || app(MaintenanceFlag::class)->isActive()) {
return $next($request);
}

View file

@ -0,0 +1,41 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Grundlegende Sicherheits-Header für alle Seiten: keine Einbettung in fremde Seiten
* (Clickjacking), kein MIME-Raten, sparsamer Referrer, HSTS bei HTTPS und eine
* Basis-CSP. Eigene Header einzelner Antworten (z. B. Datei-Downloads) bleiben erhalten.
*/
class SecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$headers = $response->headers;
$defaults = [
'X-Frame-Options' => 'SAMEORIGIN',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'strict-origin-when-cross-origin',
'Permissions-Policy' => 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
'Content-Security-Policy' => "frame-ancestors 'self'; object-src 'none'; base-uri 'self'",
];
foreach ($defaults as $name => $value) {
if (! $headers->has($name)) {
$headers->set($name, $value);
}
}
if ($request->isSecure() && ! $headers->has('Strict-Transport-Security')) {
$headers->set('Strict-Transport-Security', 'max-age=31536000');
}
return $response;
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Symfony\Component\HttpFoundation\Response;
/**
* „Passwort vergessen“ und „Passwort zurücksetzen“ begrenzen (Fortify drosselt diese Wege nicht):
* gegen Massenmails und das Durchprobieren von Adressen.
*/
class ThrottlePasswordReset
{
public function handle(Request $request, Closure $next): Response
{
if ($request->isMethod('POST') && $request->routeIs('password.email', 'password.update')) {
$key = 'password-reset:'.$request->ip();
if (RateLimiter::tooManyAttempts($key, 10)) {
abort(429, 'Zu viele Versuche. Bitte in einigen Minuten erneut versuchen.');
}
RateLimiter::hit($key, 600);
}
return $next($request);
}
}

View file

@ -13,7 +13,7 @@ class UpdateProfileRequest extends FormRequest
*/
public function rules(): array
{
$managed = $this->user()->managedFields();
$managed = $this->user()->lockedProfileFields();
return [
'first_name' => [in_array('first_name', $managed, true) ? 'nullable' : 'required', 'string', 'max:100'],

View file

@ -0,0 +1,23 @@
<?php
namespace App\Http\Responses;
use Illuminate\Http\JsonResponse;
use Laravel\Fortify\Contracts\FailedPasswordResetLinkRequestResponse;
use Laravel\Fortify\Contracts\SuccessfulPasswordResetLinkRequestResponse;
/**
* „Passwort vergessen“ antwortet immer gleich – ob es das Konto gibt oder nicht
* (sonst ließe sich ausprobieren, welche Adressen ein Konto haben).
*/
class NeutralPasswordResetLinkResponse implements FailedPasswordResetLinkRequestResponse, SuccessfulPasswordResetLinkRequestResponse
{
public function __construct(protected string $status = '') {}
public function toResponse($request)
{
$message = trans('passwords.sent');
return $request->wantsJson() ? new JsonResponse(['message' => $message], 200) : back()->with('status', $message);
}
}

View file

@ -78,6 +78,17 @@ abstract class IdentityDriver
return [];
}
/**
* Felder, die bestimmen, wohin die Geheimnisse geschickt werden (Server, Aussteller …).
* Ändert sich eines, müssen die Geheimnisse neu eingegeben werden.
*
* @return list<string>
*/
public function destinationFields(): array
{
return [];
}
/**
* Standardzuordnung Profilfeld => Attribut für neue Anbieter.
*

View file

@ -51,6 +51,12 @@ class IdentitySync
? User::query()->where('email', $email)->first()
: null;
// Konten mit Passwort oder Backend-Rechten nur verknüpfen, wenn die Adresse verlässlich
// ist – sonst könnte, wer beim Anbieter seine E-Mail ändern kann, fremde Konten übernehmen.
if ($user && ($user->password !== null || $user->canAccessAdmin()) && ! $this->emailTrusted($provider, $profile)) {
throw new IdentityException('Für diese E-Mail-Adresse gibt es bereits ein Portal-Konto. Bitte melden Sie sich mit Ihrem Passwort an oder bitten Sie die Administration, die Anmeldung freizuschalten.');
}
if (! $user) {
if (! $allowCreate) {
return null;
@ -254,6 +260,19 @@ class IdentitySync
return array_values(array_unique($desired));
}
/**
* Stammt die E-Mail-Adresse sicher von der Person? Microsoft Entra ID prüft Adressen,
* OIDC meldet es per „email_verified“, sonst entscheidet die Administration je Anbieter.
*
* @param array<string, mixed> $profile
*/
private function emailTrusted(IdentityProvider $provider, array $profile): bool
{
return $provider->type === 'entra'
|| ($profile['email_verified'] ?? false) === true
|| (bool) $provider->setting('trust_email', false);
}
/**
* Konto wurde beim Anbieter deaktiviert oder gelöscht: im Portal deaktivieren
* und die Rollen aus diesem Anbieter entfernen.

View file

@ -2,15 +2,20 @@
namespace App\Models;
use App\Push\PushSubscription;
use App\Support\Abilities;
use App\Support\Audit;
use App\Support\Avatars;
use App\Support\Covers;
use App\Support\Permissions\Permissions;
use App\Support\Permissions\PermissionSet;
use App\Support\ProfileFields;
use App\Support\Settings;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasAvatar;
use Filament\Panel;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Builder;
@ -21,6 +26,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
@ -39,6 +46,24 @@ class User extends Authenticatable implements FilamentUser, HasAvatar
protected static function booted(): void
{
// Protokoll: Konten anlegen, ändern (ohne Werte von Passwörtern), löschen
static::created(fn (User $user) => Audit::log('user.created', ['user' => $user->id, 'email' => $user->email]));
static::deleted(fn (User $user) => Audit::log('user.deleted', ['user' => $user->id, 'email' => $user->email]));
static::updated(function (User $user) {
$changed = array_values(array_diff(array_keys($user->getChanges()), ['updated_at', 'remember_token', 'last_login_at', 'avatar_path', 'cover_path']));
if ($changed !== []) {
Audit::log('user.updated', ['user' => $user->id, 'fields' => $changed, 'is_active' => $user->wasChanged('is_active') ? $user->is_active : null]);
}
});
// Deaktiviert: alle Zugänge sofort beenden (Sitzungen, „Angemeldet bleiben“, API, Push)
static::updated(function (User $user) {
if ($user->wasChanged('is_active') && ! $user->is_active) {
$user->revokeAccess();
}
});
// Der Anzeigename folgt Vor- und Nachname, solange beide gepflegt sind.
static::saving(function (User $user): void {
$fullName = trim($user->first_name.' '.$user->last_name);
@ -121,6 +146,20 @@ class User extends Authenticatable implements FilamentUser, HasAvatar
*
* @return list<string>
*/
/**
* Felder, die die Person im Profil nicht selbst ändern darf: vom Anmeldedienst gepflegte,
* die E-Mail-Adresse (Anmeldung, Verknüpfung, IT-Service) und – solange nicht freigegeben –
* Abteilung und Standort, weil sie bestimmen, wer welche Inhalte sieht.
*
* @return list<string>
*/
public function lockedProfileFields(): array
{
$selfOrg = (bool) app(Settings::class)->get(ProfileFields::SELF_EDIT_ORG, false);
return array_values(array_unique([...$this->managedFields(), 'email', ...($selfOrg ? [] : ['department', 'location'])]));
}
public function managedFields(): array
{
return $this->identities()->with('provider')->get()
@ -165,6 +204,10 @@ class User extends Authenticatable implements FilamentUser, HasAvatar
$this->roles()->attach($roleId, ['source' => 'manual', 'created_at' => now()]);
}
if (array_diff($roleIds, $current) || array_diff($current, $roleIds)) {
Audit::log('user.roles_changed', ['user' => $this->id, 'added' => array_values(array_diff($roleIds, $current)), 'removed' => array_values(array_diff($current, $roleIds))]);
}
Permissions::flush();
}
@ -205,4 +248,33 @@ class User extends Authenticatable implements FilamentUser, HasAvatar
{
$query->where('is_active', true);
}
/**
* Alle bestehenden Zugänge beenden: Sitzungen, „Angemeldet bleiben“, API-Tokens, Push-Abos.
*/
public function revokeAccess(bool $keepCurrentSession = false): void
{
$this->forceFill(['remember_token' => Str::random(60)])->saveQuietly();
$this->tokens()->delete();
PushSubscription::query()->where('user_id', $this->id)->delete();
if (Schema::hasTable(config('session.table', 'sessions'))) {
DB::table(config('session.table', 'sessions'))->where('user_id', $this->id)
->when($keepCurrentSession && session()->isStarted(), fn ($q) => $q->where('id', '!=', session()->getId()))
->delete();
}
}
/**
* Keine Reset-Mail für deaktivierte Konten und für Konten, die sich nur über
* einen Anmeldedienst anmelden (sie sollen kein lokales Passwort bekommen).
*/
public function sendPasswordResetNotification(#[\SensitiveParameter] $token): void
{
if (! $this->is_active || ($this->password === null && $this->identities()->exists())) {
return;
}
$this->notify(new ResetPassword($token));
}
}

View file

@ -77,6 +77,11 @@ class Content
$type = $this->blocks->get($clean['type']);
// Blöcke eines Moduls, von dem die Person ausgeschlossen ist, auch in der Vorschau nicht berechnen
if ($type && ! app(PluginAccess::class)->allows($type->key, $user)) {
return null;
}
return $type?->resolve ? $this->resolve($type, $clean, $user, $context) : [];
}
@ -133,8 +138,13 @@ class Content
*
* @param array<mixed>|null $content
*/
public function plainText(?array $content): string
public function plainText(?array $content, bool $publicOnly = false): string
{
// Für Suche und Auszüge: Blöcke mit eingeschränkter Sichtbarkeit (und ihr Inhalt) weglassen
if ($publicOnly && is_array($content)) {
$content = ['blocks' => self::withoutRestricted($content['blocks'] ?? [])];
}
$parts = $this->collect($content, function (array $block) {
$texts = [];
@ -154,6 +164,29 @@ class Content
return trim(preg_replace('/\s+/u', ' ', html_entity_decode(implode(' ', $parts))) ?? '');
}
/**
* @param array<mixed> $blocks
* @return list<array<string, mixed>>
*/
private static function withoutRestricted(array $blocks): array
{
$result = [];
foreach ($blocks as $block) {
if (! is_array($block) || array_filter((array) ($block['visibility'] ?? []))) {
continue;
}
if (isset($block['items'])) {
$block['items'] = array_map(fn ($item) => is_array($item) ? [...$item, 'blocks' => self::withoutRestricted((array) ($item['blocks'] ?? []))] : $item, (array) $block['items']);
}
$result[] = $block;
}
return $result;
}
/**
* @return list<array<string, mixed>>
*/

View file

@ -170,7 +170,7 @@ final class Field
}
// Relative Adressen im Portal, Anker oder http(s)/mailto/tel – nichts anderes (kein javascript:).
if (preg_match('#^(/(?!/)|\#)#', $url) || preg_match('#^(https?://|mailto:|tel:)#i', $url)) {
if (preg_match('#^(/(?![/\\\\])|\#)#', $url) || preg_match('#^(https?://|mailto:|tel:)#i', $url)) {
return $url;
}

View file

@ -61,7 +61,7 @@ class PluginAssets
$this->cache[$slug] = [
'base' => '/plugin-assets/'.rawurlencode($slug).'/'.rawurlencode($manifest->version).'/',
'components' => array_filter(array_map($clean, (array) ($data['components'] ?? []))),
'components' => array_filter(array_map($clean, (array) ($data['components'] ?? [])), fn ($file, $key) => $file !== null && preg_match('#^[A-Za-z0-9_/-]+$#', (string) $key), ARRAY_FILTER_USE_BOTH),
'css' => array_values(array_filter(array_map($clean, (array) ($data['css'] ?? [])))),
];
}

View file

@ -25,7 +25,10 @@ class PluginInstaller
return ! filter_var(config('inhaus.disallow_file_mods'), FILTER_VALIDATE_BOOL);
}
public function install(string $zipFile): PluginManifest
/**
* @param string|null $expectedSlug bei Updates: das Archiv muss genau dieses Plugin enthalten
*/
public function install(string $zipFile, ?string $expectedSlug = null): PluginManifest
{
if (! self::uploadsAllowed()) {
throw new RuntimeException('Das Installieren von Plugins ist in dieser Installation abgeschaltet.');
@ -42,6 +45,10 @@ class PluginInstaller
throw new RuntimeException('Das Archiv enthält kein gültiges Plugin: '.$e->getMessage());
}
if ($expectedSlug !== null && $manifest->slug !== $expectedSlug) {
throw new RuntimeException("Das Archiv enthält das Plugin „{$manifest->slug}“ statt „{$expectedSlug}“.");
}
$existing = $this->plugins->find($manifest->slug);
if ($existing?->core) {

View file

@ -3,6 +3,7 @@
namespace App\Plugins;
use App\Support\Audit;
use App\Support\SafeOutbound;
use App\Support\Settings;
use App\Version;
use Illuminate\Support\Facades\Artisan;
@ -102,7 +103,16 @@ class PluginUpdates
$file = tempnam(sys_get_temp_dir(), 'plugin-update');
try {
$response = Http::timeout(120)->withOptions(['sink' => $file])->get($this->safeUrl($info['download_url']));
// Nur über HTTPS (auch bei Weiterleitungen), nie an interne Adressen, Größe schon beim Laden begrenzen
$response = Http::timeout(120)->withOptions([
...SafeOutbound::options(['https']),
'sink' => $file,
'progress' => function ($total, $downloaded) {
if ($total > self::MAX_BYTES || $downloaded > self::MAX_BYTES) {
throw new RuntimeException('Das Update ist größer als 50 MB.');
}
},
])->get($this->safeUrl($info['download_url']));
if (! $response->successful()) {
throw new RuntimeException("Download fehlgeschlagen (HTTP {$response->status()}).");
@ -117,11 +127,7 @@ class PluginUpdates
}
$wasEnabled = $this->plugins->isEnabled($slug);
$manifest = $this->installer->install($file);
if ($manifest->slug !== $slug) {
throw new RuntimeException("Das Archiv enthält das Plugin „{$manifest->slug}“ statt „{$slug}“.");
}
$manifest = $this->installer->install($file, expectedSlug: $slug);
// Neue Tabellen oder Spalten des Plugins sofort anlegen
if ($wasEnabled && is_dir($manifest->migrationsPath())) {
@ -141,7 +147,7 @@ class PluginUpdates
*/
private function fetch(string $url): array
{
$response = Http::timeout(15)->acceptJson()->get($this->safeUrl($url));
$response = Http::timeout(15)->acceptJson()->withOptions(SafeOutbound::options(['https']))->get($this->safeUrl($url));
if (! $response->successful()) {
throw new RuntimeException("Update-Adresse antwortet mit HTTP {$response->status()}.");
@ -193,6 +199,10 @@ class PluginUpdates
throw new RuntimeException('Update-Adressen müssen mit https:// beginnen.');
}
if (! SafeOutbound::isPublicUrl($url, ['https'])) {
throw new RuntimeException('Update-Adressen dürfen nicht auf interne Server zeigen.');
}
return $url;
}
}

View file

@ -24,7 +24,8 @@ class RolePolicy
public function update(User $user, Role $role): bool
{
return $user->can('roles.manage');
// Die Rolle „Administration“ (Vollzugriff) ändert nur, wer selbst Vollzugriff hat
return $user->can('roles.manage') && (! $role->isAdministration() || $user->permissions()->isSuperuser());
}
/**

View file

@ -3,6 +3,7 @@
namespace App\Policies;
use App\Models\User;
use App\Support\Permissions\RoleGuard;
class UserPolicy
{
@ -23,11 +24,11 @@ class UserPolicy
public function update(User $user, User $model): bool
{
return $user->can('users.manage');
return $user->can('users.manage') && RoleGuard::canManageUser($user, $model);
}
public function delete(User $user, User $model): bool
{
return $user->can('users.manage') && ! $model->is($user);
return $user->can('users.manage') && ! $model->is($user) && RoleGuard::canManageUser($user, $model);
}
}

View file

@ -38,8 +38,11 @@ use App\Support\Theme\ThemeCompiler;
use App\Support\Update\InstalledVersion;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\UpdateProgress;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Sanctum\Sanctum;
@ -88,6 +91,8 @@ class AppServiceProvider extends ServiceProvider
public function boot(): void
{
RateLimiter::for('api', fn (Request $request) => Limit::perMinute(180)->by($request->user()?->id ?: $request->ip()));
// API-Tokens deaktivierter Konten gelten nicht mehr
Sanctum::authenticateAccessTokensUsing(fn ($token, bool $isValid) => $isValid && $token->tokenable instanceof User && $token->tokenable->is_active);

View file

@ -4,9 +4,13 @@ namespace App\Providers;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Http\Responses\NeutralPasswordResetLinkResponse;
use App\Models\IdentityProvider;
use App\Models\User;
use App\Support\Audit;
use Illuminate\Auth\Events\Failed;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Event;
@ -15,10 +19,19 @@ use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Laravel\Fortify\Contracts\FailedPasswordResetLinkRequestResponse;
use Laravel\Fortify\Contracts\SuccessfulPasswordResetLinkRequestResponse;
use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
public function register(): void
{
// „Passwort vergessen“ verrät nicht, ob es ein Konto gibt
$this->app->bind(FailedPasswordResetLinkRequestResponse::class, NeutralPasswordResetLinkResponse::class);
$this->app->bind(SuccessfulPasswordResetLinkRequestResponse::class, NeutralPasswordResetLinkResponse::class);
}
public function boot(): void
{
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
@ -47,14 +60,16 @@ class FortifyServiceProvider extends ServiceProvider
Fortify::authenticateUsing(function (Request $request): ?User {
$user = User::query()->where('email', Str::lower($request->input(Fortify::username())))->first();
if ($user && $user->is_active && $user->password !== null
&& Hash::check($request->input('password'), $user->password)) {
return $user;
}
// Immer ein Passwort prüfen – gleiche Antwortzeit, ob es das Konto gibt oder nicht
$valid = Hash::check((string) $request->input('password'), $user?->password ?? self::dummyHash());
return null;
return $user && $user->is_active && $user->password !== null && $valid ? $user : null;
});
// Anmeldungen protokollieren: fehlgeschlagene Passwort-Anmeldungen und Passwort-Resets
Event::listen(Failed::class, fn ($event) => Audit::log('auth.login_failed', ['email' => Str::lower((string) ($event->credentials['email'] ?? ''))], $event->user?->id));
Event::listen(PasswordReset::class, fn ($event) => Audit::log('auth.password_reset', ['user' => $event->user->id], $event->user->id));
Event::listen(Login::class, function (Login $event): void {
if ($event->user instanceof User) {
$event->user->forceFill(['last_login_at' => now()])->saveQuietly();
@ -67,4 +82,11 @@ class FortifyServiceProvider extends ServiceProvider
return Limit::perMinute(5)->by($throttleKey);
});
}
public static function dummyHash(): string
{
static $hash;
return $hash ??= Hash::make(Str::random(32));
}
}

View file

@ -20,6 +20,36 @@ class WebPush
{
public const KEYS = 'push.vapid';
/**
* Push-Dienste der Browser. Nur dorthin wird gesendet – sonst ließe sich der Server
* über ein präpariertes Abonnement zu Anfragen an interne Adressen bewegen.
*/
public const SERVICE_HOSTS = [
'fcm.googleapis.com', 'android.googleapis.com', // Chrome, Edge (Android), Opera, Samsung
'*.push.services.mozilla.com', // Firefox
'*.notify.windows.com', // Edge (Windows)
'web.push.apple.com', '*.push.apple.com', // Safari, iOS
];
public static function isAllowedEndpoint(string $endpoint): bool
{
$parts = parse_url($endpoint);
if (($parts['scheme'] ?? null) !== 'https' || ! isset($parts['host']) || isset($parts['user']) || isset($parts['port'])) {
return false;
}
$host = strtolower($parts['host']);
foreach (self::SERVICE_HOSTS as $allowed) {
if ($host === $allowed || (str_starts_with($allowed, '*.') && str_ends_with($host, substr($allowed, 1)))) {
return true;
}
}
return false;
}
/** Präfix einer DER-kodierten P-256-Public-Key-Struktur (SubjectPublicKeyInfo) vor dem 65-Byte-Punkt */
private const P256_SPKI_PREFIX = '3059301306072a8648ce3d020106082a8648ce3d030107034200';
@ -43,10 +73,14 @@ class WebPush
*/
public function send(PushSubscription $subscription, array $payload): bool
{
if (! self::isAllowedEndpoint($subscription->endpoint)) {
return false; // unbekannter Dienst – Abonnement wird entfernt
}
$body = $this->encrypt((string) json_encode($payload, JSON_UNESCAPED_UNICODE), $subscription->public_key, $subscription->auth_token);
$keys = $this->keys();
$response = Http::timeout(10)->withHeaders([
$response = Http::timeout(10)->withoutRedirecting()->withHeaders([
'Authorization' => 'vapid t='.$this->jwt($subscription->endpoint, $keys['private']).', k='.$keys['public'],
'Content-Encoding' => 'aes128gcm',
'Content-Type' => 'application/octet-stream',

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ß.');
}
}
}
}

View file

@ -9,5 +9,5 @@ namespace App;
*/
final class Version
{
public const VERSION = '0.28.3';
public const VERSION = '0.29.0';
}