Repository navigation
Email content & attachment security: scanEmail() and outbound mail scanning #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: #!/bin/bash
set -euo pipefail
rg -n -C3 '"symfony/mime"|symfony/mime' composer.json composer.lock 2>/dev/null || true
rg -n -C5 'fopen|resource|stream_get_contents|DataPart|text\(|html\(' tests srcRepository: LaravelPlus/content-security Length of output: 27384 🏁 Script executed: set -euo pipefail
printf '%s\n' '--- dependency metadata ---'
rg -n -C4 'symfony/mime|symfony/framework-bundle|laravel/framework' composer.json composer.lock 2>/dev/null || true
printf '%s\n' '--- ContentSecurity email flow ---'
sed -n '300,470p' src/ContentSecurity.php
printf '%s\n' '--- DataPart and email-related references ---'
rg -n -C5 'scanEmail|scanAttachment|->getBody\(\)|getBody\(\)|body\(' src testsRepository: LaravelPlus/content-security Length of output: 14178 🏁 Script executed: set -euo pipefail
printf '%s\n' '--- dependency files ---'
git ls-files composer.json composer.lock
printf '%s\n' '--- composer manifest ---'
cat -n composer.json | sed -n '1,70p'
printf '%s\n' '--- listener path ---'
cat -n src/Listeners/ScanOutgoingMail.php | sed -n '1,90p'
printf '%s\n' '--- local Symfony source, if present ---'
find . -path '*/Symfony/Component/Mime/*' -o -path '*/symfony/mime/*' | head -40Repository: LaravelPlus/content-security Length of output: 5476 🌐 Web query:
💡 Result: <search_synthesis> <source_evidence> Citations:
🌐 Web query:
💡 Result: <search_synthesis> <source_evidence> Citations:
Preserve non-seekable MIME streams during scanning. Symfony Mime rewinds seekable resources before rendering, so ordinary seekable streams are not affected. It does not rewind non-seekable resources. 🤖 Prompt for AI Agents |
||
| } | ||
|
|
||
| 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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win Clean up the temporary file when the write fails. If Proposed fix- if ($path === false || file_put_contents($path, $attachment->getBody()) === false) {
+ if ($path === false) {
return ScanResult::failure(
ScanContext::for(ScanType::File, 'default'),
'The attachment could not be written to a temporary file.',
);
}
try {
+ if (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.',
+ );
+ }
+
// The sender's filename and type are evidence for the checks,🤖 Prompt for AI Agents |
||
| 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; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace LaravelPlus\ContentSecurity\Listeners; | ||
|
|
||
| use Illuminate\Log\LogManager; | ||
| use Illuminate\Mail\Events\MessageSending; | ||
| use LaravelPlus\ContentSecurity\ContentSecurity; | ||
|
|
||
| /** | ||
| * Scans every message Laravel is about to send and cancels the ones that are | ||
| * not clean. Returning false from MessageSending is Laravel's own way of | ||
| * stopping a send, so there is no mail pipeline to replace. | ||
| * | ||
| * Fail closed: a scanner that is down stops the mail too. The individual | ||
| * findings are already logged per part; this adds the one line that says a | ||
| * message did not go out. | ||
| */ | ||
| final readonly class ScanOutgoingMail | ||
| { | ||
| public function __construct( | ||
| private ContentSecurity $security, | ||
| private LogManager $log, | ||
| ) {} | ||
|
|
||
| public function handle(MessageSending $event): ?bool | ||
| { | ||
| if (! (bool) config('content-security.mail.scan_outbound', false)) { | ||
| return null; | ||
| } | ||
|
|
||
| $result = $this->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; | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: LaravelPlus/content-security
Length of output: 6895
🏁 Script executed:
Repository: LaravelPlus/content-security
Length of output: 13669
Reachability: External
Exploitability: Moderate
CWE: CWE-693
Fail closed when URL inspection is truncated.
UrlsCheckrecordstruncated=true, butFindings::isEmpty()checks only threats. Therefore, 50 clean URLs followed by a malicious URL produce a clean check, andScanOutgoingMailallows delivery. Promote truncation to a non-clean result.🤖 Prompt for AI Agents