Security beyond the checklist in a Laravel app · Part 3 of 6
Injection and output: SQL in the search, a script in the page, a path and a shell
One mistake in four places: a search read as SQL, a note read as HTML, a filename read as a path, a filename read as a command. Each with the code, the mechanism, the test that proves the crossing, and the fix that puts input back where it is only ever data.
By Abhishek Fouzdar
Injection is what happens when something a user sent is read as code instead of as data: a search term read as SQL, a note read as HTML, a filename read as a shell command. In the 2025 OWASP Top 10 it is one category that gathers SQL, operating-system commands, cross-site scripting and more, because they are one mistake wearing different clothes. This part adds four features to NoteMini from part 2, each of which crosses the line in a different place, and for each shows the code, the mechanism, the test that proves the crossing, and the fix that redraws the line. A raw admin search, a print view, a legacy file link and a zip export.
1. The search read as SQL
The admin wants to find a user by name or email. The list query already exists, and adding a filter to it is one line:
public function index(Request $request)
{
$users = User::withCount('notes', 'teams');
if ($request->filled('q')) {
$q = $request->query('q');
$users->whereRaw("name like '%$q%' or email like '%$q%'");
}
return view('admin.users', ['users' => $users->orderBy('name')->get(), 'q' => $request->query('q', '')]);
}
whereRaw exists for the cases the query builder cannot express, and like '%…%' is awkward enough in the builder that reaching for a raw string feels justified. The cost is in the interpolation: $q is placed into the SQL text before the database parses it, so whatever structure $q contains becomes structure the database obeys. A value with a quote in it does not search for a quote; it ends the string literal and continues as SQL.
The mechanism is the whole of it. The database receives one string and parses it into a query; the question is only whether the user's input is inside a value the parser has already decided is data, or outside it where the parser is still deciding what is code. String interpolation puts it outside. A bound parameter puts it inside, permanently, because the database parses the query with a placeholder first and binds the value afterward, when parsing is over.
The test does not need a payload that reads the password column. It needs to show that input reaches the parser as structure, and an apostrophe does that:
it('treats the admin user search as data, not as SQL', function () {
$admin = User::factory()->create(['name' => 'Real Admin']);
$admin->forceFill(['is_admin' => true])->save();
User::factory()->create(['name' => 'Alice', 'email' => '[email protected]']);
// A term that matches nobody by name must not, through a quote, match everybody.
$this->actingAs($admin)->get('/admin/users?q='.urlencode("zzz%' or '1'='1"))->assertOk()
->assertDontSee('[email protected]');
// A name with an apostrophe must not reach the database as SQL and raise an error.
$this->actingAs($admin)->get('/admin/users?q='.urlencode("o'brien"))->assertOk();
});
⨯ it treats the admin user search as data, not as SQL
Expected response status code [200] but received 500.
The 500 is the proof. o'brien turned a valid query into an invalid one, which means the search term and the query are the same text, which means a search term that was valid SQL rather than invalid would run. A name is the gentlest possible demonstration, and it is a real one: the application breaks on an Irish surname before anyone malicious arrives.
The fix hands the structure back to the builder and the value to a binding:
if ($request->filled('q')) {
$q = $request->query('q');
$users->where(fn ($w) => $w->where('name', 'like', "%{$q}%")->orWhere('email', 'like', "%{$q}%"));
}
The % wildcards are part of the bound value, not the SQL, so they are wildcards and the user's % is a literal percent. The closure groups the two conditions so the orWhere cannot escape the rest of the query's where clauses, which is the other half of a correct filter and a bug in its own right when it is missing. whereRaw is not forbidden; it is for fixed SQL with bound parameters, whereRaw('score > ?', [$min]), never for SQL assembled from a request.
2. The note read as HTML
Notes are Markdown, and part 1 renders them through a method that strips raw HTML:
public function html(): string
{
return Str::markdown($this->body, ['html_input' => 'strip', 'allow_unsafe_links' => false]);
}
Then someone adds a print view, a clean page for the browser's print dialog, and writes the template the direct way:
<div class="note-body">{!! $note->body !!}</div>
{!! !!} is Blade's unescaped echo. The author reached for it because the body is Markdown and {{ }} would show the asterisks and hashes as literal text; unescaped output is how you render HTML you generated. The slip is that $note->body is not HTML the application generated. It is Markdown the user wrote, printed verbatim, and Markdown allows raw HTML inside it. The html() method that strips that raw HTML is right there on the model, and the print view did not call it; it echoed the field.
The mechanism is the same shape as the SQL one, moved to the browser. The note body is sent to the browser as part of the page's HTML, and the browser parses HTML into a document and runs any script it finds. If the user's input is inside a text node, the browser shows it; if it is a tag, the browser acts on it. {{ }} guarantees text by turning < into < before it is sent. {!! !!} sends the bytes as they are, so a <script> in the body is a <script> in the document, and it runs in the session of whoever opens the note, which for a shared note is anyone.
The test opens the print view for a note whose body contains a script, and asserts the script is not there as a tag:
it('renders a note print view with script as text, not as script', function () {
$alice = owner();
$note = Note::factory()->for($alice->teams->first())->for($alice, 'author')->create([
'body' => "Plan <script>document.title='owned'</script> <img src=x onerror=\"steal()\">",
]);
$html = $this->actingAs($alice)->get("/notes/{$note->id}/print")->assertOk()->getContent();
expect($html)->not->toContain('<script>document')->not->toContain('onerror=');
});
⨯ it renders a note print view with script as text, not as script
Expecting '<!doctype html>…</html>' not to contain '<script>document'.
The fix is to render the note the way the rest of the application does, through the method that already exists:
<div class="note-body">{!! $note->html() !!}</div>
Now the only HTML in the page is the HTML Str::markdown produced from the Markdown, with raw tags stripped and javascript: links refused. The unescaped echo is still there, and correctly: it is echoing HTML the application generated, which is what {!! !!} is for. The lesson is not "never use {!! !!}". It is that the thing inside it must be output the application produced and controls, never a field a user filled, and that when a model already has the method that produces safe HTML, every view renders through it. A grep for {!! is a two-minute audit that finds every place this decision was made.
3. The filename read as a path
The first version of attachments, before the id-based route in part 1, linked files by name under the note's folder. That route is still here, and it builds a filesystem path from the name in the URL:
public function legacyDownload(Request $request, Note $note): StreamedResponse
{
$this->authorize('view', $note);
return Storage::disk('local')->download('attachments/'.$note->id.'/'.$request->query('file'));
}
The authorisation is correct: a non-member cannot reach this note at all. The flaw is that $request->query('file') is joined into a path, and a path has structure of its own. The segment .. means the parent directory, and a filesystem obeys it exactly as a database obeys a quote. A file value of ../../../.env walks out of the note's folder, out of attachments, and reads whatever the process can read.
The mechanism, once more: the user's input is treated as structure, here the structure of a path, when the application meant it as data, here a filename to look up. The fix is the same in spirit as the bound parameter and the escaped echo: stop building the dangerous thing out of input. The name from the URL should select a record, not construct a path:
public function legacyDownload(Request $request, Note $note): StreamedResponse
{
$this->authorize('view', $note);
$attachment = $note->attachments()->where('original_name', $request->query('file'))->firstOrFail();
return Storage::disk('local')->download($attachment->path, $attachment->original_name);
}
The requested name is now a value in a where clause, matched against this note's attachments, and either it names one or the request is a 404. The path that gets served is the stored one, the uuid the server chose in part 1, which contains no user input and cannot point outside the attachments folder. The test tries three spellings of the walk and expects a 404 from each:
it('refuses to serve a file outside the note folder', function () {
Storage::fake('local');
$alice = owner();
$note = Note::factory()->for($alice->teams->first())->for($alice, 'author')->create();
foreach (['../../../.env', '..%2f..%2fcomposer.json', '....//....//.env'] as $probe) {
$this->actingAs($alice)->get("/notes/{$note->id}/file?file=".$probe)->assertNotFound();
}
});
The three spellings are there because the naive fix, "reject the string ..", is defeated by ....//, which many path normalisers collapse to ../, and by URL-encoding, which the framework decodes before the controller sees it. Rejecting bad input is a list you have to keep complete; selecting a known record is a decision that is complete by construction. The second kind of fix is the one that holds.
4. The filename read as a command
Attachments are stored under uuid names, so a download of all of a note's files as one zip would contain names like 9f3c…-.pdf. To make the zip readable, the export copies each file to its friendly name first, then zips the folder:
public function zip(Note $note): BinaryFileResponse
{
$this->authorize('view', $note);
$dir = storage_path('app/zip/'.Str::uuid());
mkdir($dir, 0700, true);
foreach ($note->attachments as $attachment) {
$source = Storage::disk('local')->path($attachment->path);
exec('cp '.$source.' '.$dir.'/'.$attachment->original_name);
}
$archive = $dir.'.zip';
exec('cd '.$dir.' && zip -r '.$archive.' .');
return response()->download($archive, $note->title.'.zip')->deleteFileAfterSend();
}
exec runs its argument through the shell, /bin/sh -c, which parses the string into commands, arguments, and the characters that separate and chain them. The copy uses the attachment's original name, and the original name came from the client at upload time, unchanged. A shell reading a filename is a shell reading whatever the uploader typed where a filename should be, including the characters that end one command and begin another.
The same mistake as the three before it: input placed where structure is parsed. The database parsed a string into SQL, the browser parsed a string into HTML, the filesystem parsed a string into a path, and here the shell parses a string into commands. The upload validated the file's type, which is right, but the client filename is separate from the file's content and was stored as given, so the validation never saw it.
The test uploads a normal file, sets its stored name to one that carries a shell payload the way a crafted upload would, asks for the zip, and checks that the payload did not run:
it('zips attachments without running a filename as a command', function () {
$alice = owner();
$note = Note::factory()->for($alice->teams->first())->for($alice, 'author')->create();
$marker = storage_path('app/pwned-'.uniqid());
$this->actingAs($alice)->post("/notes/{$note->id}/attachments", [
'file' => UploadedFile::fake()->createWithContent('safe.txt', 'hi'),
])->assertRedirect();
$note->attachments()->sole()->update(['original_name' => 'notes; touch '.$marker.' #.txt']);
$this->actingAs($alice)->get("/notes/{$note->id}/attachments.zip")->assertOk();
expect(file_exists($marker))->toBeFalse();
});
⨯ it zips attachments without running a filename as a command
Failed asserting that true is false.
The marker file exists, which means the part of the name after the semicolon ran as its own command. The fix removes the shell from the operation entirely:
$names = [];
foreach ($note->attachments as $attachment) {
$name = $attachment->id.'-'.basename($attachment->original_name);
copy(Storage::disk('local')->path($attachment->path), $dir.'/'.$name);
$names[] = $name;
}
$archive = $dir.'.zip';
Process::path($dir)->run(array_merge(['zip', '-q', $archive], $names));
Two changes. The copy is PHP's copy(), a function call with two string arguments and no shell to parse them. The zip runs through Laravel's Process with the command as an array, which Symfony's process layer passes to the operating system as a list of arguments directly, with no shell in between; there is no string for ; or $() to live in, so an argument is only ever an argument. basename on the name is defence in depth, stripping any path separators before the name is used as a filename at all. The rule that falls out: a command built from a string, with user input anywhere in the string, is the bug; a command built as a list of arguments is not, and Process wants the list.
The results
The attack suite after this part:
Tests: 21 passed (76 assertions)
Four new tests, from seventeen to twenty-one, and the feature suite at thirty-two. The four that are new are the four kinds of injection, and they are in the suite because the baseline scan cannot find most of them.
The ZAP baseline, signed in, spidered 75 URLs and reported nine header warnings and no failures, the same shape as before and nothing about the injection. That is expected and worth stating plainly: a baseline scan is passive. It reads the requests and responses that normal use produces; it does not send a quote into the search or a script into a note to see what happens. The scanner that would find these is ZAP's active scanner, which attacks, and which you point at a throwaway copy of the application and never at anything you do not own. For a codebase, though, the tests are the better instrument: they are specific, they run in CI in a second, and each one documents exactly which crossing it guards. A scanner tells you that something reflected; a test tells you that the admin search is bound and names the commit that bound it.
What the scanner is good at is the headers, and those are still open: no Content-Security-Policy, no anti-clickjacking header, the version banners. A Content-Security-Policy is also the second fence behind the XSS fix, the thing that refuses an inline script even if one slips into a page, and it is part 5's subject along with the rest of the misconfiguration.
What went wrong
The method was never added. The zip route was registered and the method that backed it was written, but the edit that inserted the method matched a controller signature that did not exist, so it silently did nothing, and the route pointed at a method that was not there. The symptom was a 500, "Call to undefined method", not the command-injection demonstration the test was written for. The lesson for this series is small and sharp: a red test proves a bug only once you have read why it is red, because a test can fail for the reason you intended or for a dozen others.
findOrFail is an access control after all, sometimes. The path-traversal fix looks the attachment up with where('original_name', …)->firstOrFail() scoped to the note, and that scoping is what makes it safe: the same filename on another note is a 404. It is the mirror of part 2's lesson, where findOrFail by a global id was the hole. The difference is the scope: a lookup inside a relationship the user already passed a policy for is safe; a lookup by a raw id is not. The same method, a different question.
Part 4 leaves what users send and turns to who they are: passwords and how they are stored, the reset flow, sessions, brute force and a second factor: Authentication and cryptographic failures: passwords, sessions, resets and a second factor.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
3 / 6- OverviewSecurity beyond the checklist in a Laravel app
- Part 1The app, the threat model, and a test suite written from the other side
- Part 2Broken access control: the id in the URL, the field in the form, the route that forgot
- Part 3Injection and output: SQL in the search, a script in the page, a path and a shell
- Part 4Authentication and cryptographic failures: tokens, passwords and a second factor
- Part 5Security misconfiguration and data integrity: headers, debug mode and a signed link
- Part 6Supply chain, logging and the unexpected: composer audit, what to record, and failing closed