PHP Security Practices, Checked: Inside mir's Taint Analysis
This code has an XSS bug:
<?php
function label(string $s): string
{
return ucfirst(trim($s));
}
$q = $_GET['q'] ?? '';
$title = label($q);
echo "<h1>Results for $title</h1>";
trim() and ucfirst() change the value, but they don’t escape it. In a real project label() sits in another file, and the bug is easy to miss in review. Taint analysis follows request data until it reaches a function like echo. mir, a PHP static analyzer written in Rust, reports this one and prints the path, source first:
src/search.php:10:0 error[MIR0801] TaintedHtml: Tainted HTML output — possible XSS
= taint flow: $_GET['q'] (line 8) → $q (line 8) → label($q) (line 9) → $title (line 9)
Psalm has taint analysis too, but as a separate mode, psalm --taint-analysis, which doesn’t report type issues, so you have to run it as a second job. In mir it’s part of the normal run: the same vendor/bin/mir src/ that checks types also reports Tainted* issues. --no-taint turns it off.
All output below is from mir’s main branch, which becomes the next release.
Sources, sinks and escapes
Sources are where untrusted data enters: $_GET, $_POST, $_COOKIE, $_REQUEST, $_FILES names and types, client-controlled $_SERVER entries such as HTTP_*, php://input, getallheaders(), and the request objects of Symfony, Laravel and PSR-7.
Sinks are where data is interpreted: echo, $pdo->query(), system(), file_put_contents(), header(), unserialize(), curl_setopt() and dozens more.
Escapes make a value safe for some sinks: htmlspecialchars(), escapeshellarg(), basename(), urlencode().
Between a source and a sink, mir follows the value through assignments, string building, arrays and their keys, object properties, closures, generators, and calls to your own functions.
How a sink decides
When a value reaches a call, mir asks four questions. A report needs a yes to every one of them.
Taint is a set of kinds
Every value carries the set of sink kinds it’s still dangerous for: html, sql, shell, file, header, cookie, unserialize, ssrf, ldap, xpath, callable, llm_prompt, plus eval and a catch-all for custom kinds. Data from a source starts with every kind. An escape removes only the kinds it neutralizes. A sink reports when the value still has the sink’s own kind.
<?php
$db = new PDO('sqlite::memory:');
$name = htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
echo "<p>Hello, $name</p>";
$db->query("SELECT * FROM users WHERE name = '$name'");
The echo is fine. The query is reported, because HTML escaping is not SQL escaping. ENT_QUOTES happens to encode ' here, but a trailing backslash still escapes the closing quote in MySQL’s default mode. A numeric comparison needs no quote at all. And the database stores ' instead of the name:
src/kinds.php:7:0 error[MIR0802] TaintedSql: Tainted SQL query — possible SQL injection
= taint flow: $_GET['name'] (line 4) → htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8') (line 4) → $name (line 4)
mir knows the escapes of PHP and common libraries. htmlspecialchars(), htmlentities() and strip_tags() clear html. escapeshellarg() clears shell. basename() clears file. filter_var() with FILTER_VALIDATE_INT clears everything. It also accepts addslashes() and mysqli_real_escape_string() for sql, but bound parameters are the better fix, as the practices below explain.
Only the dangerous argument counts
mir checks sink parameters, not whole functions. file_put_contents() is dangerous when the client picks the file name. Request data written into a log file is fine.
<?php
file_put_contents('/var/log/app/search.log', $_GET['q'], FILE_APPEND);
file_put_contents('/var/log/app/' . $_GET['q'], 'hit');
copy('/tmp/upload.bin', $_POST['to']);
mail('admin@example.com', 'Contact', $_POST['message'], 'From: ' . $_POST['email']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_GET['url']);
curl_setopt($ch, CURLOPT_USERAGENT, $_GET['ua']);
$a = unserialize($_COOKIE['c']);
$b = unserialize($_COOKIE['c'], ['allowed_classes' => false]);
src/args.php:4:0 error[MIR0800] TaintedInput: Tainted input reaching sink 'file'
= taint flow: $_GET['q'] (line 4)
src/args.php:6:0 error[MIR0800] TaintedInput: Tainted input reaching sink 'file'
= taint flow: $_POST['to'] (line 6)
src/args.php:8:0 error[MIR0805] TaintedHeader: Tainted HTTP header — possible header injection or open redirect
= taint flow: $_POST['email'] (line 8)
src/args.php:11:0 error[MIR0807] TaintedSsrf: Tainted URL — possible server-side request forgery
= taint flow: $_GET['url'] (line 11)
src/args.php:14:5 error[MIR0800] TaintedInput: Tainted input reaching sink 'unserialize'
= taint flow: $_COOKIE['c'] (line 14)
mir reports 5 of the 7 calls with request data. The log line on line 3, the message body on line 8 and the user agent on line 12 are not reported. Neither is unserialize() with allowed_classes set to false, which can’t create objects. curl_setopt() is a sink only for CURLOPT_URL and CURLOPT_PROXY, so the option argument decides whether the value argument is checked.
Types can make a value safe
The third check uses mir’s type inference. A value whose type is int, float, bool, a numeric string or a literal string can’t carry an injection payload, whatever its taint says. Validation narrows the type, so it also clears the taint:
<?php
function page(): int
{
return (int) ($_GET['page'] ?? 1);
}
$db = new PDO('sqlite::memory:');
$id = $_GET['id'];
if (ctype_digit($id)) {
$db->query("SELECT * FROM posts WHERE id = $id");
}
$dir = $_GET['dir'];
if (in_array($dir, ['asc', 'desc'], true)) {
$db->query("SELECT * FROM posts ORDER BY created_at $dir");
}
$limit = page() * 20;
$db->query("SELECT * FROM posts LIMIT $limit");
$db->query("SELECT * FROM posts WHERE slug = '" . $_GET['slug'] . "'");
src/types.php:23:0 error[MIR0802] TaintedSql: Tainted SQL query — possible SQL injection
= taint flow: $_GET['slug'] (line 23)
Inside the ctype_digit() branch, $id is a numeric string. After the strict in_array(), $dir is 'asc'|'desc'. page() returns an int, and arithmetic always yields a number. Only the last query keeps raw request data. A loose in_array() without true doesn’t narrow and is still reported, because loose comparison treats numeric strings as numbers: '1e1' == '10' is true.
Sinks inside your own functions
In real code a sink usually sits behind a helper, e.g. a repository method or a view function. mir doesn’t need annotations for these. It analyzes each function body once and records a summary: which parameters flow to the return value, and which reach a sink inside.
<?php
function render(string $title, string $body): string
{
return '<h1>' . htmlspecialchars($title) . '</h1>' . $body;
}
function search(PDO $db, string $term, int $limit): array
{
return $db->query("SELECT * FROM posts WHERE title LIKE '%$term%' LIMIT $limit")->fetchAll();
}
echo render($_GET['title'], '<p>Static body</p>');
echo render('Static title', $_GET['body']);
$db = new PDO('sqlite::memory:');
search($db, $_GET['term'], 10);
src/summary.php:14:0 error[MIR0801] TaintedHtml: Tainted HTML output — possible XSS
= taint flow: $_GET['body'] (line 14) → render('Static title', $_GET['body']) (line 14)
src/summary.php:17:0 error[MIR0802] TaintedSql: Tainted SQL query — possible SQL injection
= taint flow: $_GET['term'] (line 17)
render() escapes $title and returns $body as it is, so only the second call is reported. search() is reported at the call, not inside the function: a function that builds SQL from a parameter becomes a bug only when someone calls it with untrusted input. $limit is an int, so it never matters.
For this, one set of kinds per value isn’t enough. mir stores taint in 128 bits: nine slots of 14 kinds. The first slot is taint from real sources, the one that triggers reports. While a body is analyzed, each of the first eight parameters gets its own slot, called a label. If htmlspecialchars($title) clears html in the slot of $title, the summary remembers that $title is safe for HTML, and that $body isn’t.
Summaries cover more than return values: a constructor that stores a parameter in a property, a setter, a by-reference parameter the function writes into, values a generator yields.
Declaring your own
Functions without a body, such as interface methods or SDK calls mir can’t see into, need annotations. They follow Psalm’s, and each also accepts the @psalm- prefix, so existing @psalm-taint-* annotations keep working:
| Annotation | Meaning |
|---|---|
@taint-source | The return value is user-controlled |
@taint-sink <kind> $param | Tainted data passed to $param is reported |
@taint-escape <kind> | The return value is safe for <kind> sinks |
@taint-unescape <kind> | The return value is dangerous again for <kind>, for example after html_entity_decode() |
@psalm-flow ($a) -> return | Taint flows from $a to the return value |
Use @taint-source for data that isn’t from the request but is still attacker-controlled: messages from a queue, rows imported from a partner’s CSV, a webhook payload.
Five practices, and what checks them
1. Treat all request data as untrusted
Every part of the request is controlled by the client: headers, cookies, the uploaded file name, the Host header. Validation in the browser doesn’t count; anyone can send a request with curl. Figure 1 is the common mistake: trusting a value because a helper touched it. Normalizing a value with trim() or strtolower() doesn’t make it safe.
2. Escape output for its context
For HTML, escape at the moment of output, with the flags that cover quotes and broken UTF-8:
echo htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
Since PHP 8.1 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 is the default, but set them explicitly if you still support PHP 8.0 or older. In templates, use the escaping your engine does by default: Twig and Blade’s {{ }} both escape. Their raw output, |raw and {!! !!}, is where XSS comes back.
HTML escaping is right only for HTML text and quoted attributes. A value inside a <script> block, a style attribute or an href needs a different encoding, and htmlspecialchars() doesn’t stop javascript:alert(1) in a link. If your project has its own helper, tell mir what it escapes:
/**
* @taint-escape html
*/
function e(string $s): string
{
return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
3. Bind values, allowlist identifiers
Escaping functions for SQL are easy to get wrong: a missing quote around the value, a different connection charset, a number that isn’t quoted. Bound parameters remove the problem, because the value never becomes part of the SQL text:
$stmt = $db->prepare('SELECT * FROM posts WHERE title LIKE ? LIMIT ?');
$stmt->bindValue(1, '%' . $term . '%');
$stmt->bindValue(2, $limit, PDO::PARAM_INT);
$stmt->execute();
Column names, table names and sort directions can’t be bound. Check them against a fixed list with a strict comparison, match or a strict in_array(), as in the type example above. Cast numbers with (int).
4. Keep request data out of paths, commands, headers and unserialize()
<?php
$name = $_GET['file'];
readfile('/var/www/uploads/' . $name);
readfile('/var/www/uploads/' . basename($name));
system('convert ' . $_POST['image'] . ' out.png');
system('convert ' . escapeshellarg($_POST['image']) . ' out.png');
header('Location: ' . $_GET['next']);
$prefs = unserialize($_COOKIE['prefs']);
$prefs = json_decode($_COOKIE['prefs'], true);
$avatar = file_get_contents($_POST['avatar_url']);
src/files.php:4:0 error[MIR0800] TaintedInput: Tainted input reaching sink 'file'
= taint flow: $_GET['file'] (line 3) → $name (line 3)
src/files.php:7:0 error[MIR0803] TaintedShell: Tainted shell command — possible command injection
= taint flow: $_POST['image'] (line 7)
src/files.php:10:0 error[MIR0805] TaintedHeader: Tainted HTTP header — possible header injection or open redirect
= taint flow: $_GET['next'] (line 10)
src/files.php:12:9 error[MIR0800] TaintedInput: Tainted input reaching sink 'unserialize'
= taint flow: $_COOKIE['prefs'] (line 12)
src/files.php:15:10 error[MIR0800] TaintedInput: Tainted input reaching sink 'file'
= taint flow: $_POST['avatar_url'] (line 15)
Every unsafe line is reported, and none of the safe variants. How to fix each one:
- File paths: the client can send
../../etc/passwdas the name. Usebasename()when the value should be a plain name, or resolve it withrealpath()and check that it starts with the base directory plus a trailing/. Better, store uploads under a generated name. - Shell commands: Avoid the shell when a PHP function or library does the job. Otherwise
escapeshellarg()every argument, or pass the command toproc_open()as an array, which since PHP 7.4 runs the program without a shell. - Headers: PHP blocks line breaks in
header(), but a taintedLocationis still an open redirect. Redirect only to relative paths or hosts on an allowlist. - Deserialization:
unserialize()on client data can construct any class the autoloader knows and run its magic methods. Usejson_decode(), or at least['allowed_classes' => false]. - Outgoing requests: A URL from the request lets the client make your server fetch
http://169.254.169.254/or an internal admin panel. Fix the scheme and host in code andurlencode()what you append. mir doesn’t report a URL that starts with a literalhttps://host/.
5. Treat LLM prompts as a sink
More PHP applications send user text to a language model. Prompt injection is the SQL injection of that code: the user’s text can override your instructions, leak the system prompt or trigger tool calls. No escaping function fixes it, but the data flow is the same, so mark the method that sends the prompt:
<?php
interface LanguageModel
{
/**
* @taint-sink llm_prompt $prompt
*/
public function complete(string $prompt): string;
}
function summarize(LanguageModel $llm): string
{
return $llm->complete('Summarize this review: ' . $_POST['review']);
}
src/llm.php:13:11 error[MIR0804] TaintedLlmPrompt: Tainted LLM prompt — possible prompt injection
= taint flow: $_POST['review'] (line 13)
The annotation on the interface covers every implementation. There is no escape for this kind, so the fix is in how you call the model. Keep user content apart from instructions in the API call. Don’t give the model tools it doesn’t need. Treat its answer as untrusted output too. Once you’ve reviewed a call, suppress it with @psalm-suppress TaintedLlmPrompt and a comment saying why.
On a real framework
I ran mir on Laravel framework v13.36.0. Two reports lead to the same function:
src/Illuminate/Foundation/Http/Middleware/PreventRequestForgery.php:189:51 error[MIR0800] TaintedInput: Tainted input reaching sink 'unserialize'
= taint flow: $request->header('X-XSRF-TOKEN') (line 187) → $header (line 187)
src/Illuminate/Cookie/Middleware/EncryptCookies.php:91:25 error[MIR0800] TaintedInput: Tainted input reaching sink 'unserialize'
= taint flow: $request->cookies (line 85) → $cookie (line 85)
The X-XSRF-TOKEN header and the cookies go to Encrypter::decrypt(), which calls unserialize() when its second argument is true. Here it is static::$serialize: false by default, but a mutable static property, so mir can’t prove it stays off. The payload is also encrypted and authenticated with APP_KEY.
This is the path behind CVE-2018-15133. Before Laravel 5.6.30, cookies were serialized by default, and anyone who knew the APP_KEY could send a payload in X-XSRF-TOKEN and get remote code execution. The flow mir reports is real. Today only a default and a secret keep it safe. Have that in mind before you set $serialize = true or commit an .env file.
Try it
Paste any of the examples into the playground, or run it on your project:
composer require --dev miropen/mir-php
vendor/bin/mir src/
The taint annotations and every security issue are documented at jorgsowa.github.io/mir. If mir misses a flow or reports a safe one, open an issue with a short code sample.
I audit codebases in any language, covering security, architecture, supply chain and code quality. You get a clear report with a fix for every finding, and I help you ship the fixes and add guardrails that keep problems out. Get in touch.