Taint Flow#

The taint graph#

Psalm builds a directed graph while it analyses the code: a node stands for a value in a place (a variable, an argument, the result of a call), an edge says that the value of one node flows into the next. A source is a node that starts with taints (user input), a sink is a node that must not receive them. Psalm reports the paths from a source to a sink that no escape removes.

<?php // --taint-analysis
function wrap(string $s): string { return $s; }

$x = wrap($_GET['a']);
echo $x;

psalm --taint-analysis --dump-taint-graph=taints.dot writes the graph; these are its edges for the example, in the order of the flow:

"$_GET specialized in src/a.php:64" -> "$_GET['a'] from src/a.php:64-68"
"$_GET['a'] from src/a.php:64-68" -> "string-cast from src/a.php:64-73"
"string-cast from src/a.php:64-73" -> "call to wrap from src/a.php:64-73"
"call to wrap from src/a.php:64-73" -> "wrap#1 specialized in src/a.php:59"
"wrap#1" -> "$s from src/a.php:27-28"
"$s from src/a.php:27-28" -> "wrap"
"wrap specialized in src/a.php:59" -> "$x from src/a.php:54-55"
"$x from src/a.php:54-55" -> "$GLOBALS['x']" -> "call to echo from src/a.php:82-83"
"call to echo from src/a.php:82-83" -> "echo#1 specialized in src/a.php:77"
  • wrap#1 is the node of the first argument of wrap() and wrap the node of its result: the nodes of the function itself. Unless the function is specialized, they are shared by all its calls, so what one caller passes in comes out at every other caller.
  • Specialized nodes (wrap#1 specialized in …) belong to one call only. For a function that is specialized, or that Psalm infers to be pure, the taints go from the arguments of a call to its result without leaving that call, which is why the flow above ends in $x and not in the other callers of wrap().

To add edges that the code doesn't show, use the annotations of the next section, or the methods described in Taint flows from plugins.

Optimized Taint Flow#

When dealing with frameworks, keeping track of the data flow might involve different layers and even other 3rd party components. Using the @psalm-flow annotation allows PsalmPHP to take a shortcut and to make a tainted data flow more explicit.

Proxy hint#

<?php // --taint-analysis
/**
 * @psalm-flow proxy exec($value)
 */
function process(string $value): void {}

process($_GET['malicious'] ?? '');

The example above states, that the function process($value) is a proxy of the native PHP function exec($value) - which is potentially vulnerable to code execution (TaintedShell).

Examples

  • @psalm-flow proxy exec($value) referencing the global/scoped function exec
  • @psalm-flow proxy MyClass::mySinkMethod($value) referencing a function/method of the class MyClass

Return value hint#

<?php // --taint-analysis
/**
 * @psalm-flow ($value, $items) -> return
 */
function inputOutputHandler(string $value, string ...$items): string
{
    // lots of complicated magic
}

echo inputOutputHandler('first', 'second', $_GET['malicious'] ?? '');

The example above states, that the function parameters $value and $items are reflected again in the return value. Thus, in case any of the input parameters to the function inputOutputHandler is tainted, then the resulting return value is as well. In this example TaintedHtml would be detected due to using echo.

Object to return value hint#

<?php // --taint-analysis
interface Message
{
    /**
     * @psalm-taint-specialize
     * @psalm-flow ($this) -> return
     */
    public function getBody(): string;
}

/**
 * @psalm-taint-source input
 */
function fetch(): Message {
    // a request to another server
}

echo fetch()->getBody();

$this in a return value hint states that what a method returns holds what the object it is called on holds: here, the bodies of the messages fetch() returns are tainted, while those of the messages the code builds itself only hold what they were given. This is useful for methods whose bodies Psalm doesn't analyze, such as those of interfaces, stubs and vendor code. With @psalm-taint-specialize, each call returns what its own object holds; without it, what any object the method is called on holds flows into what every call returns.

The methods of the builtin containers and iterators (ArrayObject, ArrayIterator, SplObjectStorage, …) and of Generator return what their object holds without annotations: getArrayCopy() all of it, offsetGet('key') what is stored under 'key', current() an element, key() a key, and Generator::getReturn() what the generator returns. Plugins that follow calls themselves (such as the method calls of a template) get the path along which a method returns what its object holds with Codebase::getReceiverTaintPath(): =, arrayvalue-fetch, arrayvalue-fetch-'key' given the types of the arguments of a call with a literal key, arraykey-fetch or return, or null for a method returning none of it.

Callable result to return value hint#

<?php // --taint-analysis
interface Cache
{
    /**
     * @template T
     * @param callable(): T $compute
     * @return T
     * @psalm-taint-specialize
     * @psalm-flow ($compute()) -> return
     */
    public function get(string $key, callable $compute): mixed;
}

function show(Cache $cache): void
{
    echo $cache->get('key', fn(): string => $_GET['malicious'] ?? '');
}

$compute() in a return value hint states that what the function returns holds what the callables given to $compute return: the closure's body, or the function named. Here TaintedHtml is detected. As for $this, each call returns what its own callables return only with @psalm-taint-specialize.

Arguments to callables#

<?php // --taint-analysis
interface Events
{
    /**
     * @param callable(string): void $listener
     * @psalm-taint-specialize
     * @psalm-flow ($payload) -> $listener()
     */
    public function dispatch(string $payload, callable $listener): void;
}

function listen(Events $events): void
{
    $events->dispatch((string) ($_GET['x'] ?? ''), function (string $payload): void {
        echo $payload; // TaintedHtml
    });
    $events->dispatch('safe', function (string $payload): void {
        echo $payload; // no issue
    });
}

-> $listener() states that the callables given to $listener are called with what is given to $payload, as their arguments.

Keyed stores#

Caches, key-value stores and similar services keep what they are given out of the analyzed code, under a key. Their methods can say so, and what is stored under a key then flows into what the reads of that key return, wherever the code reading it is:

<?php // --taint-analysis
final class Cache
{
    /**
     * @psalm-flow ($value) -> Cache::$data[$key]
     */
    public static function set(string $key, string $value): void {}

    /**
     * @psalm-flow Cache::$data[$key] -> return
     */
    public static function get(string $key): string {}
}

function remember(string $id): void {
    Cache::set('comment_' . $id, $_GET['comment'] ?? '');
}

echo Cache::get('comment_1'); // TaintedHtml
echo Cache::get('title_1');   // no issue
  • ($value, $other) -> Store::$data[$key] stores the arguments given to $value and $other under the key given to $key, and Store::$data[$key] -> return makes a call return what is stored under its key. ($compute()) stores what the callables given to $compute return, as in a return value hint: ($compute()) -> Cache::$data[$key] for a cache computing what it stores when the key is missing.
  • A store is named like a static property, Class::$name. The class and the property need not exist; self names the class declaring the method. The methods of other classes (a wrapper, an extension) share a store by naming the same one.
  • static names the class the method is called on, giving each class its own store, e.g. for the temporary properties of ORM models: ($value) -> static::$temp[$key]. What is stored through a class can be read through it, its subclasses and their parents and interfaces, but not through unrelated classes.
  • [*] is any key: ($values) -> Store::$data[*] for a method storing an array of keys and values, and Store::$data[*] -> return for one returning what is stored under any key. [$keys[*]] is each key of a list, as for mGet(array $keys). In nested stores, like Store::$data[$namespace][$key], only the first key tells the values apart.
  • Keys are told apart by what the analysis knows of them: the exact keys of literal strings and class names, else how the key starts: the start of a concatenation, of an interpolated string, of a sprintf() format up to its first conversion other than %s, of an implode() of a list with a literal separator, __CLASS__, or what the variable (also one a closure uses), the property of $this, the method of the class or the function giving the key starts with. A property set only by its default and its constructor starts like what the constructor is given by the new of the classes analyzed. The keys of a list start like all its items: those of a literal list, those assigned to it ($keys[] = 'lock_' . $id;), and those of a list a method or a function builds this way and returns. A key the analysis knows nothing of can be any key.
  • Psalm's stubs declare the keyed store of phpredis, Redis::$data, and that of APCu, APCu::$data. Plugins can connect their own nodes to a store with Codebase::addTaintStoreWrite() (paths from a node into the store under the names) and Codebase::addTaintStoreRead() (paths from the store to a node), with the names Codebase::getTaintStoreNames() tells for an expression, for stores whose keys an annotation can't express (a table named in an SQL query).

Databases#

A value stored in the database comes back out of it: what a query stores in a column of a table taints what the queries selecting that column read, wherever they are. Psalm reads the SQL of the queries run with PDO, mysqli, pgsql and SQLite3:

  • an INSERT, REPLACE or UPDATE stores in each column the value of its placeholder, or the part of the SQL the analysis doesn't know the text of (a variable concatenated into it);
  • a SELECT reads each column it names into the key of that name of the rows fetched. SELECT * reads each column of the table under its name, and any of them by position, as the order of the columns isn't known.
<?php // --taint-analysis
function store(PDO $pdo): void {
    $statement = $pdo->prepare('INSERT INTO comments (author, body) VALUES (?, ?)');
    $statement->execute(['admin', $_GET['body'] ?? '']);
}

function show(PDO $pdo): void {
    $row = $pdo->query('SELECT author, body FROM comments')->fetch();
    echo (string) $row['body'];   // TaintedHtml
    echo (string) $row['author']; // no issue
    echo (string) $pdo->query('SELECT name FROM users')->fetchColumn(); // no issue

    $row = $pdo->query('SELECT * FROM comments')->fetch();
    echo (string) $row['body'];   // TaintedHtml
    echo (string) $row['author']; // no issue
    echo (string) $row[0];        // TaintedHtml
}

Where the analysis can't tell the table or the column, the query stores in, or reads from, every column it can be:

<?php // --taint-analysis
function store(PDO $pdo): void {
    $pdo->prepare('INSERT INTO comments (author, body) VALUES (?, ?)')->execute(['admin', $_GET['body'] ?? '']);
}

function show(PDO $pdo, string $table): void {
    echo (string) $pdo->query("SELECT name FROM $table")->fetchColumn(); // TaintedHtml
    echo (string) $pdo->query("SELECT * FROM $table")->fetch()['body'];  // TaintedHtml
    echo (string) $pdo->query("SELECT * FROM $table")->fetch()['name'];  // no issue
}
  • A query it can't parse, a table name that isn't a literal and INSERT INTO t VALUES (...) without the column list read or write any column. A table name that isn't a literal can be any table.
  • A column a UNION of SELECT * gives can be any column of their tables.
  • The values given to a prepared statement it can't follow back to the query that prepared it (a statement passed to another function) are stored in every column of every table.

Your own database layer#

Inside a method that runs the queries it is given, Psalm doesn't know their SQL, and what a method stores through code Psalm doesn't analyze is lost. Annotations describe the queries such methods run: Psalm then reads the SQL at each call, and ignores the queries in their bodies:

<?php // --taint-analysis
final class Db
{
    public function __construct(private PDO $pdo) {}

    /**
     * @psalm-database-query $sql $params rows
     */
    public function all(string $sql, array $params = []): array {
        $statement = $this->pdo->prepare($sql);
        $statement->execute($params);
        return $statement->fetchAll();
    }

    /**
     * @psalm-database-insert $table $data
     */
    public function insert(string $table, array $data): void {
        // runs the query with a library Psalm doesn't analyze
    }
}

function run(Db $db): void {
    $db->insert('users', ['name' => 'admin', 'bio' => $_GET['bio'] ?? '']);
    foreach ($db->all('SELECT name, bio FROM users') as $user) {
        echo (string) $user['bio'];  // TaintedHtml
        echo (string) $user['name']; // no issue
    }
}

Properties set and got by name#

ORM models and other property bags often set and get properties by name. These annotations tell Psalm which property a method sets or returns:

<?php // --taint-analysis
/**
 * @property string $title
 * @property string $body
 */
abstract class Model
{
    abstract public function __get(string $name): mixed;

    /** @psalm-flow ($value) -> $this->$name */
    abstract public function set(string $name, string $value): void;

    /** @psalm-flow $this->$name -> return */
    abstract public function get(string $name): string;
}

function save(Model $model): void {
    $model->set('title', $_GET['title'] ?? '');
}

function show(Model $model): void {
    echo $model->title;       // TaintedHtml
    echo $model->get('title'); // TaintedHtml
    echo $model->get('body');  // no issue
}
  • ($value) -> $this->$name sets the property named by $name to $value, like $object->title = $value.
  • $this->$name -> return returns that property, like $object->title.
  • $this->* is any property: ($values) -> $this->* for a method like setProperties(), $this->* -> return for one like toArray().
  • ($values) -> $this->{key} sets each property to what is under its name in the array $values, and $this->{key} -> return[key] returns an array holding each property under its name. Unlike $this->*, they keep the properties apart:

```php /* @psalm-flow ($values) -> $this->{key} / abstract public function setProperties(array $values): void;

/* @psalm-flow $this->{key} -> return[key] / abstract public function toArray(): array; ```

After $model->setProperties(['title' => $_GET['title'], 'body' => 'text']), only $model->title and $model->toArray()['title'] are tainted. What is under a key the analysis doesn't know (an array whose keys aren't literals, or a key read with a variable) may be any property, and a key that names no property of the class is still returned under that key. + When $name isn't a literal string, the call sets or returns every property it may name. A copy loop, foreach ($values as $name => $value) { $model->set($name, $value); }, sets each property to what is under its name in $values, as ($values) -> $this->{key} does, when $name and $value are still the key and the value of the loop. + For a class with @psalm-taint-specialize, properties are tracked per object.

Properties held in an array property#

Models often hold their properties in an array property under their names, and their methods read and write them there. @psalm-taint-property-bag on the class names that array property: in the methods of the class and of the classes extending it, an element of it under a literal key is the property of that name.

<?php // --taint-analysis
/** @psalm-taint-property-bag $properties */
abstract class Model
{
    /** @var array<string, mixed> */
    protected array $properties = [];

    public function __get(string $name): mixed {
        return $this->properties[$name] ?? null;
    }
}

/**
 * @property string $title
 * @property string $body
 */
final class Article extends Model
{
    public function setTitle(string $title): void {
        $this->properties['title'] = $title;
    }

    public function getBody(): string {
        return (string) $this->properties['body'];
    }
}

function save(Article $article): void {
    $article->setTitle($_GET['title'] ?? '');
}

function show(Article $article): void {
    echo $article->title;     // TaintedHtml
    echo $article->getBody(); // no issue
}
  • $this->properties['title'] reads $this->title, and $this->properties['title'] = $value sets it, also under further keys ($this->properties['tags']['main'] = $tag). They meet $object->title, @property tags and the flows of properties set and got by name.
  • An element under a key that isn't a literal, and the whole array, are only the array property: declare the flows of the methods setting and getting properties by name with @psalm-flow.

A property and its elements#

A method can also say which property it sets or returns by naming it, and which element of an array property by the parameter giving its key, for request objects and other containers holding their values in an array property:

<?php // --taint-analysis
abstract class Request
{
    /** @var array<string, string> */
    protected array $vars = [];

    /** @psalm-flow ($vars) -> $this->vars */
    abstract public function __construct(array $vars);

    /** @psalm-flow ($value) -> $this->vars[$name] */
    abstract public function set(string $name, string $value): void;

    /** @psalm-flow $this->vars[$name] -> return */
    abstract public function get(string $name): string;

    /** @psalm-flow $this->vars -> return */
    abstract public function toArray(): array;
}

function save(Request $request): void {
    $request->set('title', $_GET['title'] ?? '');
}

function show(Request $request): void {
    echo $request->get('title');            // TaintedHtml
    echo $request->get('body');             // no issue
    echo $request->toArray()['title'];      // TaintedHtml
}
  • ($value) -> $this->vars sets the property vars, like $object->vars = $value, and $this->vars -> return returns it. The arrays set keep their keys.
  • ($value) -> $this->vars[$name] sets the element of vars under the key given to $name, like $object->vars[$name] = $value, and $this->vars[$name] -> return returns it. Keys are told apart as for keyed stores.
  • $this->vars[*] is any element: ($value) -> $this->vars[*] for a method like add(), $this->vars[*] -> return for one returning any of them.
  • The flows into the properties of a constructor set them on the object it constructs: new Request(['title' => $_GET['title']]) taints get('title') of the requests. They also apply to ($values) -> $this->$name, ($values) -> $this->* and ($values) -> $this->{key}.

Combined proxy & return value hint#

<?php // --taint-analysis
/**
 * @psalm-flow proxy exec($value)
 * @psalm-flow ($value, $items) -> return
 */
function handleInput(string $value, string ...$items): string
{
    // lots of complicated magic
}

echo handleInput($_GET['malicious'] ?? '');

The example above combines both previous examples and shows, that the @psalm-flow annotation can be used multiple times. Here, it would lead to detecting both TaintedHtml and TaintedShell.

Taint flows from plugins#

Plugins can add flows that annotations can't express with these Codebase methods ($source is the event's getStatementsSource()):

  • getTaintNode($source, $label, $location, $value_type = null): a node for a value at a location. The taints of $value_type flow into it. To make an expression carry what reaches the node, use $type->addParentNodes([$node]).
  • getTaintPropertyNode('Class::$name'): the node holding a property's value. The property doesn't need to be declared.
  • addTaintSink($taint_id, $location, $taints): adds a sink and returns it.
  • addTaintPath($source, $from, $to, $path_type = '=', $added_taints = 0, $removed_taints = 0): connects two nodes.
  • addTaintPropertyAssignment($source, $value, 'Class::$name'): assigns the node $value to an instance property of an object of the class, as $object->name = does: what the parent classes sharing the property and the subclasses read of it gets the value too.
  • getTaintReturnNode($source, $function, $call_location = null), getTaintArgumentNode($source, $function, $offset, $call_location = null) and getTaintReceiverNode($source, 'Class::method', $call_location): the nodes of what a function ('ns\f'), a method ('Class::method') or a closure (its Closure/ArrowFunction node) returns, of its parameter at $offset and of the object it runs on, for a call the code doesn't show (e.g. a framework's). Given the location of the call, these are the nodes of that call if Psalm tells its calls apart (see @psalm-taint-specialize); the receiver node only exists then (null otherwise).
  • addTaintValidation($source, $call, $value, $removed_taints, $kind): records that the call $call validates $value (a local variable, or one cast to a string) against a pattern removing $removed_taints (getTaintsRemovedByPattern($pattern)). Where a condition on its result tells the validation passed, the variable can't carry those taints, as long as it holds the same value: $validator->fails() and passes() for a result of kind validator, count($violations) > 0, $violations->count() === 0, ... for one of kind violations. Call it from afterExpressionAnalysis().
  • tracksTaintFlow($source): false when taints aren't tracked there, e.g. when TaintedInput is suppressed. The methods above then add nothing.

See examples/plugins/TaintModelFields.php, which tracks ORM model fields from set() to get(), and examples/plugins/TaintPageComponents.php, which outputs what the components of a page render, as a framework would.