Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

feat: improve S3 restore path handling and validation state

Andras Bacsai875351188fbd
diff --git a/app/Events/RestoreJobFinished.php b/app/Events/RestoreJobFinished.php
index e17aef9045..cc4be80298 100644
--- a/app/Events/RestoreJobFinished.php
+++ b/app/Events/RestoreJobFinished.php
@@ -22,11 +22,11 @@ class RestoreJobFinished
$commands = [];
if (isSafeTmpPath($scriptPath)) {
- $commands[] = "docker exec {$container} sh -c 'rm {$scriptPath} 2>/dev/null || true'";
+ $commands[] = "docker exec {$container} sh -c 'rm ".escapeshellarg($scriptPath)." 2>/dev/null || true'";
}
if (isSafeTmpPath($tmpPath)) {
- $commands[] = "docker exec {$container} sh -c 'rm {$tmpPath} 2>/dev/null || true'";
+ $commands[] = "docker exec {$container} sh -c 'rm ".escapeshellarg($tmpPath)." 2>/dev/null || true'";
}
if (! empty($commands)) {
diff --git a/app/Events/S3RestoreJobFinished.php b/app/Events/S3RestoreJobFinished.php
index a672f472f2..e1f8445585 100644
--- a/app/Events/S3RestoreJobFinished.php
+++ b/app/Events/S3RestoreJobFinished.php
@@ -27,21 +27,21 @@ class S3RestoreJobFinished
// Ensure helper container is removed (may already be gone from inline cleanup)
if (filled($containerName)) {
- $commands[] = "docker rm -f {$containerName} 2>/dev/null || true";
+ $commands[] = 'docker rm -f '.escapeshellarg($containerName).' 2>/dev/null || true';
}
// Clean up server temp file if still exists (should already be cleaned)
if (isSafeTmpPath($serverTmpPath)) {
- $commands[] = "rm -f {$serverTmpPath} 2>/dev/null || true";
+ $commands[] = 'rm -f '.escapeshellarg($serverTmpPath).' 2>/dev/null || true';
}
// Clean up any remaining files in database container (may already be cleaned)
if (filled($container)) {
if (isSafeTmpPath($containerTmpPath)) {
- $commands[] = "docker exec {$container} rm -f {$containerTmpPath} 2>/dev/null || true";
+ $commands[] = 'docker exec '.escapeshellarg($container).' rm -f '.escapeshellarg($containerTmpPath).' 2>/dev/null || true';
}
if (isSafeTmpPath($scriptPath)) {
- $commands[] = "docker exec {$container} rm -f {$scriptPath} 2>/dev/null || true";
+ $commands[] = 'docker exec '.escapeshellarg($container).' rm -f '.escapeshellarg($scriptPath).' 2>/dev/null || true';
}
}
diff --git a/app/Livewire/Project/Database/Import.php b/app/Livewire/Project/Database/Import.php
index b13c990f6e..01ddb7f5df 100644
--- a/app/Livewire/Project/Database/Import.php
+++ b/app/Livewire/Project/Database/Import.php
@@ -280,6 +280,23 @@ EOD;
}
}
+ public function updatedS3Path($value)
+ {
+ // Reset validation state when path changes
+ $this->s3FileSize = null;
+
+ // Ensure path starts with a slash
+ if ($value !== null && $value !== '') {
+ $this->s3Path = str($value)->trim()->start('/')->value();
+ }
+ }
+
+ public function updatedS3StorageId()
+ {
+ // Reset validation state when storage changes
+ $this->s3FileSize = null;
+ }
+
public function checkS3File()
{
if (! $this->s3StorageId) {
diff --git a/app/Models/S3Storage.php b/app/Models/S3Storage.php
index de27bbca66..47652eb358 100644
--- a/app/Models/S3Storage.php
+++ b/app/Models/S3Storage.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Traits\HasSafeStringAttribute;
+use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Storage;
@@ -41,6 +42,19 @@ class S3Storage extends BaseModel
return "{$this->endpoint}/{$this->bucket}";
}
+ protected function path(): Attribute
+ {
+ return Attribute::make(
+ set: function (?string $value) {
+ if ($value === null || $value === '') {
+ return null;
+ }
+
+ return str($value)->trim()->start('/')->value();
+ }
+ );
+ }
+
public function testConnection(bool $shouldSave = false)
{
try {
diff --git a/bootstrap/helpers/shared.php b/bootstrap/helpers/shared.php
index 29667a581e..1b23247faf 100644
--- a/bootstrap/helpers/shared.php
+++ b/bootstrap/helpers/shared.php
@@ -3250,18 +3250,16 @@ function isSafeTmpPath(?string $path): bool
$dirPath = dirname($resolvedPath);
// If the directory exists, resolve it via realpath to catch symlink attacks
- if (file_exists($resolvedPath) || is_dir($dirPath)) {
+ if (is_dir($dirPath)) {
// For existing paths, resolve to absolute path to catch symlinks
- if (is_dir($dirPath)) {
- $realDir = realpath($dirPath);
- if ($realDir === false) {
- return false;
- }
+ $realDir = realpath($dirPath);
+ if ($realDir === false) {
+ return false;
+ }
- // Check if the real directory is within /tmp (or its canonical path)
- if (! str($realDir)->startsWith('/tmp') && ! str($realDir)->startsWith($canonicalTmpPath)) {
- return false;
- }
+ // Check if the real directory is within /tmp (or its canonical path)
+ if (! str($realDir)->startsWith('/tmp') && ! str($realDir)->startsWith($canonicalTmpPath)) {
+ return false;
}
}
diff --git a/resources/views/livewire/project/database/import.blade.php b/resources/views/livewire/project/database/import.blade.php
index 6e53d516a0..b3c21e93eb 100644
--- a/resources/views/livewire/project/database/import.blade.php
+++ b/resources/views/livewire/project/database/import.blade.php
@@ -173,7 +173,7 @@
<div x-show="restoreType === 's3'" class="pt-6">
<h3>Restore from S3</h3>
<div class="flex flex-col gap-2 pt-2">
- <x-forms.select label="S3 Storage" wire:model="s3StorageId">
+ <x-forms.select label="S3 Storage" wire:model.live="s3StorageId">
<option value="">Select S3 Storage</option>
@foreach ($availableS3Storages as $storage)
<option value="{{ $storage->id }}">{{ $storage->name }}
@@ -186,7 +186,8 @@
<x-forms.input label="S3 File Path (within bucket)"
helper="Path to the backup file in your S3 bucket, e.g., /backups/database-2025-01-15.gz"
- placeholder="/backups/database-backup.gz" wire:model='s3Path'></x-forms.input>
+ placeholder="/backups/database-backup.gz" wire:model.blur='s3Path'
+ wire:keydown.enter='checkS3File'></x-forms.input>
<div class="flex gap-2">
<x-forms.button class="w-full" wire:click='checkS3File' x-bind:disabled="!s3StorageId || !s3Path">
diff --git a/tests/Unit/RestoreJobFinishedShellEscapingTest.php b/tests/Unit/RestoreJobFinishedShellEscapingTest.php
new file mode 100644
index 0000000000..e45ec966b0
--- /dev/null
+++ b/tests/Unit/RestoreJobFinishedShellEscapingTest.php
@@ -0,0 +1,118 @@
+<?php
+
+/**
+ * Security tests for shell metacharacter escaping in restore events.
+ *
+ * These tests verify that escapeshellarg() properly neutralizes shell injection
+ * attempts in paths that pass isSafeTmpPath() validation.
+ */
+describe('Shell metacharacter escaping in restore events', function () {
+ it('demonstrates that malicious paths can pass isSafeTmpPath but are neutralized by escapeshellarg', function () {
+ // This path passes isSafeTmpPath() validation (it's within /tmp/, no .., no null bytes)
+ $maliciousPath = "/tmp/file'; whoami; '";
+
+ // Path validation passes - it's a valid /tmp/ path
+ expect(isSafeTmpPath($maliciousPath))->toBeTrue();
+
+ // But when escaped, the shell metacharacters become literal strings
+ $escaped = escapeshellarg($maliciousPath);
+
+ // The escaped version wraps in single quotes and escapes internal single quotes
+ expect($escaped)->toBe("'/tmp/file'\\''; whoami; '\\'''");
+
+ // Building a command with escaped path is safe
+ $command = "rm -f {$escaped}";
+
+ // The command contains the quoted path, not an unquoted injection
+ expect($command)->toStartWith("rm -f '");
+ expect($command)->toEndWith("'");
+ });
+
+ it('escapes paths with semicolon injection attempts', function () {
+ $path = '/tmp/backup; rm -rf /; echo';
+ expect(isSafeTmpPath($path))->toBeTrue();
+
+ $escaped = escapeshellarg($path);
+ expect($escaped)->toBe("'/tmp/backup; rm -rf /; echo'");
+
+ // The semicolons are inside quotes, so they're treated as literals
+ $command = "rm -f {$escaped}";
+ expect($command)->toBe("rm -f '/tmp/backup; rm -rf /; echo'");
+ });
+
+ it('escapes paths with backtick command substitution attempts', function () {
+ $path = '/tmp/backup`whoami`.sql';
+ expect(isSafeTmpPath($path))->toBeTrue();
+
+ $escaped = escapeshellarg($path);
+ expect($escaped)->toBe("'/tmp/backup`whoami`.sql'");
+
+ // Backticks inside single quotes are not executed
+ $command = "rm -f {$escaped}";
+ expect($command)->toBe("rm -f '/tmp/backup`whoami`.sql'");
+ });
+
+ it('escapes paths with $() command substitution attempts', function () {
+ $path = '/tmp/backup$(id).sql';
+ expect(isSafeTmpPath($path))->toBeTrue();
+
+ $escaped = escapeshellarg($path);
+ expect($escaped)->toBe("'/tmp/backup\$(id).sql'");
+
+ // $() inside single quotes is not executed
+ $command = "rm -f {$escaped}";
+ expect($command)->toBe("rm -f '/tmp/backup\$(id).sql'");
+ });
+
+ it('escapes paths with pipe injection attempts', function () {
+ $path = '/tmp/backup | cat /etc/passwd';
+ expect(isSafeTmpPath($path))->toBeTrue();
+
+ $escaped = escapeshellarg($path);
+ expect($escaped)->toBe("'/tmp/backup | cat /etc/passwd'");
+
+ // Pipe inside single quotes is treated as literal
+ $command = "rm -f {$escaped}";
+ expect($command)->toBe("rm -f '/tmp/backup | cat /etc/passwd'");
+ });
+
+ it('escapes paths with newline injection attempts', function () {
+ $path = "/tmp/backup\nwhoami";
+ expect(isSafeTmpPath($path))->toBeTrue();
+
+ $escaped = escapeshellarg($path);
+ // Newline is preserved inside single quotes
+ expect($escaped)->toContain("\n");
+ expect($escaped)->toStartWith("'");
+ expect($escaped)->toEndWith("'");
+ });
+
+ it('handles normal paths without issues', function () {
+ $normalPaths = [
+ '/tmp/restore-backup.sql',
+ '/tmp/restore-script.sh',
+ '/tmp/database-dump-abc123.sql',
+ '/tmp/deeply/nested/path/to/file.sql',
+ ];
+
+ foreach ($normalPaths as $path) {
+ expect(isSafeTmpPath($path))->toBeTrue();
+
+ $escaped = escapeshellarg($path);
+ // Normal paths are just wrapped in single quotes
+ expect($escaped)->toBe("'{$path}'");
+ }
+ });
+
+ it('escapes container names with injection attempts', function () {
+ // Container names are not validated by isSafeTmpPath, so escaping is critical
+ $maliciousContainer = 'container"; rm -rf /; echo "pwned';
+ $escaped = escapeshellarg($maliciousContainer);
+
+ expect($escaped)->toBe("'container\"; rm -rf /; echo \"pwned'");
+
+ // Building a docker command with escaped container is safe
+ $command = "docker rm -f {$escaped}";
+ expect($command)->toBe("docker rm -f 'container\"; rm -rf /; echo \"pwned'");
+ });
+});