Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions src/Transport/CidImageEmbedder.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

class CidImageEmbedder
{
private const MAX_LOCAL_IMAGE_BYTES = 5 * 1024 * 1024;

/**
* Parse HTML, extract embedded base64 or local images, replace src with cid: references,
* and produce attachment definitions for mail transport.
Expand Down Expand Up @@ -63,11 +65,11 @@ public static function embed(string $html, ?string $basePath = null): array
}

// Case 2: Local relative file path (if basePath is provided and file exists)
if ($basePath !== null && ! str_starts_with($src, 'http://') && ! str_starts_with($src, 'https://')) {
$filePath = rtrim($basePath, '/').'/'.ltrim($src, '/');
if (file_exists($filePath) && is_readable($filePath)) {
if ($basePath !== null) {
$filePath = self::resolveLocalImage($basePath, $src);
if ($filePath !== null) {
$content = (string) file_get_contents($filePath);
$mime = mime_content_type($filePath) ?: 'image/png';
$mime = (string) mime_content_type($filePath);
$fileName = basename($filePath);
$hash = substr(md5($content), 0, 12);
$cid = "img_{$hash}@{$cidDomain}";
Expand All @@ -94,4 +96,31 @@ public static function embed(string $html, ?string $basePath = null): array
'attachments' => $attachments,
];
}

/**
* Resolve a relative image path inside the base path, or null when it must not be embedded.
*
* The template is untrusted input, so the file must stay inside the base directory (after symlinks
* and ".." are resolved), be a regular readable file of a modest size, and really be an image.
*/
private static function resolveLocalImage(string $basePath, string $src): ?string
{
// URLs, protocol-relative addresses, stream wrappers and NUL bytes are never local paths.
if (str_contains($src, "\0") || str_starts_with($src, '//') || preg_match('/^[a-z][a-z0-9+.\-]*:/i', $src)) {
return null;
}

$root = realpath($basePath);
$file = $root === false ? false : realpath(rtrim($basePath, '/').'/'.ltrim($src, '/'));

if ($root === false || $file === false || ! str_starts_with($file, rtrim($root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR)) {
return null;
}

if (! is_file($file) || ! is_readable($file) || filesize($file) > self::MAX_LOCAL_IMAGE_BYTES) {
return null;
}

return str_starts_with((string) mime_content_type($file), 'image/') ? $file : null;
}
}
61 changes: 61 additions & 0 deletions tests/Unit/EmailBuilderAdvancedEnterpriseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -668,3 +668,64 @@ public function render(string $html, array $devices = []): array
expect($mailable->compiledHtml)->toContain('src="cid:img_');
expect($mailable->customAttachments)->not->toBeEmpty();
});

describe('CidImageEmbedder local files', function () {
beforeEach(function () {
$this->root = sys_get_temp_dir().'/cid-embed-'.bin2hex(random_bytes(4));
mkdir($this->root.'/base/img', 0777, true);
file_put_contents(
$this->root.'/base/img/logo.png',
base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==')
);
file_put_contents($this->root.'/secret.txt', 'top secret');
file_put_contents($this->root.'/base/img/notes.txt', 'plain text, not an image');
$this->base = $this->root.'/base';
});

afterEach(function () {
foreach ([$this->root.'/base/img/logo.png', $this->root.'/base/img/notes.txt', $this->root.'/secret.txt'] as $file) {
@unlink($file);
}
@rmdir($this->root.'/base/img');
@rmdir($this->root.'/base');
@rmdir($this->root);
});

it('embeds an image inside the base path', function () {
$result = MailBuilder::embedCidImages('<img src="img/logo.png">', $this->base);

expect($result['attachments'])->toHaveCount(1)
->and($result['attachments'][0]['mime'])->toBe('image/png')
->and($result['html'])->toContain('src="cid:img_');
});

it('does not embed files outside the base path', function (string $src) {
$html = '<img src="'.$src.'">';

expect(MailBuilder::embedCidImages($html, $this->base))
->toBe(['html' => $html, 'attachments' => []]);
})->with([
'parent traversal' => '../secret.txt',
'deep traversal' => 'img/../../secret.txt',
'stream wrapper' => 'php://filter/resource=img/logo.png',
'file scheme' => 'file:///etc/hosts',
'protocol-relative' => '//example.com/logo.png',
]);

it('does not embed a symlink that leaves the base path', function () {
symlink($this->root.'/secret.txt', $this->base.'/img/link.png');
$html = '<img src="img/link.png">';

$result = MailBuilder::embedCidImages($html, $this->base);
@unlink($this->base.'/img/link.png');

expect($result)->toBe(['html' => $html, 'attachments' => []]);
});

it('does not embed a file that is not an image', function () {
$html = '<img src="img/notes.txt">';

expect(MailBuilder::embedCidImages($html, $this->base))
->toBe(['html' => $html, 'attachments' => []]);
});
});
Loading