From 12dcb409b49d116691f01d43d41b21d4922ada9d Mon Sep 17 00:00:00 2001 From: nejcc Date: Tue, 15 Sep 2026 22:00:20 +0200 Subject: [PATCH 1/2] =?UTF-8?q?urls:=20CSS=20in=20proza=20nista=20ve=C4=8D?= =?UTF-8?q?=20URL-ja?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Vzorec je vsak `beseda:` bral kot shemo, zato sta color:#fff in time:10am postala URL-ja s prepovedano shemo (High) in besedilo je bilo blokirano. Zdaj: shema z //, ali javascript:/vbscript:/data:/file:. --- src/Text/Checks/UrlsCheck.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Text/Checks/UrlsCheck.php b/src/Text/Checks/UrlsCheck.php index 3d776ee..f36fdce 100644 --- a/src/Text/Checks/UrlsCheck.php +++ b/src/Text/Checks/UrlsCheck.php @@ -71,9 +71,11 @@ protected function inspect(string $text, TextPolicy $policy, ScanContext $contex */ private function extract(string $text): array { - // Any scheme, not just http(s): a pattern that only matches http - // would skip the javascript: and data: payloads that matter most. - preg_match_all('#\b[a-z][a-z0-9+.-]{1,20}:(?://)?[^\s<>"\']{1,2000}#i', $text, $matches); + // Any scheme followed by `//`, plus the slashless schemes that carry + // payloads. A pattern that only matched http would skip javascript: + // and data:; one that took every `word:` read CSS (`color:#fff`) and + // prose (`time:10am`) as URLs with forbidden schemes and blocked them. + preg_match_all('#\b(?:[a-z][a-z0-9+.-]{1,20}://|(?:javascript|vbscript|data|file):)[^\s<>"\']{1,2000}#i', $text, $matches); /** @var list $urls */ $urls = array_values(array_unique($matches[0])); From a5801d7856f1c69d2ba55f116afc11bc1547f2de Mon Sep 17 00:00:00 2001 From: nejcc Date: Tue, 15 Sep 2026 22:00:20 +0200 Subject: [PATCH 2/2] =?UTF-8?q?email:=20ContentSecurity::scanEmail()=20in?= =?UTF-8?q?=20skeniranje=20odhodne=20po=C5=A1te?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Zadeva, telo, HTML in priponke gredo skozi obstoječe cevovode, rezultat je najslabši del. Poslušalec na MessageSending prekliče pošto, ki ni čista (content-security.mail.scan_outbound, privzeto izklopljeno). Closes #1 --- README.md | 16 ++++ config/content-security.php | 13 +++ resources/js/pages/types/index.ts | 2 +- src/ContentSecurity.php | 85 ++++++++++++++++++ src/ContentSecurityServiceProvider.php | 5 ++ src/Domain/Scan/ScanType.php | 2 + src/Facades/ContentSecurity.php | 2 + src/Listeners/ScanOutgoingMail.php | 53 +++++++++++ tests/Feature/ScanEmailTest.php | 120 +++++++++++++++++++++++++ 9 files changed, 297 insertions(+), 1 deletion(-) create mode 100644 src/Listeners/ScanOutgoingMail.php create mode 100644 tests/Feature/ScanEmailTest.php diff --git a/README.md b/README.md index de91412..4e96516 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,22 @@ $result->metadata(); $result->highestThreatLevel(); ``` +### Email + +`scanEmail()` takes a `Symfony\Component\Mime\Email` — which every Laravel mail already is — and runs each part through the pipeline it belongs to: subject and text body as text, the HTML body as text with URL checks, every attachment as a file (audited and quarantined like any upload). The result is the worst part; `checks()` holds one entry per part (`subject`, `text`, `html`, `attachment:invoice.pdf`), each carrying its own `scan_id`. + +```php +$result = ContentSecurity::scanEmail($email); + +if (! $result->isClean()) { + // block or quarantine +} +``` + +Inbound mail (SES, Mailgun, Postmark, IMAP) is scanned the same way once parsed into an `Email`. + +To scan everything the application sends, set `CONTENT_SECURITY_SCAN_OUTBOUND_MAIL=true`. A message that is not clean is cancelled before it leaves — `Mail::send()` returns `null` and `content-security.mail.blocked` is logged. That includes a scanner that is down: fail closed. + ### The file pipeline Cheapest first, so an obviously bad upload never reaches the engine: diff --git a/config/content-security.php b/config/content-security.php index 4bb1c97..b0a1d6c 100644 --- a/config/content-security.php +++ b/config/content-security.php @@ -403,6 +403,19 @@ 'cleanup_at' => '03:30', ], + /* + |-------------------------------------------------------------------------- + | Email + |-------------------------------------------------------------------------- + | ContentSecurity::scanEmail() is always available, for inbound mail too. + | This switch also scans every message Laravel sends and cancels any that + | is not clean — including when the scanner is down (fail closed). + */ + + 'mail' => [ + 'scan_outbound' => (bool) env('CONTENT_SECURITY_SCAN_OUTBOUND_MAIL', false), + ], + /* |-------------------------------------------------------------------------- | Admin console diff --git a/resources/js/pages/types/index.ts b/resources/js/pages/types/index.ts index 9c1d47d..c02a92d 100644 --- a/resources/js/pages/types/index.ts +++ b/resources/js/pages/types/index.ts @@ -15,7 +15,7 @@ export type ScanStatus = export type ThreatLevel = 'info' | 'low' | 'medium' | 'high' | 'critical'; -export type ScanType = 'file' | 'text' | 'html' | 'url'; +export type ScanType = 'file' | 'text' | 'html' | 'url' | 'email'; export type PostureState = 'healthy' | 'warning' | 'critical'; diff --git a/src/ContentSecurity.php b/src/ContentSecurity.php index 120e8b5..6335c87 100644 --- a/src/ContentSecurity.php +++ b/src/ContentSecurity.php @@ -23,6 +23,7 @@ use LaravelPlus\ContentSecurity\Domain\File\FileReference; use LaravelPlus\ContentSecurity\Domain\Policy\FilePolicy; use LaravelPlus\ContentSecurity\Domain\Policy\TextPolicy; +use LaravelPlus\ContentSecurity\Domain\Scan\CheckResult; use LaravelPlus\ContentSecurity\Domain\Scan\Findings; use LaravelPlus\ContentSecurity\Domain\Scan\ScanContext; use LaravelPlus\ContentSecurity\Domain\Scan\ScanId; @@ -36,6 +37,8 @@ use LaravelPlus\ContentSecurity\Pipeline\CheckRegistry; use LaravelPlus\ContentSecurity\Support\HookRegistry; use LaravelPlus\ContentSecurity\Support\ScannerHealth; +use Symfony\Component\Mime\Email; +use Symfony\Component\Mime\Part\DataPart; /** * The package's front door, and the object behind the ContentSecurity facade. @@ -164,6 +167,57 @@ public function isSafeUrl(string $url): bool return $this->urls->isSafe($url); } + /** + * Scans every part of an email — subject, bodies, attachments — through + * the pipelines above and returns one verdict: the worst of its parts. + * + * Outbound Laravel mail already is an Email; inbound mail (SES, Mailgun, + * IMAP) is scanned once parsed into one. Each part is scanned, audited + * and quarantined exactly as it would be on its own, and its outcome is + * one entry in the result's checks(). + */ + public function scanEmail(Email $email): ScanResult + { + $started = hrtime(true); + $parts = []; + + if (($subject = (string) $email->getSubject()) !== '') { + $parts[] = ['subject', $this->scanText($subject)]; + } + + if (($text = $this->body($email->getTextBody())) !== '') { + $parts[] = ['text', $this->scanText($text)]; + } + + if (($html = $this->body($email->getHtmlBody())) !== '') { + // ponytail: the plain-text policy, not `rich`. Mail HTML is + // inline-styled by design, so the rich policy's sanitizer diff + // flags every message. Scripts, event handlers and hostile URLs + // are still caught; a mail-specific sanitizer profile is the + // upgrade if markup-level findings are ever wanted. + $parts[] = ['html', $this->scanHtml($html, 'default')]; + } + + foreach ($email->getAttachments() as $attachment) { + $parts[] = ['attachment:'.($attachment->getFilename() ?? 'unnamed'), $this->scanAttachment($attachment)]; + } + + $checks = array_map(static fn (array $part): CheckResult => new CheckResult( + check: $part[0], + status: $part[1]->status(), + threats: $part[1]->threats(), + metadata: ['scan_id' => (string) $part[1]->scanId()], + durationMs: $part[1]->duration(), + ), $parts); + + return ScanResult::fromChecks( + ScanContext::for(ScanType::Email, 'default'), + $checks, + 'email', + (hrtime(true) - $started) / 1e6, + ); + } + // --------------------------------------------------------------------- // Queued scanning // --------------------------------------------------------------------- @@ -384,6 +438,37 @@ private function reference(UploadedFile|FileReference|string $file): FileReferen }; } + /** @param resource|string|null $body */ + private function body(mixed $body): string + { + return is_resource($body) ? (string) stream_get_contents($body, null, 0) : (string) $body; + } + + private function scanAttachment(DataPart $attachment): ScanResult + { + // No dots in the prefix: the double-extension check reads the name. + $path = tempnam(sys_get_temp_dir(), 'cs-mail-'); + + if ($path === false || file_put_contents($path, $attachment->getBody()) === false) { + return ScanResult::failure( + ScanContext::for(ScanType::File, 'default'), + 'The attachment could not be written to a temporary file.', + ); + } + + try { + // The sender's filename and type are evidence for the checks, + // never trusted and never used as a path. + return $this->scanFile(FileReference::fromPath( + $path, + $attachment->getFilename() ?? 'unnamed', + $attachment->getContentType(), + )); + } finally { + @unlink($path); + } + } + private function policyName(FilePolicy|string|null $policy): ?string { return $policy instanceof FilePolicy ? $policy->name() : $policy; diff --git a/src/ContentSecurityServiceProvider.php b/src/ContentSecurityServiceProvider.php index d000ea4..4f96c27 100644 --- a/src/ContentSecurityServiceProvider.php +++ b/src/ContentSecurityServiceProvider.php @@ -6,6 +6,7 @@ use Illuminate\Console\Scheduling\Schedule; use Illuminate\Contracts\Container\Container; +use Illuminate\Mail\Events\MessageSending; use Illuminate\Support\ServiceProvider; use Inertia\Inertia; use LaravelPlus\ContentSecurity\Console\Commands\CleanupQuarantineCommand; @@ -40,6 +41,7 @@ use LaravelPlus\ContentSecurity\File\Malware\MalwareScannerManager; use LaravelPlus\ContentSecurity\File\Pdf\PdfInspector; use LaravelPlus\ContentSecurity\Listeners\LogSecurityEvent; +use LaravelPlus\ContentSecurity\Listeners\ScanOutgoingMail; use LaravelPlus\ContentSecurity\Pipeline\CheckRegistry; use LaravelPlus\ContentSecurity\Pipeline\PipelineRunner; use LaravelPlus\ContentSecurity\Repositories\ConfigPolicyRepository; @@ -120,6 +122,9 @@ public function boot(): void $this->registerSchedule(); $this->app->make('events')->subscribe(LogSecurityEvent::class); + // Always registered; it checks `mail.scan_outbound` itself, so the + // switch works at runtime and not only at boot. + $this->app->make('events')->listen(MessageSending::class, ScanOutgoingMail::class); // Policies resolve through the repository unless the host has // registered its own resolver, which still wins. diff --git a/src/Domain/Scan/ScanType.php b/src/Domain/Scan/ScanType.php index 0f2ab78..8a2b210 100644 --- a/src/Domain/Scan/ScanType.php +++ b/src/Domain/Scan/ScanType.php @@ -10,6 +10,7 @@ enum ScanType: string case Text = 'text'; case Html = 'html'; case Url = 'url'; + case Email = 'email'; public function label(): string { @@ -18,6 +19,7 @@ public function label(): string self::Text => 'Text', self::Html => 'HTML', self::Url => 'URL', + self::Email => 'Email', }; } } diff --git a/src/Facades/ContentSecurity.php b/src/Facades/ContentSecurity.php index 6c9ff08..abbe3fd 100644 --- a/src/Facades/ContentSecurity.php +++ b/src/Facades/ContentSecurity.php @@ -17,6 +17,7 @@ use LaravelPlus\ContentSecurity\Pipeline\CheckRegistry; use LaravelPlus\ContentSecurity\Support\HookRegistry; use LaravelPlus\ContentSecurity\Support\ScannerHealth; +use Symfony\Component\Mime\Email; /** * @method static ScanResult scanFile(UploadedFile|FileReference|string $file, FilePolicy|string|null $policy = null) @@ -28,6 +29,7 @@ * @method static string sanitizeHtml(string $html) * @method static ScanResult scanUrl(string $url) * @method static bool isSafeUrl(string $url) + * @method static ScanResult scanEmail(Email $email) * @method static ScanId queue(UploadedFile|FileReference|string $file, FilePolicy|string|null $policy = null) * @method static MalwareScanner scanner(string|null $name = null) * @method static list health() diff --git a/src/Listeners/ScanOutgoingMail.php b/src/Listeners/ScanOutgoingMail.php new file mode 100644 index 0000000..9f6c0b8 --- /dev/null +++ b/src/Listeners/ScanOutgoingMail.php @@ -0,0 +1,53 @@ +security->scanEmail($event->message); + + if ($result->isClean()) { + // null, not true: `until()` stops at the first non-null answer, + // and other MessageSending listeners still deserve their turn. + return null; + } + + /** @var string|null $channel */ + $channel = config('content-security.logging.channel'); + + ($channel === null ? $this->log->driver() : $this->log->channel($channel)) + ->warning('content-security.mail.blocked', [ + 'scan_id' => (string) $result->scanId(), + 'status' => $result->status()->value, + 'parts' => array_map(static fn ($check): string => $check->check.'='.$check->status->value, $result->checks()), + ]); + + return false; + } +} diff --git a/tests/Feature/ScanEmailTest.php b/tests/Feature/ScanEmailTest.php new file mode 100644 index 0000000..f29f0ed --- /dev/null +++ b/tests/Feature/ScanEmailTest.php @@ -0,0 +1,120 @@ +> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n"; +} + +function mailScanner(MalwareScanner $scanner): void +{ + ContentSecurity::extend('clamav', fn (): MalwareScanner => $scanner); + config()->set('content-security.malware.default', 'clamav'); + config()->set('content-security.malware.drivers.clamav', ['driver' => 'clamav']); +} + +/** What Laravel's markdown mail actually produces: a head, a style block, inline styles everywhere. */ +function styledMail(): Email +{ + return (new Email) + ->subject('Your invoice') + ->text('Your invoice is attached. View it at http://localhost/invoices/1') + ->html('' + .'
' + .'View invoice' + .'
') + ->attach(pdf(), 'invoice.pdf', 'application/pdf'); +} + +function parts(ScanResult $result): array +{ + return array_combine( + array_map(fn ($check) => $check->check, $result->checks()), + array_map(fn ($check) => $check->status, $result->checks()), + ); +} + +it('passes an ordinary styled mail with an attachment', function (): void { + mailScanner(FakeMalwareScanner::clean()); + + $result = ContentSecurity::scanEmail(styledMail()); + + expect($result->isClean())->toBeTrue() + ->and($result->type())->toBe(ScanType::Email) + ->and(array_keys(parts($result)))->toBe(['subject', 'text', 'html', 'attachment:invoice.pdf']); +}); + +it('reports the infected attachment and marks the whole mail', function (): void { + mailScanner(FakeMalwareScanner::infected('Win.Test.EICAR_HDB-1')); + + $result = ContentSecurity::scanEmail(styledMail()); + + expect($result->isClean())->toBeFalse() + ->and(parts($result)['subject'])->toBe(ScanStatus::Clean) + ->and(parts($result)['attachment:invoice.pdf'])->not->toBe(ScanStatus::Clean); + + $names = array_map(fn ($threat) => $threat->name, $result->threats()); + expect($names)->toContain('Win.Test.EICAR_HDB-1'); +}); + +it('fails closed when the engine cannot scan an attachment', function (): void { + mailScanner(FakeMalwareScanner::unavailable()); + + expect(ContentSecurity::scanEmail(styledMail())->isClean())->toBeFalse(); +}); + +it('flags hostile markup in the html body', function (): void { + $result = ContentSecurity::scanEmail( + (new Email)->subject('Hi')->html('

Hello

'), + ); + + expect($result->isClean())->toBeFalse() + ->and(parts($result)['html'])->not->toBe(ScanStatus::Clean); +}); + +it('cancels outbound mail that is not clean, and only when switched on', function (): void { + config()->set('mail.default', 'array'); + mailScanner(FakeMalwareScanner::infected()); + + $send = fn () => Mail::raw('See attached.', fn ($message) => $message + ->to('client@example.com') + ->subject('Invoice') + ->attachData(pdf(), 'invoice.pdf', ['mime' => 'application/pdf'])); + + expect($send())->not->toBeNull(); + + config()->set('content-security.mail.scan_outbound', true); + + expect($send())->toBeNull(); +}); + +it('sends clean outbound mail when switched on', function (): void { + config()->set('mail.default', 'array'); + config()->set('content-security.mail.scan_outbound', true); + mailScanner(FakeMalwareScanner::clean()); + + expect(Mail::raw('Hello there.', fn ($message) => $message->to('client@example.com')->subject('Hello'))) + ->not->toBeNull(); +}); + +it('does not read css or prose as urls, but still catches payload schemes', function (string $text, bool $clean): void { + expect(ContentSecurity::scanText($text)->isClean())->toBe($clean); +})->with([ + 'inline css' => ['Hi', true], + 'prose' => ['Meeting at time:10am, ratio 16:9', true], + 'https link' => ['See https://example.com/docs', true], + 'javascript uri' => ['click javascript:alert(1)', false], + 'data uri' => ['open data:text/html;base64,PHNjcmlwdD4=', false], + 'ftp link' => ['grab ftp://example.com/file', false], +]);