Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
35 changes: 31 additions & 4 deletions app/Http/Controllers/SecurePathController.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Safe\Exceptions\FilesystemException;
use function Safe\realpath;

/**
* Controller responsible for serving files securely.
Expand All @@ -48,9 +50,7 @@ public function __invoke(SecurePathRequest $request, ?string $path)
throw new InvalidSignatureException();
}

if (is_null($path)) {
throw new WrongPathException();
}
$this->prevalidation_path($path);

if ($request->configs()->getValueAsBool('secure_image_link_enabled')) {
try {
Expand All @@ -60,7 +60,12 @@ public function __invoke(SecurePathRequest $request, ?string $path)
}
}

$file = Storage::disk(StorageDiskType::LOCAL->value)->path($path);
try {
$file = realpath(Storage::disk(StorageDiskType::LOCAL->value)->path($path));
} catch (FilesystemException) {
throw new WrongPathException();
}

$valid_path_start = Storage::disk(StorageDiskType::LOCAL->value)->path('');
if (!str_starts_with($file, $valid_path_start)) {
Log::error('Invalid path for secure path request.', [
Expand Down Expand Up @@ -104,4 +109,26 @@ private function signatureHasNotExpired(Request $request)

return !($expires !== null && $expires !== '' && Carbon::now()->getTimestamp() > $expires);
}

/**
* Validate the path.
*
* @param string|null $path
*
* @return void
*
* @throws WrongPathException
*/
private function prevalidation_path(?string $path): void
{
if (is_null($path)) {
throw new WrongPathException();
}

foreach (['..', '%2e', '%2f', '\\'] as $invalid_sequence) {
if (str_contains($path, $invalid_sequence)) {
throw new PathTraversalException('Invalid path for secure path request.');
}
}
}
}
9 changes: 9 additions & 0 deletions tests/Feature_v2/SecureImageLinksTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,13 @@ public function testDisabledSecureImageLinkIsForbidden(): void
$response = $this->get($broken_url);
$this->assertUnauthorized($response);
}

public function testPathTraversalIsForbidden(): void
{
$this->setTemporaryLink();
$path = URL::route('image', ['path' => 'c3/3d/c661c594a5a781cd44db06828783.png']);
$traversal_path = str_replace('c3/3d/c661c594a5a781cd44db06828783.png', '../.env', $path);
$response = $this->actingAs($this->userMayUpload1)->get($traversal_path);
$this->assertStatus($response, 418);
}
}
Loading