concept-image / laravel-fortress
Laravel Fortress: switchable security modules (HTTPS, security headers, session and password hardening, safe mail links), modular .htaccess security rules with the Perishable Press firewall, and a security maintenance killswitch.
Package info
gitlab.com/concept-image-public/laravel-fortress
pkg:composer/concept-image/laravel-fortress
Requires
- php: ^8.3
- illuminate/auth: ^12.0|^13.0
- illuminate/console: ^12.0|^13.0
- illuminate/http: ^12.0|^13.0
- illuminate/notifications: ^12.0|^13.0
- illuminate/process: ^12.0|^13.0
- illuminate/routing: ^12.0|^13.0
- illuminate/session: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
- illuminate/validation: ^12.0|^13.0
Requires (Dev)
- enshrined/svg-sanitize: ^1.1.1
- larastan/larastan: ^3.0
- laravel/fortify: ^1.30
- laravel/pint: ^1.18
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^4.0|^5.0
- pestphp/pest-plugin-arch: ^4.0|^5.0
Suggests
- ext-zip: Required by fortress:firewall-update to read the 8G firewall archive.
- enshrined/svg-sanitize: Required by the SanitizedSvg validation rule and the SvgSanitizer.
- laravel/fortify: Two-factor detection of RequireTwoFactor and the password check of Fortify's two-factor logins.
- spatie/laravel-permission: Roles of the per-role password policy and of RequireTwoFactor (any role source works through UserRoles::using()).
Provides
None
Conflicts
None
Replaces
None
README
Security defaults for production Laravel applications, as modules you switch on and off in config/fortress.php, and a command that writes security rules into public/.htaccess.
Requirements
- PHP 8.3 or higher
- Laravel 12 or 13
Installation
composer require concept-image/laravel-fortress
php artisan fortress:install
php artisan fortress:htaccess
The provider is auto-discovered and every module is enabled by default (the firewall rules are off). fortress:install publishes config/fortress.php, public/.htaccess.maintenance and public/maintenance.html (each kept when it already exists), the same as:
php artisan vendor:publish --tag=fortress-config
php artisan vendor:publish --tag=fortress-maintenance
Modules
Modules boot with the application. Each one is a class implementing ConceptImage\LaravelFortress\Contracts\Module, enabled in config/fortress.php:
'modules' => [
ForceHttps::class => env('FORTRESS_FORCE_HTTPS', true),
SecurityHeaders::class => env('FORTRESS_SECURITY_HEADERS', true),
],
| Module | Effect |
|---|---|
ForceHttps | URL::forceHttps(): every generated URL uses https |
SecurityHeaders | Appends a middleware to the web group adding X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy, a Content-Security-Policy (only when the response has none) and Strict-Transport-Security (production only). Values live in security_headers. |
IgnoreForeignReferer | Prepends a middleware to the web group dropping a Referer of another site, so back() and failed validation never redirect there (open redirect, CWE-601). The request host and the APP_URL host are the site's; add others in foreign_referer.allowed_hosts. |
AuthenticateSessions | Appends Laravel's AuthenticateSession to the web group: a password change ends the user's other sessions (CWE-613). |
SafeMailLinks | Builds the password reset and email verification links on APP_URL instead of the request host, which a forged Host or X-Forwarded-Host header controls (host header poisoning, CWE-644). An application's own createUrlUsing() still wins. |
PasswordDefaults | Password::defaults() from password (min 12, mixed case, letters, numbers, symbols, uncompromised), stricter for the roles of password.roles of the signed-in user (30 characters for super_admin and admin), in production only. |
RequirePasswordChange | A user signing in with a password their policy now refuses is sent to password.change_route until they change it. |
RequireTwoFactor | Users of the roles of two_factor.roles without two-factor authentication are sent to two_factor.setup_route until they set it up. |
TrustedHosts | In production, a request whose host (Host or X-Forwarded-Host) is not the APP_URL host or one of trusted_hosts.hosts answers 400, so links, redirects and signed URLs are never built on an attacker's host (CWE-644). trusted_hosts.subdomains accepts their subdomains. |
ThrottleRoutes | Defines the fortress-login (per username and IP, plus 4 times as many per IP), fortress-two-factor and fortress-forms (per IP and route) rate limiters, and throttles the routes of rate_limits.routes by name: Fortify's login, two-factor, password reset, password confirmation and registration by default. Applied at request time, it holds with route:cache and on package routes. |
SafeLivewireUploads | Adds the SafeUpload rule to Livewire's temporary upload rules: every file sent to a component is checked before it is stored. |
NoDebugTools | In production, APP_DEBUG is forced off, Debugbar and Telescope stop, and the debug paths (Ignition, Debugbar, Telescope, Clockwork…) answer 404, whatever the .env says. |
RestrictPathsByIp | Keeps admin tools to their own IPs, one group per tool (see below). |
NoIndexOutsideProduction | X-Robots-Tag: noindex, nofollow on every response outside production: staging sites never end in search results. |
SecureSessionCookie | In production, the session cookie is Secure and HttpOnly with the session_cookie.same_site value, whatever the .env says (CWE-614, CWE-1004). |
Content-Security-Policy
The SecurityHeaders module sends two policies:
- the baseline
content_security_policy(upgrade-insecure-requests; frame-ancestors 'self'), always enforced; - the strict policy of
security_headers.csp, with a nonce per request:script-src 'self' 'nonce-…',object-src 'none',base-uri 'self'…
The nonce is put on every tag Vite and Livewire render, and given to Horizon and Telescope. Use it on your own inline scripts, and pass it to Flux's @fluxAppearance, which does not add it on its own:
<script nonce="{{ Vite::cspNonce() }}">…</script>
@fluxAppearance(['nonce' => Vite::cspNonce()])
The strict policy starts in report-only mode (Content-Security-Policy-Report-Only): nothing breaks, and browsers post each violation to /fortress/csp-report, which logs it as a warning (in csp.report_log_channel, or the default channel). Fix what the reports show (inline scripts and onclick handlers without nonce, external scripts, images or fonts to allow in directives), then enforce it:
FORTRESS_CSP_MODE=enforce # report-only (default), enforce or off
Livewire's default Alpine build compiles expressions with new Function(), so 'unsafe-eval' is added to script-src while livewire.csp_safe is false (csp.unsafe_eval: 'auto'). Livewire 4's csp_safe mode removes that need, with restrictions on Alpine expressions. The Vite dev server is allowed while npm run dev runs, for scripts, styles, websockets, and the fonts and images its stylesheets load.
Passwords and two-factor authentication by role
Roles come from spatie/laravel-permission (hasAnyRole()) when the user model has it, else from the roles.attribute attribute (role, a string or backed enum). Any other source:
UserRoles::using(fn (User $user): array => $user->isAdmin() ? ['admin'] : []);
Password policy. Each role of password.roles makes the policy of its users stricter; with several roles, the longest minimum and every requirement win:
'password' => [
'min' => 12,
// …
'roles' => [
'super_admin' => ['min' => 30],
'admin' => ['min' => 30],
],
],
Password::default() uses the signed-in user, so a user changing their own password gets their policy. To validate the password of another user, use PasswordPolicy::rule($user), such as in Fortify's actions:
// app/Actions/Fortify/ResetUserPassword.php: runs once the reset token is checked
Validator::make($input, ['password' => ['required', 'string', PasswordPolicy::rule($user), 'confirmed']])->validate();
// An admin creating an account
'password' => ['required', PasswordPolicy::rule(new User(['role' => $request->role]))],
Don't look the user up from the submitted email before the token is checked: the error message would tell which addresses are admins.
Existing passwords. A policy only applies when a password is set. With RequirePasswordChange, the password typed at login is checked against the user's policy (without the compromised passwords lookup, so no network call); when it fails, every page sends the user to password.change_route until their password hash changes. The check runs on Auth::attempt() (the Validated event) and on Fortify's two-factor challenge, which checks credentials without it.
Two-factor authentication. With RequireTwoFactor, a signed-in user of two_factor.roles (['*'] for everyone) without two-factor authentication is sent to two_factor.setup_route; a JSON request gets a 403. Two-factor authentication is set up when Fortify's hasEnabledTwoFactorAuthentication() says so; accept another second factor (passkeys…) with:
RequireTwoFactor::enabledUsing(fn (User $user): bool => $user->hasEnabledTwoFactorAuthentication() || $user->passkeys()->exists());
While held, the user can still reach the setup page and account_security.allowed_routes: logout, password and two-factor endpoints, password confirmation, email verification, passkeys and Livewire updates. The redirection flashes fortress.account_security (password-change-required or two-factor-required) for the page to explain why. Both apply in production only (password.environments, two_factor.environments), and only to the web group: a Filament panel has its own middleware, use its multi-factor authentication with isRequired: true there.
Restricted paths
Each group of restricted_paths keeps its paths to its own IPs or CIDR ranges; other visitors get a 404 before routing and authentication. Horizon, Pulse, Filament (admin) and Nova are ready, set from the .env:
FORTRESS_HORIZON_IPS=203.0.113.5,10.0.0.0/8
FORTRESS_FILAMENT_IPS=203.0.113.5
A group whose IPs are not set restricts nothing; an empty array refuses everyone. Add a group per tool or panel path ('paths' => ['back-office', 'back-office/*']). The client IP is the one TrustProxies resolves: behind a reverse proxy, trust it or every visitor has the proxy's IP. Livewire requests of a panel go through /livewire/update, which stays open: its components still check their own authorization.
Mail links
An application with several domains gives the root of each user's mail links:
SafeMailLinks::rootUsing(fn (User $user): string => $user->isClient() ? 'https://client.example.com' : config('app.url'));
An application module is any class implementing Module, added to the list. It is resolved through the container, so its constructor can inject services.
.htaccess rules
php artisan fortress:htaccess writes each enabled rule of htaccess.rules into htaccess.path (public/.htaccess by default), in the configured order, each between its own markers:
# BEGIN Fortress: deny-private-paths
<IfModule mod_rewrite.c>
RewriteEngine On
...
</IfModule>
# END Fortress: deny-private-paths
<IfModule mod_rewrite.c>
... Laravel rules, never touched ...
- an existing section is updated in place, a new one is added after the last Fortress section (at the top of the file the first time);
- the section of a rule that is disabled or removed from the configuration is deleted;
- everything outside the markers is kept as is, and running the command again changes nothing.
| Option | Effect |
|---|---|
--dry-run | Prints the resulting file, writes nothing |
--check | Writes nothing, fails when the file is not up to date (CI, deploy) |
| Rule | Effect |
|---|---|
SendSecurityHeaders | Removes ETag and sends the headers of security_headers (Content-Security-Policy included) with Header setifempty: static files get them, while a header the application already sent is never replaced nor duplicated. Strict-Transport-Security is left to the SecurityHeaders module and its environments. |
DenySensitiveFiles | 403 on environment files (.env, .env.backup, production.env), .htaccess/.htpasswd, composer.json/composer.lock, logs and SQL dumps, archived or not (.log, .sql, .sql.gz…) |
DenyPrivatePaths | 403 on hidden files and folders at any depth (.git/, .idea/, .DS_Store…) except .well-known/, and on node_modules/. vendor/ stays reachable: Laravel publishes package assets (Horizon, Nova…) to public/vendor/. |
SandboxSvg | SVG files opened directly run in a sandbox, with no script nor remote resource (stored XSS through an upload). SVG shown through <img> or CSS are not affected. |
DenySensitiveFiles | 403 on environment files (.env, .env.backup, production.env), .htaccess/.htpasswd, composer.json/composer.lock, logs and SQL dumps, archived or not (.log, .sql, .sql.gz…), backup and editor files (.bak, .old, .orig, .swp, ~…) |
DenyDataExports | 403 on .csv and .tsv files: exports go through an authorized route, never a public URL. Disable it for a site that publishes CSV on purpose. |
DenyScriptExecution | 403 on any PHP script except /index.php, double extensions included (shell.php.jpg): an uploaded script never runs. /index.php/… URLs are refused too. A site installed in a sub-folder writes its own rule. |
ServeDocumentsAsDownloads | Office documents (.doc(x), .xls(x), .ppt(x), OpenDocument, .rtf…) are never handed to a script handler or CGI, whatever the server configuration, and are served as attachments. |
HideDocumentationFiles | 404 on readme, changelog and license files (.txt, .html, .md) |
Firewall8G | The 8G firewall: 403 on requests whose query string, URI, user agent, referrer, cookie or method match known attack patterns. Off by default, see below. |
BlockAiBots | 403 on the bots of the Ultimate AI Block List, matched anywhere in the user agent. Off by default, see below. |
Firewall
The 8G firewall and the AI block list come from Perishable Press. Enable Firewall8G and BlockAiBots in htaccess.rules, then fetch them:
php artisan fortress:firewall-update # fetches the latest versions and writes them into the .htaccess
php artisan fortress:firewall-update --dry-run # prints the resulting .htaccess instead
Nothing is stored besides the .htaccess: commit it, so deploys never download anything. fortress:htaccess keeps the firewall sections already in the file as they are, and fails while they are missing. Run fortress:firewall-update again to update them, and after changing firewall.excluded_user_agents.
Both lists block broadly (8G blocks curl, any user agent containing scan…, the AI list Zero, Scrap, Traefik…). Remove the user agents your site needs, such as your monitoring, deploy checks or reverse proxy:
'firewall' => [
'excluded_user_agents' => ['curl', 'Traefik'],
],
Each name is removed, case-insensitively, from the alternatives of the user agent conditions. The 8G query string and URI patterns are kept. Test the site well after enabling the firewall.
The 8G firewall is free to use and modify as long as its first two credit lines stay intact: the package keeps them.
To add a rule, implement ConceptImage\LaravelFortress\Htaccess\Contracts\HtaccessRule and enable it in the configuration:
final class DenyComposerFiles implements HtaccessRule
{
public function key(): string
{
return 'deny-composer-files';
}
public function content(): string
{
return <<<'APACHE'
<FilesMatch "^composer\.(json|lock)$">
Require all denied
</FilesMatch>
APACHE;
}
}
The key is kebab-case and unique: it names the section markers. content() may return null to keep the section already in the file (as the firewall rules do outside fortress:firewall-update).
Uploads
SanitizedSvg cleans an uploaded SVG while validating it (scripts, event handlers, javascript: links and remote references removed), also when it is renamed .png, and refuses an SVG that can't be read. It needs enshrined/svg-sanitize:
composer require enshrined/svg-sanitize
'logo' => ['required', 'file', 'mimes:png,jpg,svg', new SanitizedSvg],
SvgSanitizer does the same outside validation.
SafeUpload refuses what a server or a browser could run: script and web page extensions, even hidden before the last one (shell.php.jpg, page.html.pdf), server configuration files (.htaccess, .user.ini, web.config), HTML, JavaScript, PHP or SVG content under another extension (an HTML page renamed .png, detected from the content), and PHP code anywhere in the file (a webshell in an image). It needs no package.
'attachment' => ['required', 'file', 'max:20480', 'mimes:pdf,jpg,png,docx', new SafeUpload],
The SafeLivewireUploads module adds it to every Livewire upload.
Same-origin routes
The fortress.same-origin middleware keeps routes, typically an internal API, to the application's own pages: the host must be the APP_URL host (or one of same_origin.hosts), and the browser must say the request comes from the same origin (Sec-Fetch-Site, or the Origin/Referer of older browsers).
Route::middleware(['fortress.same-origin', 'throttle:api'])->group(base_path('routes/api.php'));
It's not an authentication boundary: a client outside a browser can forge these headers.
Security maintenance
A killswitch for a server security issue, such as a PHP CVE: every request answers 503 with public/maintenance.html, and no PHP runs.
php artisan fortress:security-maintenance on --php=8.5.13 # until the server runs PHP 8.5.13
php artisan fortress:security-maintenance on # until switched off by hand
php artisan fortress:security-maintenance status
php artisan fortress:security-maintenance off
oncopiespublic/.htaccessto.htaccess.bak, then moves.htaccess.maintenanceover.htaccessin one atomic rename: the server never runs without an.htaccess.offdoes the reverse and keeps.htaccess.maintenancefor next time. The package page and.htaccessare used when the application has none.- The maintenance
.htaccessanswers 503 with aRetry-After, refuses any script called directly (403, with the same page), keeps/.well-known/acme-challenge/open for certificate renewals, and refuses everything whenmod_rewriteis missing. - With
--php, the scheduledfortress:security-maintenance check(every 15 minutes, registered by the package:schedule:runmust run in cron) switches the maintenance off once the server runs that version or a later one.onrefuses a version the server already runs. - The version checked is the CLI PHP's. When the web server's PHP may differ (PHP-FPM from another package), give the command that prints it:
'php_version_command' => ['php-fpm8.5', '-v']. fortress:htaccessrefuses to run while the maintenance is on.- A deploy restores
public/.htaccessfrom the repository, which ends the maintenance: don't deploy while it is on, or switch it on again afterwards.
Testing
composer test # Pest
composer analyse # Larastan
composer lint # Pint
composer ci # all three
License
The MIT License (MIT). Please see License File for more information.