#!/usr/bin/env python3 """Extract Zimbra activity worth investigating from retained application/host logs. Reads plain or gzip-compressed logs and writes JSON Lines. It never connects to Zimbra, changes configuration, or treats an operation name as proof of abuse. """ from __future__ import annotations import argparse import gzip import json from pathlib import Path import re import shlex import sys from urllib.parse import parse_qs, unquote, urlsplit ZIMBRA = re.compile(r"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d,\d+)\s+(\w+)\s+\[([^\]]+)\]\s+\[([^\]]*)\]\s+(\S+)\s+-\s?(.*)$") HTTP = re.compile(r'"(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH) (\S+) HTTP/[0-9.]+"\s+(\d{3})\b') UUID = r"[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}" SUDO = re.compile(r"\bsudo(?:\[\d+\])?:\s+(\S+)\s+:.*?;\s*USER=([^ ;]+)\s*;\s*COMMAND=(.*)$") SOAP = { "GrantRightsRequest": ["CVE-2026-50054"], "GrantPermissionRequest": ["CVE-2026-137843"], "ModifyFilterRulesRequest": ["CVE-2026-50055"], "ModifyOutgoingFilterRulesRequest": ["CVE-2026-50055"], "SaveDraftRequest": ["CVE-2026-73571", "CVE-2026-137846"], "SendMsgRequest": ["CVE-2026-73571"], "TestDataSourceRequest": ["CVE-2026-93632", "CVE-2026-115785"], "ConfigureZimletRequest": ["CVE-2026-93639"], "DeployZimletRequest": ["ZIMBRA-ADMINRCE"], "UndeployZimletRequest": ["ZIMBRA-ADMINRCE"], "CreateAppSpecificPasswordRequest": ["CVE-2026-137844"], "RevokeAppSpecificPasswordRequest": ["CVE-2026-137844"], "GetAppSpecificPasswordsRequest": ["CVE-2026-137844"], "GenerateScratchCodesRequest": ["CVE-2026-137844"], "GetScratchCodesRequest": ["CVE-2026-137844"], "DisableTwoFactorAuthRequest": ["CVE-2026-137844"], "RecoverAccountRequest": ["CVE-2026-137847"], "ResetPasswordRequest": ["CVE-2026-137847"], "SetRecoveryAccountRequest": ["CVE-2026-137847"], "CreateArchiveRequest": ["CVE-2026-137848"], "CreateS3BucketConfigRequest": ["CVE-2026-137849"], "GetS3BucketConfigRequest": ["CVE-2026-137849"], "EditS3BucketConfigRequest": ["CVE-2026-137849"], "DeleteS3BucketConfigRequest": ["CVE-2026-137849"], "ValidateS3BucketReachableRequest": ["CVE-2026-137849"], "FileSharedWithMeRequest": ["CVE-2026-93634", "CVE-2026-115786"], "SearchCalendarResourcesRequest": ["CVE-2026-93636"], "GetSMIMEPublicCertsRequest": ["CVE-2026-93635"], } def context_values(text): return {k: v for field in text.split(";") if "=" in field for k, v in [field.split("=", 1)] if k in ("name", "aname", "mid", "ip", "oip", "port", "soapId")} def url_host(value): try: parsed = urlsplit(value) return parsed.hostname except (TypeError, ValueError): return None def oauth_state_fields(query): # HttpServletRequest.getParameter() selects the first value. Do not copy # the relay, arbitrary type strings, or the optional authentication JWT. state = query.get("state", [""])[0].split(";") datasource_type = state[1] if len(state) > 1 else None if datasource_type not in ("contact", "calendar", "caldav"): datasource_type = None return {"datasource_type": datasource_type, "state_contains_jwt": len(state) > 2 and bool(state[2])} def inspect_http(line): match = HTTP.search(line) if not match: return [] method, target, status = match.groups() try: parsed = urlsplit(target) path = unquote(parsed.path) query = parse_qs(parsed.query, keep_blank_values=True) except ValueError: return [] base = {"method": method, "path": path, "http_status": int(status)} out = [] if re.search(r"/zdocument/[^/]+/docbuilder(?:/|$)", path, re.I): out.append(dict(base, event="onlyoffice_docbuilder", cves=["CVE-2026-93646"])) printfile = re.search(r"(/zdocument/[^/]+/printfile)/([^/]+)(?:/|$)", path, re.I) if printfile: out.append(dict(method=method, route=printfile.group(1), job_id=printfile.group(2), http_status=int(status), event="onlyoffice_printfile", cves=["CVE-2026-93643", "CVE-2026-93644", "CVE-2026-93646"])) if re.search(r"/zdocument/[^/]+/downloadas(?:/|$)", path, re.I): commands = query.get("cmd", []) if not commands: out.append(dict(base, event="onlyoffice_downloadas_unparsed", cves=["CVE-2026-93643", "CVE-2026-93644"])) for raw in commands: try: command = json.loads(raw) except (TypeError, ValueError): out.append(dict(base, event="onlyoffice_downloadas_unparsed", cves=["CVE-2026-93643", "CVE-2026-93644"])) continue if not isinstance(command, dict): continue fmt = command.get("format") if isinstance(fmt, str) and (".." in fmt or "/" in fmt or "\\" in fmt): out.append(dict(base, event="onlyoffice_format_traversal", cves=["CVE-2026-93643"], command=command.get("c"), format=fmt, save_type=command.get("savetype"))) if command.get("c") == "savefromorigin": out.append(dict(base, event="onlyoffice_savefromorigin", cves=["CVE-2026-93644"], destination_host=url_host(command.get("url", "")))) if re.fullmatch(r"/service/extension/oauth2/authenticate/[A-Za-z0-9_-]+", path.rstrip("/"), re.I): out.append(dict(base, event="oauth_account_link_callback", cves=["CVE-2026-93631"], **oauth_state_fields(query))) if re.search(r"/zimlet/[^/]+/[^/]+\.jsp$", path, re.I): out.append(dict(base, event="zimlet_jsp_request", cves=["ZIMBRA-ADMINRCE"])) if path.startswith('/h/') and any(key.startswith('zimbra_target_') or key == 'zimbra_authToken' for key in query): out.append(dict(base, event="rest_request_attribute_override", cves=["CVE-2026-50053", "CVE-2026-10632"], parameter_names=sorted(query))) login_op = query.get("loginOp", [None])[0] remember = query.get("zrememberme", [""])[0] if login_op == "relogin" and re.search(r'[<>"\']', remember): out.append(dict(base, event="login_zrememberme_markup", cves=["CVE-2026-93638"])) return out def inspect_sudo(line): match = SUDO.search(line) if not match or match.group(1) != "zimbra" or match.group(2) != "root": return [] command = match.group(3) try: argv = shlex.split(command) except ValueError: argv = command.split() if not argv: return [] executable = argv[0] args = argv[1:] event = None if executable == "/opt/zimbra/libexec/zmmailboxdmgr" and any(a.startswith(("-XX:OnOutOfMemoryError=", "-Djetty.startServerAsPrivileged=", "-agentlib:", "-agentpath:")) for a in args): event = ("mailbox_launcher_jvm_options", "CVE-2026-50056") elif executable == "/opt/zimbra/common/sbin/postconf" and any(re.match(r"(?:daemon|command)_directory\s*=", a) for a in args): event = ("postfix_program_directory_change", "CVE-2026-50057") elif executable == "/opt/zimbra/common/sbin/postfix" and any(a == "-c" or a.startswith("-c/") for a in args): event = ("postfix_alternate_configuration", "CVE-2026-50057") elif executable == "/opt/zimbra/libexec/zmstat-fd" and re.search(r"[;&|`$<>]", command): event = ("statistics_monitor_shell_metacharacters", "CVE-2026-93645") elif executable == "/opt/zimbra/libexec/zmunbound" and any(a == "-c" or a.startswith("-c/") for a in args): event = ("unbound_selected_configuration", "CVE-2026-93640") return [dict(event=event[0], cves=[event[1]], actor="zimbra", run_as="root", command=command)] if event else [] def records(path, kinds): opener = gzip.open if path.suffix == ".gz" else open pending_ews = {} def finish_ews(thread, complete): entry = pending_ews.pop(thread, None) if entry and len(entry["account_uuids"]) > 1: entry["account_uuids"] = list(dict.fromkeys(entry["account_uuids"])) if len(entry["account_uuids"]) > 1: return dict(entry, event="ews_cross_account_finditem", cves=["CVE-2026-10631"], complete_operation=complete) return None with opener(path, "rt", encoding="utf-8", errors="replace") as source: for number, line in enumerate(source, 1): meta = {"file": str(path), "line": number} if "onlyoffice" in kinds or "web" in kinds: for event in inspect_http(line): family = "onlyoffice" if event["event"].startswith("onlyoffice_") else "web" if family in kinds: yield dict(meta, **event) if "local" in kinds: for event in inspect_sudo(line): yield dict(meta, **event) match = ZIMBRA.match(line.rstrip("\n")) if not match: continue timestamp, level, thread, context, logger, message = match.groups() meta.update(timestamp=timestamp, thread=thread, context=context_values(context)) if "ews" in kinds and logger == "ews": if message == "Start findItem": previous = finish_ews(thread, False) if previous: yield previous pending_ews[thread] = dict(meta, account_uuids=[]) elif thread in pending_ews: account = re.search(r"\bThe account:\s*(" + UUID + r")\b", message) if account: pending_ews[thread]["account_uuids"].append(account.group(1).lower()) pending_ews[thread]["context"].update(meta["context"]) if message == "End findItem": event = finish_ews(thread, True) if event: yield event if "graphql" in kinds and "/service/extension/graphql" in thread: alias = re.search(r"Exception while fetching data \(([^)]+)\) : (.*)", message) if alias and "authentication failed" in alias.group(2).lower(): yield dict(meta, event="graphql_authentication_failure", cves=["CVE-2026-93637"], response_path=alias.group(1)) elif "StackOverflowError" in message: yield dict(meta, event="graphql_stack_overflow", cves=["CVE-2026-137856"]) if "soap" in kinds and logger == "soap": operation = re.match(r"(?:\(batch\) )?([A-Za-z][A-Za-z0-9]*Request)(?: elapsed=|$)", message) if operation and operation.group(1) in SOAP: name = operation.group(1) yield dict(meta, event="soap_operation", cves=SOAP[name], operation=name, batch=message.startswith("(batch) ")) if "calendar" in kinds and logger == "calendar" and ("CalendarItem:" in message or "Unknown calendar item UID" in message): yield dict(meta, event="calendar_processing", cves=["CVE-2026-93627", "CVE-2026-93628", "CVE-2026-93629"], message=message) for thread in list(pending_ews): event = finish_ews(thread, False) if event: yield event def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--kind", action="append", choices=("ews", "graphql", "soap", "onlyoffice", "web", "local", "calendar"), help="select one or more hunts; default: all") parser.add_argument("logs", nargs="+", type=Path, help="plain or .gz log files, in any order") args = parser.parse_args() kinds = set(args.kind or ("ews", "graphql", "soap", "onlyoffice", "web", "local", "calendar")) failed = False for path in args.logs: try: for event in records(path, kinds): print(json.dumps(event, ensure_ascii=True, sort_keys=True)) except (OSError, EOFError) as exc: print(f"{path}: {exc}", file=sys.stderr) failed = True return int(failed) if __name__ == "__main__": raise SystemExit(main())