A free open source IT asset/license management system
Signature Capture: Fixed FD-57825 / 76rv-6364 - validate signature png size
snipefd61abe573a1
diff --git a/app/Http/Controllers/Account/AcceptanceController.php b/app/Http/Controllers/Account/AcceptanceController.phpindex 99f683b1a2..ae05665a23 100644--- a/app/Http/Controllers/Account/AcceptanceController.php+++ b/app/Http/Controllers/Account/AcceptanceController.php@@ -101,9 +101,16 @@ class AcceptanceController extends Controller// Bound the note server-side. Unbounded notes were reaching synchronous// CommonMark rendering in the acceptance notification email and// consuming worker CPU on a per-request basis (defense in depth against- // the parser CVE; the commonmark bump to 2.9.0 is the primary fix).+ // the parser CVE, with the commonmark bump to 2.9.0 as the primary fix).+ //+ // Bound signature_output as well. Legitimate signaturepad canvas output+ // is well under 100 KB base64. The 2 MB cap here keeps a crafted+ // payload from forcing base64_decode and the downstream image+ // flattening into very large allocations before any dimension check+ // runs.$request->validate(['note' => 'nullable|string|max:1000',+ 'signature_output' => 'nullable|string|max:2097152',]);$acceptance = CheckoutAcceptance::find($id);@@ -177,7 +184,26 @@ class AcceptanceController extends Controllerreturn redirect()->back()->with('error', trans('general.shitty_browser'));}- $decoded_image = $this->flattenSignatureBackgroundToWhite($decoded_image);+ // Validate the decoded bytes are an image and bound dimensions+ // BEFORE allocating any pixel buffer. getimagesizefromstring+ // reads headers only, so a crafted payload with large declared+ // width/height is rejected without imagecreatefromstring+ // decoding the raster or the flatten path allocating a second+ // same-size buffer.+ $imgInfo = @getimagesizefromstring($decoded_image);+ if ($imgInfo === false || $imgInfo[0] > 2000 || $imgInfo[1] > 2000) {+ return redirect()->back()->with('error', trans('general.shitty_browser'));+ }++ $flattened = $this->flattenSignatureBackgroundToWhite($decoded_image);+ if ($flattened !== null) {+ $decoded_image = $flattened;+ }+ // Keep the original validated bytes if flattening is unavailable+ // (no GD) or allocation failed. Dimensions already clear the+ // 2000x2000 cap, and getimagesizefromstring already confirmed+ // the content is a real image rather than attacker-supplied+ // text passed through base64.$encodedSignatureImage = base64_encode($decoded_image);// Storage::put returns false on silent write failures on@@ -283,7 +309,7 @@ class AcceptanceController extends Controller// rolled back, since cleaning up on the loser side would race// the winner reading the same file. Not ideal, but the alternative// is a more complex transactional file store that can roll back on failure.- if (!$acceptance->accept($sig_filename, $item->getEula(), $pdf_filename, $request->input('note'))) {+ if (! $acceptance->accept($sig_filename, $item->getEula(), $pdf_filename, $request->input('note'))) {return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.asset_already_accepted'));}@@ -314,7 +340,7 @@ class AcceptanceController extends Controller// declinedCheckout side effects internally for qty > 1. If another// request already finalized this row, bail before notifications// and events fire.- if (!$acceptance->decline($sig_filename, $request->input('note'))) {+ if (! $acceptance->decline($sig_filename, $request->input('note'))) {return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.asset_already_accepted'));}@@ -468,16 +494,21 @@ class AcceptanceController extends Controllerreturn [(int) $acceptance->checkoutable_id, session('sign_in_place_resource_type', 'Assets')];}- private function flattenSignatureBackgroundToWhite(string $signatureBinary): string+ private function flattenSignatureBackgroundToWhite(string $signatureBinary): ?string{+ // Fail-closed on every unexpected branch rather than returning+ // the original bytes. The previous shape fell through on+ // decode failure, which let non-image input survive to the+ // Storage::put below and land in private_uploads/signatures+ // with a .png filename.if (! function_exists('imagecreatefromstring') || ! function_exists('imagecreatetruecolor')) {- return $signatureBinary;+ return null;}$source = @imagecreatefromstring($signatureBinary);if ($source === false) {- return $signatureBinary;+ return null;}$width = imagesx($source);@@ -487,7 +518,7 @@ class AcceptanceController extends Controllerif ($flattened === false) {imagedestroy($source);- return $signatureBinary;+ return null;}$white = imagecolorallocate($flattened, 255, 255, 255);diff --git a/tests/Feature/CheckoutAcceptances/AcceptanceSignatureImageValidationTest.php b/tests/Feature/CheckoutAcceptances/AcceptanceSignatureImageValidationTest.phpnew file mode 100644index 0000000000..8ec43fceeb--- /dev/null+++ b/tests/Feature/CheckoutAcceptances/AcceptanceSignatureImageValidationTest.php@@ -0,0 +1,157 @@+<?php++namespace Tests\Feature\CheckoutAcceptances;++use App\Models\Asset;+use App\Models\CheckoutAcceptance;+use App\Models\Setting;+use App\Models\User;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++class AcceptanceSignatureImageValidationTest extends TestCase+{+ private function pendingAcceptance(User $target): CheckoutAcceptance+ {+ $asset = Asset::factory()->assignedToUser($target)->create();++ return CheckoutAcceptance::factory()->pending()->for($asset, 'checkoutable')->create([+ 'assigned_to_id' => $target->id,+ ]);+ }++ private function enableRequiredSignatures(): void+ {+ $settings = Setting::query()->firstOrFail();+ $settings->require_accept_signature = 1;+ $settings->save();+ Setting::$_cache = null;+ }++ private function tinyPng(int $width = 2, int $height = 2): string+ {+ $canvas = imagecreatetruecolor($width, $height);+ ob_start();+ imagepng($canvas);+ $bytes = (string) ob_get_clean();+ imagedestroy($canvas);++ return $bytes;+ }++ /**+ * Craft a PNG whose IHDR declares the given dimensions. Used to+ * exercise the dimension cap without actually allocating a huge+ * pixel buffer in the test itself. getimagesizefromstring reads+ * the IHDR header and reports these declared dimensions, so the+ * cap triggers before any decoder opens the raster.+ */+ private function pngWithIhdrDimensions(int $width, int $height): string+ {+ $signature = "\x89PNG\r\n\x1a\n";+ $ihdrData = pack('NNCCCCC', $width, $height, 8, 2, 0, 0, 0);+ $ihdrChunk = pack('N', 13) . 'IHDR' . $ihdrData . pack('N', crc32('IHDR' . $ihdrData));+ $iendChunk = pack('N', 0) . 'IEND' . pack('N', crc32('IEND'));++ return $signature . $ihdrChunk . $iendChunk;+ }++ public function test_signature_output_with_non_image_bytes_is_rejected_and_nothing_is_written(): void+ {+ Storage::fake();+ $this->enableRequiredSignatures();++ $target = User::factory()->create();+ $acceptance = $this->pendingAcceptance($target);++ $marker = 'SNIPE-CAND-11-NOT-A-PNG';+ $payload = [+ 'asset_acceptance' => 'accepted',+ 'signature_output' => 'data:image/png;base64,' . base64_encode($marker),+ ];++ $this->actingAs($target)+ ->post(route('account.store-acceptance', $acceptance), $payload)+ ->assertSessionHas('error');++ $acceptance->refresh();+ $this->assertNull($acceptance->accepted_at, 'A rejected signature must not finalize the acceptance.');++ $written = Storage::disk()->files('private_uploads/signatures');+ $this->assertEmpty($written, 'A rejected signature must not land any file under signatures/.');+ }++ public function test_signature_output_with_oversized_declared_dimensions_is_rejected_before_decode(): void+ {+ Storage::fake();+ $this->enableRequiredSignatures();++ $target = User::factory()->create();+ $acceptance = $this->pendingAcceptance($target);++ // A PNG that declares 10000x10000 in its IHDR but is only a few+ // dozen bytes on the wire. getimagesizefromstring reports the+ // declared dimensions, the cap trips, and the request is+ // rejected without imagecreatefromstring ever running.+ $bombHeader = $this->pngWithIhdrDimensions(10000, 10000);+ $payload = [+ 'asset_acceptance' => 'accepted',+ 'signature_output' => 'data:image/png;base64,' . base64_encode($bombHeader),+ ];++ $this->actingAs($target)+ ->post(route('account.store-acceptance', $acceptance), $payload)+ ->assertSessionHas('error');++ $acceptance->refresh();+ $this->assertNull($acceptance->accepted_at);+ $this->assertEmpty(Storage::disk()->files('private_uploads/signatures'));+ }++ public function test_signature_output_exceeding_2mb_cap_is_rejected_by_validator(): void+ {+ Storage::fake();+ $this->enableRequiredSignatures();++ $target = User::factory()->create();+ $acceptance = $this->pendingAcceptance($target);++ $payload = [+ 'asset_acceptance' => 'accepted',+ 'signature_output' => 'data:image/png;base64,' . str_repeat('A', 2_100_000),+ ];++ $this->actingAs($target)+ ->post(route('account.store-acceptance', $acceptance), $payload)+ ->assertSessionHasErrors('signature_output');++ $acceptance->refresh();+ $this->assertNull($acceptance->accepted_at);+ }++ public function test_legitimate_tiny_png_signature_still_finalizes_acceptance(): void+ {+ // Companion: the fix must not break the happy path. A real tiny+ // PNG from the signaturepad canvas should continue to validate,+ // flatten, store, and finalize.+ Storage::fake();+ $this->enableRequiredSignatures();++ $target = User::factory()->create();+ $acceptance = $this->pendingAcceptance($target);++ $payload = [+ 'asset_acceptance' => 'accepted',+ 'signature_output' => 'data:image/png;base64,' . base64_encode($this->tinyPng()),+ ];++ $this->actingAs($target)+ ->post(route('account.store-acceptance', $acceptance), $payload)+ ->assertRedirectToRoute('account.accept')+ ->assertSessionHas('success');++ $acceptance->refresh();+ $this->assertNotNull($acceptance->accepted_at, 'A legitimate PNG signature must still finalize the acceptance.');+ $this->assertCount(1, Storage::disk()->files('private_uploads/signatures'));+ }+}diff --git a/tests/Feature/CheckoutAcceptances/AcceptanceStorageFailureTest.php b/tests/Feature/CheckoutAcceptances/AcceptanceStorageFailureTest.phpindex 6f6222a18a..702ed4f58d 100644--- a/tests/Feature/CheckoutAcceptances/AcceptanceStorageFailureTest.php+++ b/tests/Feature/CheckoutAcceptances/AcceptanceStorageFailureTest.php@@ -37,14 +37,18 @@ class AcceptanceStorageFailureTest extends TestCaseprivate function acceptPayloadWithSignature(): array{- // Minimal valid signature payload: a data URI containing base64-encoded- // bytes. flattenSignatureBackgroundToWhite is tolerant of arbitrary- // input because it treats non-decodable data as opaque bytes.- $body = base64_encode('signature-bytes');+ // AcceptanceController rejects signature_output whose decoded+ // bytes are not a real image, so this test needs a legitimate tiny+ // PNG to exercise the failure path. The actual image content is irrelevant to the test.+ $canvas = imagecreatetruecolor(2, 2);+ ob_start();+ imagepng($canvas);+ $signaturePng = (string) ob_get_clean();+ imagedestroy($canvas);return ['asset_acceptance' => 'accepted',- 'signature_output' => 'data:image/png;base64,'.$body,+ 'signature_output' => 'data:image/png;base64,' . base64_encode($signaturePng),];}