#!/usr/bin/python3 """mac-telemetry es-filter 0.2.0 Reads eslogger JSON lines and writes a slim, secret-scrubbed event stream for the Splunk universal forwarder. Modes: --follow RAW OUT [--max-raw-mb N] [--heartbeat-s N] [--state FILE] daemon: tail RAW (eslogger output), append to OUT; with --state, resume where the last run stopped --seed-state RAW FILE write a state that starts at the end of RAW, unless FILE exists (install.sh, migration from 0.1.0) --stdin filter stdin to stdout (tests, ad hoc) --stats FILE SECONDS calibration: in vs out volume, extrapolated per day --who-runs PATH FILE diagnostics: which images exec PATH, by image What is dropped, by design: - exec of Apple platform binaries, except INTEREST (living-off-the-land tools) - env and fds of every exec (env carries tokens; fds are bulk) - audit tokens, replaced by pid, pidversion and euid What is kept: every non-exec event subscribed (BTM, sudo, auth, XProtect, ...), and every exec of a binary that is not an Apple platform binary. Added in 0.2.0 (schema mac-es/1, additive): - attribution at the edge: proc.parent_path and proc.responsible_path, from a cache of pid -> image fed by every raw event (dropped execs included), with a live proc_pidpath() lookup as the fallback; *_src says which ("cache", "live", "self" when the process is its own responsible process, or "none"). A cached path can be wrong after pid reuse; pidversion is kept so that a reader can check. - type filter_heartbeat every --heartbeat-s seconds (default 60) with the counters of that interval: raw lines in, lines out, execs dropped, parse errors, gaps and resets in eslogger's global_seq_num, raw reclaims, the age of the newest event. Silence of the sensor and lost events become searchable. - tcc_modify enums as names next to the numbers (values from the macOS 15.5 SDK's ESTypes.h, read on the Mac on 2026-10-20). - --state FILE: the read position in RAW (inode, offset) and the last global_seq_num, written atomically about every 2 s and on SIGTERM, after OUT is synced. Up to 0.1.0 every start read RAW from offset 0, so each restart of the filter wrote everything still in RAW (up to --max-raw-mb) to OUT a second time. Now a stop and start reads each event once; after a SIGKILL or a crash the events of the last save interval (about 2.5 s) are written again; a power loss repeats, it does not lose. A state that cannot be written is counted (state_errors) and the filter keeps going. A filter_start event records how each run began (resume = state, none, bad_state, other_file or past_end); the last heartbeat is written on stop. Argument redaction is best effort: known flag names, header values, URL userinfo, query secrets and well-known token shapes. It is not a guarantee. """ import collections import datetime import json import os import re import signal import sys import time SCHEMA = "mac-es/1" VERSION = "0.2.0" INTEREST = frozenset({ "osascript", "curl", "security", "ditto", "zip", "unzip", "launchctl", "python3", "sh", "bash", "zsh", "base64", "xattr", "codesign", "spctl", "pkgutil", "installer", "nscurl", "openssl", "scp", "ssh", "sftp", "nc", "dscl", "sqlite3", "screencapture", "osacompile", "plutil", "defaults", "sudo", "su", "chmod", "kextload", "systemextensionsctl", "profiles", "tccutil", "csrutil", "hdiutil", "mkfifo", "perl", "ruby", "swift", "tclsh", "launchd", "crontab", "at", }) SECRET_FLAG = re.compile( r"^--?(?:password|passwd|pass|pwd|token|secret|api[-_]?key|apikey|access[-_]?key|" r"client[-_]?secret|auth|auth[-_]?token|bearer|private[-_]?key)$", re.I) SECRET_FLAG_EQ = re.compile( r"^(--?(?:password|passwd|pass|pwd|token|secret|api[-_]?key|apikey|access[-_]?key|" r"client[-_]?secret|auth|auth[-_]?token|bearer|private[-_]?key)=).+$", re.I) SUBS = [ (re.compile(r"(?i)^((?:authorization|proxy-authorization|x-api-key|cookie|x-auth-token)\s*:\s*).+$"), r"\1"), (re.compile(r"([a-zA-Z][a-zA-Z0-9+.-]*://)[^/\s:@]+:[^/\s@]+@"), r"\1@"), (re.compile(r"(?i)([?&](?:token|key|apikey|api_key|access_token|sig|signature|password|secret)=)[^&\s]+"), r"\1"), (re.compile(r"ghp_[A-Za-z0-9]{36}|github_pat_\w{20,}"), ""), (re.compile(r"xox[abprs]-[\w-]{10,}"), ""), (re.compile(r"sk-[A-Za-z0-9_-]{20,}"), ""), (re.compile(r"AKIA[0-9A-Z]{16}"), ""), (re.compile(r"eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}"), ""), ] MAX_ARG, MAX_ARGS = 512, 48 DROP_KEYS = frozenset({"env", "fds", "audit_token", "parent_audit_token", "responsible_audit_token"}) CACHE_MAX = 8192 STATE_VERSION = 1 STATE_EVERY_S = 2.0 # ESTypes.h, MacOSX15.5.sdk (read on the Mac, 2026-10-20) TCC_RIGHT = ["denied", "unknown", "allowed", "limited", "add_modify_added", "session_pid", "learn_more"] TCC_REASON = ["none", "error", "user_consent", "user_set", "system_set", "service_policy", "mdm_policy", "service_override_policy", "missing_usage_string", "prompt_timeout", "preflight_unknown", "entitled", "app_type_policy", "prompt_cancel"] TCC_UPDATE = ["unknown", "create", "modify", "delete"] def norm_time(t): """eslogger nanosecond ISO time -> microseconds, always 6 digits, Z.""" if not isinstance(t, str) or "T" not in t: return t t = t.rstrip("Z") if "." in t: head, frac = t.split(".", 1) frac = (frac + "000000")[:6] else: head, frac = t, "000000" return f"{head}.{frac}Z" def utc_now(): return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") def live_pidpath_factory(): """proc_pidpath() through libproc on macOS; None elsewhere (tests, Linux).""" if sys.platform != "darwin": return None try: import ctypes lib = ctypes.CDLL("/usr/lib/libproc.dylib") buf = ctypes.create_string_buffer(4096) def lookup(pid): if not isinstance(pid, int) or pid <= 0: return None n = lib.proc_pidpath(pid, buf, 4096) return buf.value.decode("utf-8", "replace") if n > 0 else None return lookup except OSError: return None def name_of(table, value): return table[value] if isinstance(value, int) and 0 <= value < len(table) else None class Counters: """Per-interval counters; the heartbeat emits and resets them.""" FIELDS = ("lines_in", "lines_out", "dropped_exec", "parse_errors", "seq_gaps", "seq_resets", "reclaims", "live_lookups", "state_errors") def __init__(self): self.reset() def reset(self): for f in self.FIELDS: setattr(self, f, 0) def snapshot(self): return {f: getattr(self, f) for f in self.FIELDS} class EsFilter: def __init__(self, live_lookup=None): self.cache = collections.OrderedDict() # pid -> image path, most recent last self.live = live_lookup self.c = Counters() self.last_seq = None self.last_event_time = None # --- attribution ------------------------------------------------------- def remember(self, pid, path): if isinstance(pid, int) and path: self.cache[pid] = path self.cache.move_to_end(pid) if len(self.cache) > CACHE_MAX: self.cache.popitem(last=False) def resolve(self, pid): if not isinstance(pid, int): return None, "none" if pid in self.cache: return self.cache[pid], "cache" if self.live is not None: self.c.live_lookups += 1 path = self.live(pid) if path: return path, "live" return None, "none" def learn(self, ev, body, et): p = ev.get("process") or {} self.remember((p.get("audit_token") or {}).get("pid"), (p.get("executable") or {}).get("path")) if et == "exec": tgt = (body.get(et) or {}).get("target") or {} self.remember((tgt.get("audit_token") or {}).get("pid"), (tgt.get("executable") or {}).get("path")) def proc_slim(self, p, attribute=False): if not isinstance(p, dict): return None at = p.get("audit_token") or {} rat = p.get("responsible_audit_token") or {} out = { "pid": at.get("pid"), "pidversion": at.get("pidversion"), "euid": at.get("euid"), "ppid": p.get("ppid"), "original_ppid": p.get("original_ppid"), "responsible_pid": rat.get("pid"), "session_id": p.get("session_id"), "path": (p.get("executable") or {}).get("path"), "signing_id": p.get("signing_id"), "team_id": p.get("team_id") or None, "platform": bool(p.get("is_platform_binary")), "cdhash": p.get("cdhash"), "start_time": norm_time(p.get("start_time")), } if attribute: out["parent_path"], out["parent_src"] = self.resolve(p.get("ppid")) if out["responsible_pid"] == out["pid"]: out["responsible_path"], out["responsible_src"] = out["path"], "self" else: out["responsible_path"], out["responsible_src"] = self.resolve(out["responsible_pid"]) return out def scrub(self, obj): if isinstance(obj, dict): if "executable" in obj and "audit_token" in obj: return self.proc_slim(obj, attribute=True) return {k: self.scrub(v) for k, v in obj.items() if k not in DROP_KEYS} if isinstance(obj, list): return [self.scrub(v) for v in obj] return obj # --- sequence --------------------------------------------------------- def track_seq(self, g): if not isinstance(g, int): return if isinstance(self.last_seq, int): if g > self.last_seq + 1: self.c.seq_gaps += g - self.last_seq - 1 elif g <= self.last_seq: self.c.seq_resets += 1 # eslogger restarted (or its client did) self.last_seq = g # --- one event -------------------------------------------------------- def transform(self, ev): body = ev.get("event") or {} et = next(iter(body), None) if et is None: return None self.track_seq(ev.get("global_seq_num")) self.last_event_time = norm_time(ev.get("time")) # attribution of this event first, so an exec's own target does not # answer for its parent; then learn what the event says about pids proc = self.proc_slim(ev.get("process"), attribute=True) out = {"schema": SCHEMA, "time": norm_time(ev.get("time")), "type": et, "seq": ev.get("global_seq_num"), "proc": proc} self.learn(ev, body, et) if et == "exec": ex = body[et] or {} tgt = ex.get("target") or {} path = (tgt.get("executable") or {}).get("path") or "" base = path.rsplit("/", 1)[-1] if tgt.get("is_platform_binary") and base not in INTEREST: self.c.dropped_exec += 1 return None out["target"] = self.proc_slim(tgt) out["args"], out["redacted"] = redact_args(ex.get("args")) out["cwd"] = (ex.get("cwd") or {}).get("path") out["script"] = (ex.get("script") or {}).get("path") if isinstance(ex.get("script"), dict) else None else: detail = self.scrub(body[et]) if et == "tcc_modify" and isinstance(detail, dict): for key, table in (("right", TCC_RIGHT), ("reason", TCC_REASON), ("update_type", TCC_UPDATE)): if key in detail: detail[key + "_name"] = name_of(table, detail[key]) out["detail"] = detail return out def filter_line(self, raw): raw = raw.strip(b"\x00 \r\n") if not raw: return None self.c.lines_in += 1 try: ev = json.loads(raw) if not isinstance(ev, dict): raise ValueError("not a JSON object") o = self.transform(ev) except Exception as e: # one line must never stop the sensor (KeepAlive would replay it forever) self.c.parse_errors += 1 self.c.lines_out += 1 return json.dumps({"schema": SCHEMA, "type": "filter_parse_error", "time": utc_now(), "bytes": len(raw), "error": type(e).__name__}, separators=(",", ":")) if o is None: return None self.c.lines_out += 1 return json.dumps(o, separators=(",", ":")) def heartbeat(self, interval_s, raw_bytes=None): hb = {"schema": SCHEMA, "time": utc_now(), "type": "filter_heartbeat", "version": VERSION, "interval_s": interval_s, "pid": os.getpid(), "cache_size": len(self.cache), "last_event_time": self.last_event_time, "raw_bytes": raw_bytes} hb.update(self.c.snapshot()) self.c.reset() return json.dumps(hb, separators=(",", ":")) def redact_args(args): out, n, hide_next = [], 0, False for a in (args or [])[:MAX_ARGS]: a = str(a) if hide_next: out.append("") n += 1 hide_next = False continue if SECRET_FLAG.match(a): out.append(a) hide_next = True continue m = SECRET_FLAG_EQ.match(a) if m: out.append(m.group(1) + "") n += 1 continue for rx, rep in SUBS: a, k = rx.subn(rep, a) n += k if len(a) > MAX_ARG: a = a[:MAX_ARG] + f"...(+{len(a) - MAX_ARG})" out.append(a) extra = len(args or []) - MAX_ARGS if extra > 0: out.append(f"...(+{extra} args)") return out, n _DEFAULT = None def filter_line(raw): """Module-level entry kept from 0.1.0 (tests, --stdin): one shared filter, no live lookup.""" global _DEFAULT if _DEFAULT is None: _DEFAULT = EsFilter() return _DEFAULT.filter_line(raw) def run_stdin(): f = EsFilter() for raw in sys.stdin.buffer: o = f.filter_line(raw) if o is not None: sys.stdout.write(o + "\n") sys.stdout.flush() def open_out(path): f = open(path, "ab", buffering=0) return f, os.fstat(f.fileno()).st_ino def read_state(path): """(state, why): why is "none" without a file and "bad_state" for a file that cannot be used.""" if not path or not os.path.exists(path): return None, "none" try: with open(path) as f: st = json.load(f) except (OSError, ValueError): return None, "bad_state" if isinstance(st, dict) and st.get("v") == STATE_VERSION: return st, "ok" return None, "bad_state" def write_state(path, st): """Atomic: a reader (the next start) sees the old state or the new one, never half.""" tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(st, f, separators=(",", ":")) f.flush() os.fsync(f.fileno()) os.replace(tmp, path) def resume_offset(state, why, st_raw): """Where to start reading RAW: the saved offset when the state names this very file. Without a usable state the run starts at 0 and says why (filter_start.resume): a duplicate can be found later by seq and time, a skipped event cannot. The inode alone names the file; the device number is kept in the state for the record but not compared, because a volume's number may change across reboots [inference]. """ if not state: return 0, why if state.get("ino") != st_raw.st_ino: return 0, "other_file" off = state.get("offset") if not isinstance(off, int) or isinstance(off, bool) or off < 0 or off > st_raw.st_size: return 0, "past_end" # RAW was truncated or reclaimed after the state was written return off, "state" def seed_state(raw_path, state_path): """Migration from 0.1.0 (no state): start the next run at the end of RAW. Run only while eslogger and the old filter are stopped (install.sh does), so the end of RAW is the end of what the old filter already read. """ _, why = read_state(state_path) if why == "ok": print(f"state kept: {state_path}") return 0 try: st = os.stat(raw_path) except FileNotFoundError: print("no raw file yet: the first run starts at 0") return 0 write_state(state_path, {"v": STATE_VERSION, "ino": st.st_ino, "dev": st.st_dev, "offset": st.st_size, "last_seq": None}) print(f"state {'replaced (it was unusable)' if why == 'bad_state' else 'seeded'} at the end of the raw file ({st.st_size} bytes)") return 0 def follow(raw_path, out_path, max_raw, heartbeat_s=60.0, live_lookup=None, state_path=None): flt = EsFilter(live_lookup=live_lookup) stopping = [] signal.signal(signal.SIGTERM, lambda *_: stopping.append(1)) state, why = read_state(state_path) if state and isinstance(state.get("last_seq"), int): flt.last_seq = state["last_seq"] # a restart of eslogger during our downtime is a reset while not os.path.exists(raw_path): if stopping: return 0 time.sleep(1) fin = open(raw_path, "rb") st0 = os.fstat(fin.fileno()) offset, how = resume_offset(state, why, st0) fin.seek(offset) fout, out_ino = open_out(out_path) fout.write(json.dumps({"schema": SCHEMA, "time": utc_now(), "type": "filter_start", "version": VERSION, "pid": os.getpid(), "resume": how, "offset": offset, "raw_bytes": st0.st_size, "state_file": bool(state_path)}, separators=(",", ":")).encode() + b"\n") buf = b"" saved = None save_ok = True def save(): # the offset of the first byte not yet filtered: what was read minus the partial line. # The output is synced first, so a power loss repeats events rather than loses them. nonlocal saved, save_ok if not state_path or fin.closed: return st = os.fstat(fin.fileno()) cur = {"v": STATE_VERSION, "ino": st.st_ino, "dev": st.st_dev, "offset": fin.tell() - len(buf), "last_seq": flt.last_seq} if cur == saved: return try: os.fsync(fout.fileno()) write_state(state_path, cur) saved = cur save_ok = True except OSError as e: # keep filtering: a crash would bring back the replay this file prevents flt.c.state_errors += 1 if save_ok: print(f"es-filter: state not saved: {e}", file=sys.stderr, flush=True) save_ok = False last_check = 0.0 last_save = time.monotonic() last_beat = time.monotonic() while True: if stopping: if heartbeat_s > 0: # the last interval's counters, gaps and resets included fout.write(flt.heartbeat(round(time.monotonic() - last_beat, 1), None).encode() + b"\n") save() fin.close() fout.close() return 0 now = time.monotonic() if now - last_save >= STATE_EVERY_S: last_save = now save() if heartbeat_s > 0 and now - last_beat >= heartbeat_s: last_beat = now try: rb = os.stat(raw_path).st_size except FileNotFoundError: rb = None fout.write(flt.heartbeat(heartbeat_s, rb).encode() + b"\n") chunk = fin.read(65536) if chunk: buf += chunk *lines, buf = buf.split(b"\n") for line in lines: o = flt.filter_line(line) if o is not None: fout.write(o.encode() + b"\n") continue if now - last_check >= 2: last_check = now try: if os.stat(out_path).st_ino != out_ino: fout.close() fout, out_ino = open_out(out_path) except FileNotFoundError: fout.close() fout, out_ino = open_out(out_path) try: st_path = os.stat(raw_path) except FileNotFoundError: st_path = None st_fd = os.fstat(fin.fileno()) if st_path is None or st_path.st_ino != st_fd.st_ino: fin.close() while not os.path.exists(raw_path) and not stopping: time.sleep(1) if stopping: continue fin = open(raw_path, "rb") buf = b"" save() continue pos = fin.tell() if st_fd.st_size < pos: fin.seek(0) buf = b"" continue if not buf and pos == st_fd.st_size and pos > max_raw: # Reclaim the raw file. The window between this size check and the # truncate is the only place an event can be lost; eslogger writes # through O_APPEND, so after truncation it continues at offset 0. # A loss here shows up as a gap in global_seq_num in the heartbeat. if os.stat(raw_path).st_size == pos: os.truncate(raw_path, 0) fin.seek(0) flt.c.reclaims += 1 save() time.sleep(0.5) def stats(path, secs): cin, bin_, cout, bout = (collections.Counter() for _ in range(4)) kept_exec = collections.Counter() red = 0 flt = EsFilter() with open(path, "rb") as f: for raw in f: try: ev = json.loads(raw) except ValueError: continue et = next(iter(ev.get("event") or {}), "unknown") cin[et] += 1 bin_[et] += len(raw) o = flt.transform(ev) if o is None: continue s = json.dumps(o, separators=(",", ":")) cout[et] += 1 bout[et] += len(s) + 1 red += o.get("redacted") or 0 if et == "exec": kept_exec[(o.get("target") or {}).get("path") or "?"] += 1 day = 86400.0 / secs print(f"sample {secs/60:.1f} min | in {sum(bin_.values())/1e6:.2f} MB -> out {sum(bout.values())/1e6:.3f} MB " f"({100*sum(bout.values())/max(1, sum(bin_.values())):.1f}%) | argument redactions: {red}") print(f"per day [estimate, linear]: in {sum(bin_.values())*day/1e6:.1f} MB, out {sum(bout.values())*day/1e6:.2f} MB") print(f"{'type':26} {'n_in':>6} {'n_out':>6} {'MB/d out':>9} {'avg B out':>9}") for et in sorted(cin, key=lambda k: -cin[k]): print(f"{et:26} {cin[et]:6d} {cout[et]:6d} {bout[et]*day/1e6:9.2f} {bout[et]//max(1, cout[et]):9d}") home = os.path.expanduser("~") print("-- kept exec, top 12:") for p, n in kept_exec.most_common(12): print(f" {n:5d} {p.replace(home, '~')}") def who_runs(target, path): by_image = collections.Counter() parents = collections.defaultdict(set) with open(path, "rb") as f: for raw in f: try: ev = json.loads(raw) except ValueError: continue ex = (ev.get("event") or {}).get("exec") if not ex: continue if ((ex.get("target") or {}).get("executable") or {}).get("path") == target: p = ev.get("process") or {} img = (p.get("executable") or {}).get("path") by_image[img] += 1 parents[img].add(p.get("ppid")) home = os.path.expanduser("~") print(f"who executes {target} (image before exec, count, distinct parent pids):") for img, n in by_image.most_common(10): print(f" {n:5d} {str(img).replace(home, '~')} parents={len(parents[img])}") def arg_value(argv, name, default): if name in argv: return float(argv[argv.index(name) + 1]) return default def arg_str(argv, name): return argv[argv.index(name) + 1] if name in argv else None def main(argv): if argv[:1] == ["--stdin"]: run_stdin() elif argv[:1] == ["--follow"] and len(argv) >= 3: mx = arg_value(argv, "--max-raw-mb", 64.0) hb = arg_value(argv, "--heartbeat-s", 60.0) return follow(argv[1], argv[2], int(mx * 1024 * 1024), hb, live_pidpath_factory(), arg_str(argv, "--state")) elif argv[:1] == ["--seed-state"] and len(argv) == 3: return seed_state(argv[1], argv[2]) elif argv[:1] == ["--stats"] and len(argv) == 3: stats(argv[1], float(argv[2])) elif argv[:1] == ["--who-runs"] and len(argv) == 3: who_runs(argv[1], argv[2]) elif argv[:1] == ["--version"]: print(VERSION) else: print(__doc__, file=sys.stderr) return 2 return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))