Download scan/sets_process.py from luokelabs/luoke-bench: direct link, hf CLI and curl.
- Browser
- Download file 31.2 kB
-
https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/scan/sets_process.py
- Command line
-
hf download hf://datasets/luokelabs/luoke-bench/scan/sets_process.py
-
curl -L -o sets_process.py https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/scan/sets_process.py
31.2 kB
| """The process set: a snapshot of a Mac's processes, for luoke-scan's `process` rule and the two findings of its | |
| `exposure` rule that are about running processes (listening beyond this Mac, secrets on a command line). | |
| A question is one process table of 30 to 80 rows: the system's own processes, the user's apps and their helpers, a | |
| terminal with a few shells and tools, and into that a few things planted (PLANT) and a few that only look like | |
| something (NEAR). The rules judge it from fakes.json and from the file system (is a program still there); the model | |
| reads the same table as text. EXPECTED is what each planted thing was meant to give, so make_sets.py can tell when | |
| the rules say something else. | |
| The program names of well-known tools (node, postgres, tmux...) are real: some rules go by them. Apps, the user's own | |
| tools, hosts and people are made up. | |
| """ | |
| from __future__ import annotations | |
| import datetime | |
| import os | |
| import random | |
| from fakemac import T0, iso | |
| RULES = {"process", "exposure"} | |
| KINDS = ["deleted-binary", "dyld-insert", "library-temp", "library-deleted", "pile-up", "orphan", "listening", "argv-secret", | |
| "partial"] | |
| EXPOSURE = {"exposure.listening": "listening", "exposure.argv-secret": "argv-secret"} | |
| # other accounts' processes: the rules do not look at them | |
| SYSTEM = [(0, "/usr/libexec/logd"), (0, "/usr/sbin/syslogd"), (0, "/usr/libexec/configd"), (0, "/usr/libexec/opendirectoryd"), | |
| (0, "/System/Library/CoreServices/powerd.bundle/powerd"), (65, "/usr/sbin/mDNSResponder"), (0, "/usr/sbin/bluetoothd"), | |
| (88, "/System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer"), (0, "/usr/libexec/airportd"), | |
| (0, "/usr/sbin/notifyd"), (0, "/usr/libexec/securityd"), (205, "/usr/libexec/locationd"), (0, "/usr/sbin/cupsd"), | |
| (202, "/usr/sbin/coreaudiod"), (0, "/usr/libexec/diskarbitrationd"), (0, "/usr/libexec/UserEventAgent"), | |
| (0, "/usr/sbin/KernelEventAgent"), (0, "/usr/libexec/thermalmonitord"), (0, "/usr/libexec/watchdogd")] | |
| ACCOUNTS = {0: "root", 65: "_mdnsresponder", 88: "_windowserver", 202: "_coreaudiod", 205: "_locationd"} | |
| # the user's own system processes (launchd's jobs). Only the ones this Mac has are used: a process of this user whose | |
| # program is not on the disk is a finding. | |
| USER_SYSTEM = ["/usr/sbin/cfprefsd", "/usr/libexec/pboard", "/usr/sbin/distnoted", "/usr/libexec/trustd", "/usr/libexec/secd", | |
| "/usr/libexec/lsd", "/System/Library/CoreServices/Dock.app/Contents/MacOS/Dock", | |
| "/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder", | |
| "/System/Library/CoreServices/SystemUIServer.app/Contents/MacOS/SystemUIServer", | |
| "/System/Library/CoreServices/ControlCenter.app/Contents/MacOS/ControlCenter", "/usr/libexec/UserEventAgent", | |
| "/usr/sbin/usernoted", "/usr/libexec/sharingd", "/usr/libexec/nsurlsessiond", "/usr/libexec/rapportd", | |
| "/System/Library/CoreServices/NotificationCenter.app/Contents/MacOS/NotificationCenter"] | |
| APPS = ["Quillbay", "Lumora", "Brackenmail", "Vextra", "Ondolo", "Tarnwell", "Mossgate", "Pinecrest", "Saltmarsh", "Emberline"] | |
| TERMINALS = ["Harborterm", "Glasshell"] | |
| OWN_TOOLS = ["tidewatch", "portloom", "syncferry", "logharbor", "buildkiln", "mapquill", "cachewren", "lintfinch"] | |
| BREW_TOOLS = ["node", "python3.13", "redis-server", "postgres", "ruby", "deno", "caddy", "git"] | |
| SYSTEM_LIBS = ["/usr/lib/libz.1.dylib", "/usr/lib/libSystem.B.dylib", "/usr/lib/libc++.1.dylib", "/usr/lib/libobjc.A.dylib", | |
| "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation", | |
| "/System/Library/Frameworks/Security.framework/Versions/A/Security"] | |
| SIGNED = {"adhoc": "临时签名,没有开发者担保", "unsigned": "没有签名", "invalid": "签名对不上:签名以后文件被改过", "apple": "Apple 签名"} | |
| TEAMS = ["7KQ2XW9LHV", "M4T8ZD3RPA", "Q9B6NH2YKC"] | |
| ALNUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
| BOUNDARY = {"other-user-gone", "other-user-listening"} | |
| BIG = {"pile-up-20", "pile-up-many", "pile-19", "app-helpers-25", "two-programs-12-each"} | |
| PLANT: dict = {} | |
| NEAR: dict = {} | |
| def _plant(name, expected, alone=()): | |
| def deco(f): | |
| PLANT[name] = (list(expected), f, set(alone)) | |
| return f | |
| return deco | |
| def _near(name): | |
| def deco(f): | |
| NEAR[name] = ([], f, set()) | |
| return f | |
| return deco | |
| def _secret(rng: random.Random, n: int = 14) -> str: | |
| return "".join(rng.choice(ALNUM) for _ in range(n)) | |
| class Snap: | |
| """The process table being built.""" | |
| def __init__(self, fx, rng: random.Random): | |
| self.fx, self.rng, self.me = fx, rng, os.getuid() | |
| self.procs: list = [] | |
| self.jobs: list = [] # what `launchctl list` names | |
| self.no_launchctl = False | |
| self.codesign: dict = {} | |
| self.last = rng.randint(280, 420) | |
| self.own = rng.sample(OWN_TOOLS, len(OWN_TOOLS)) | |
| self.session = datetime.timedelta(days=rng.randint(1, 18), hours=rng.randint(0, 23), minutes=rng.randint(0, 59)) | |
| self.shells: list = [] | |
| def pid(self) -> int: | |
| self.last += self.rng.randint(1, 41) | |
| return self.last | |
| def add(self, path: str, ppid: int, age: datetime.timedelta, *, uid: int | None = None, args=None, env=None, libs=None, | |
| listen=None, job: bool = False, exists: bool = True, filler: bool = False, gone: bool | None = None, | |
| secret: bool = False) -> int: | |
| """One process. path: as Fixture.p takes it; exists: its program is on the disk (made when it is the fake | |
| Mac's). gone: only for another account's process, whether the table says its program is gone. secret: its | |
| command line carries the secret the question planted.""" | |
| mine = uid is None | |
| real = self.fx.p(path) if not path.startswith("/") else path | |
| # nothing is older than the Mac's start, no child older than its parent | |
| older = [q["age"] for q in self.procs if q["pid"] == ppid] if ppid > 1 else [self.session] if self.procs else [] | |
| if older and age >= older[0]: | |
| age = older[0] - datetime.timedelta(seconds=self.rng.randint(2, 50)) | |
| # argv[0] is the program's name (a login shell's has a dash, an app's is its path) | |
| if args is not None and not (args and (args[0].lstrip("-") == os.path.basename(real) or args[0].endswith("/" + os.path.basename(real)))): | |
| args = [os.path.basename(real), *args] | |
| if mine and exists and real.startswith(self.fx.root): | |
| self.fx.program(real) | |
| p = {"pid": self.pid(), "ppid": ppid, "uid": self.me if mine else uid, "path": real, "started": iso(T0 - age), "age": age, | |
| "args": args, "env": env, "libs": libs, "listen": listen or [], "filler": filler, "secret": secret, | |
| "gone": (not os.path.exists(real)) if mine else bool(gone)} | |
| if mine and exists and p["gone"]: | |
| raise ValueError(f"{real} is not on this Mac: a process of this user with it would be a finding nobody planted") | |
| self.procs.append(p) | |
| if job: | |
| self.jobs.append(p["pid"]) | |
| return p["pid"] | |
| def lib(self, rel: str, signed: str | None = None, *, exists: bool = True) -> str: | |
| """A library file of the fake Mac; signed: who vouches for it (what the rules get instead of asking codesign).""" | |
| path = self.fx.p(rel) | |
| if exists: | |
| self.fx.file(rel, "not a real library\n") | |
| if signed: | |
| self.codesign[path] = signed | |
| return path | |
| def minutes(self, low: int, high: int) -> datetime.timedelta: | |
| return datetime.timedelta(minutes=self.rng.randint(low, high), seconds=self.rng.randint(0, 59)) | |
| def shell(self) -> int: | |
| return self.rng.choice(self.shells) | |
| def tool(self) -> str: | |
| """A tool of the user's own, a different one each time while they last.""" | |
| name = self.own.pop() if self.own else "tool-" + _secret(self.rng, 4).lower() | |
| return "~/.local/bin/" + name | |
| # ---------------------------------------------------------------- the ordinary Mac around it | |
| def _population(s: Snap) -> None: | |
| rng = s.rng | |
| s.add("/sbin/launchd", 0, s.session + datetime.timedelta(minutes=3), uid=0) | |
| s.procs[-1]["pid"] = 1 | |
| for uid, path in rng.sample(SYSTEM, rng.randint(7, 11)): | |
| s.add(path, 1, s.session + s.minutes(0, 2), uid=uid, filler=True) | |
| have = [p for p in USER_SYSTEM if os.path.exists(p)] | |
| if len(have) < 6: | |
| raise SystemExit("this Mac has too few of the system programs the questions name; see USER_SYSTEM") | |
| for path in rng.sample(have, rng.randint(6, min(9, len(have)))): | |
| s.add(path, 1, s.session - s.minutes(1, 30), job=True, filler=True) | |
| for app in rng.sample(APPS, rng.randint(2, 3)): | |
| base = f"Applications/{app}.app/Contents" | |
| main = s.add(f"{base}/MacOS/{app}", 1, s.minutes(20, 60 * 30), args=[f"/Applications/{app}.app/Contents/MacOS/{app}"]) | |
| for kind in rng.sample(["Renderer", "GPU", "Plugin", "Renderer", "Renderer"], rng.randint(1, 4)): | |
| s.add(f"{base}/Frameworks/{app} Helper ({kind}).app/Contents/MacOS/{app} Helper ({kind})", main, s.minutes(1, 600), | |
| libs=[s.fx.p(f"{base}/Frameworks/{app} Framework.framework/{app} Framework"), rng.choice(SYSTEM_LIBS)], filler=True) | |
| term = rng.choice(TERMINALS) | |
| t = s.add(f"Applications/{term}.app/Contents/MacOS/{term}", 1, s.minutes(60, 60 * 40)) | |
| for _ in range(rng.randint(2, 3)): | |
| s.shells.append(s.add("/bin/zsh", t, s.minutes(30, 60 * 30), args=["-zsh"])) | |
| home = "/Users/" + s.fx.user | |
| ordinary = [ | |
| ("opt-homebrew/bin/node", ["node", f"{home}/Projects/harbor-site/server.js"], [{"port": 3000, "address": "127.0.0.1"}]), | |
| ("opt-homebrew/bin/python3.13", ["python3.13", "-m", "http.server", "--bind", "127.0.0.1", "8000"], [{"port": 8000, "address": "127.0.0.1"}]), | |
| ("opt-homebrew/bin/redis-server", ["redis-server", "127.0.0.1:6379"], [{"port": 6379, "address": "127.0.0.1"}]), | |
| ("opt-homebrew/bin/postgres", ["postgres", "-D", "/opt/homebrew/var/postgresql@17"], [{"port": 5432, "address": "::1"}]), | |
| ("opt-homebrew/bin/git", ["git", "log", "--oneline", "-n", "200"], []), | |
| ("/usr/bin/tail", ["tail", "-f", f"{home}/Projects/harbor-site/logs/dev.log"], []), | |
| ("/usr/bin/ssh", ["ssh", "-N", "-L", "15432:127.0.0.1:5432", "deploy@bastion.internal.example"], [{"port": 15432, "address": "127.0.0.1"}]), | |
| ("/usr/bin/vim", ["vim", "notes.md"], []), | |
| ] | |
| for path, args, listen in rng.sample(ordinary, rng.randint(2, 4)): | |
| s.add(path, s.shell(), s.minutes(2, 60 * 5), args=args, listen=listen) | |
| # ---------------------------------------------------------------- planted | |
| def _(s): | |
| s.add(s.tool(), s.shell(), s.minutes(30, 60 * 40), exists=False, args=["serve", "--config", "dev.toml"]) | |
| def _(s): | |
| app = s.rng.choice([a for a in APPS if not os.path.exists(s.fx.p(f"Applications/{a}.app"))]) | |
| age = s.minutes(60 * 20, 60 * 24 * 6) | |
| for _ in range(s.rng.randint(2, 4)): | |
| s.add(f"~/Applications/{app}.app/Contents/MacOS/{app} Agent", 1, age, exists=False) | |
| def _(s): | |
| s.add(s.tool(), s.shell(), s.minutes(60, 60 * 30), exists=False, libs=[s.lib("~/.local/lib/libferry.2.dylib", exists=False)]) | |
| s.procs[-1]["libs_deleted"] = {s.procs[-1]["libs"][0]} | |
| def _dyld(s, signed, exists=True): | |
| hook = s.lib(s.rng.choice(["~/.cache/io.example.overlay/hook.dylib", "~/Library/Application Support/Overlayd/inject.dylib", | |
| "~/.local/lib/libtrace-shim.dylib"]), signed, exists=exists) | |
| shell = s.add("/bin/zsh", s.shell(), s.minutes(40, 60 * 9), args=["zsh"], env=["DYLD_INSERT_LIBRARIES=" + hook]) | |
| s.add(s.tool(), shell, s.minutes(1, 39), env=["DYLD_INSERT_LIBRARIES=" + hook], args=["run"]) | |
| def _(s): _dyld(s, s.rng.choice(["adhoc", "unsigned"])) | |
| def _(s): _dyld(s, "developer:" + s.rng.choice(TEAMS)) | |
| def _(s): _dyld(s, None, exists=False) | |
| def _temp_lib(s, rel, signed): | |
| lib = s.lib(rel, signed) | |
| s.add(s.tool(), s.shell(), s.minutes(5, 60 * 20), libs=[lib, s.rng.choice(SYSTEM_LIBS), s.lib("~/.local/lib/libcommon.1.dylib")], | |
| args=["watch"]) | |
| def _(s): _temp_lib(s, f"$TMPDIR/io.example.unpack-{_secret(s.rng, 6)}/libpayload.dylib", s.rng.choice(["adhoc", "unsigned"])) | |
| def _(s): _temp_lib(s, f"$TMPDIR/.{_secret(s.rng, 8)}/libhelper.dylib", "invalid") | |
| def _(s): _temp_lib(s, "~/Downloads/plugin-pack/libplugin.dylib", s.rng.choice(["adhoc", "developer:" + s.rng.choice(TEAMS)])) | |
| def _(s): | |
| old = s.lib(s.rng.choice(["opt-homebrew/lib/libssl.3.dylib", "~/.local/lib/libferry.2.dylib", "opt-homebrew/lib/libicuuc.76.dylib"]), exists=False) | |
| s.add(s.rng.choice(["opt-homebrew/bin/postgres", "opt-homebrew/bin/ruby"]) if "opt-homebrew" in old else s.tool(), s.shell(), | |
| s.minutes(60 * 30, 60 * 24 * 9), libs=[old, s.rng.choice(SYSTEM_LIBS)]) | |
| s.procs[-1]["libs_deleted"] = {old} | |
| def _pile(s, n): | |
| parent = s.add(s.tool(), s.shell(), s.minutes(60, 60 * 30), args=["poll", "--every", "5s"]) | |
| child = s.rng.choice(["/usr/sbin/lsof", "/bin/sleep", "opt-homebrew/bin/git"]) | |
| args = {"/usr/sbin/lsof": ["lsof", "-nP", "-iTCP", "-sTCP:LISTEN"], "/bin/sleep": ["sleep", "86400"], | |
| "opt-homebrew/bin/git": ["git", "status", "--porcelain"]}[child] | |
| for i in range(n): | |
| s.add(child, parent, s.minutes(0, 58), args=args) | |
| return parent | |
| def _(s): _pile(s, 20) | |
| def _(s): _pile(s, s.rng.randint(21, 30)) | |
| def _orphan(s, age): | |
| path = s.rng.choice([s.tool(), "opt-homebrew/bin/node", "opt-homebrew/bin/deno", "opt-homebrew/bin/caddy"]) | |
| home = "/Users/" + s.fx.user | |
| args = {"opt-homebrew/bin/node": ["node", f"{home}/Projects/old-demo/watch.js"], "opt-homebrew/bin/deno": ["deno", "run", "-A", "dev.ts"], | |
| "opt-homebrew/bin/caddy": ["caddy", "run", "--config", f"{home}/Caddyfile"]}.get(path, ["daemon"]) | |
| s.add(path, 1, age, args=args) | |
| def _(s): _orphan(s, s.minutes(60 * 7, 60 * 24 * 12)) | |
| def _(s): | |
| for _ in range(s.rng.randint(2, 3)): | |
| _orphan(s, s.minutes(60 * 7, 60 * 24 * 12)) | |
| def _(s): _orphan(s, datetime.timedelta(hours=6)) | |
| def _listening(s, address): | |
| port = s.rng.choice([3000, 4000, 5173, 8000, 8080, 8888, 9000]) | |
| path = s.rng.choice(["opt-homebrew/bin/node", "opt-homebrew/bin/python3.13", "opt-homebrew/bin/caddy", s.tool()]) | |
| args = {"opt-homebrew/bin/node": ["server.js", "--host", address, "--port", str(port)], | |
| "opt-homebrew/bin/python3.13": ["-m", "http.server", "--bind", address, str(port)], | |
| "opt-homebrew/bin/caddy": ["file-server", "--listen", (f"[{address}]" if ":" in address else address) + f":{port}"]}.get( | |
| path, ["serve", "--listen", (f"[{address}]" if ":" in address else address) + f":{port}"]) | |
| s.add(path, s.shell(), s.minutes(3, 60 * 8), args=args, listen=[{"port": port, "address": address}]) | |
| def _(s): _listening(s, "0.0.0.0") | |
| def _(s): _listening(s, "::") | |
| def _(s): _listening(s, f"192.168.{s.rng.randint(0, 20)}.{s.rng.randint(2, 250)}") | |
| def _(s): | |
| flag = s.rng.choice(["--password", "--token", "--api-key", "--client-secret", "--auth-token"]) | |
| value = _secret(s.rng, 18) | |
| s.add(s.tool(), s.shell(), s.minutes(2, 60 * 6), args=s.rng.choice([["sync", flag, value, "--verbose"], ["sync", f"{flag}={value}"]]), secret=True) | |
| def _(s): | |
| s.add("opt-homebrew/bin/mysql", s.shell(), s.minutes(2, 60 * 3), args=["mysql", "-h", "db.internal.example", "-u", "report", "-p" + _secret(s.rng, 12), "sales"], secret=True) | |
| def _(s): | |
| s.add("/usr/bin/curl", s.shell(), s.minutes(0, 20), args=["curl", "-s", "-u", "deploy:" + _secret(s.rng, 12), "https://builds.internal.example/api/artifacts"], secret=True) | |
| def _(s): | |
| s.add(s.rng.choice(["opt-homebrew/bin/node", s.tool()]), s.shell(), s.minutes(2, 60 * 9), | |
| args=["migrate", "--database-url", f"postgres://app:{_secret(s.rng, 12)}@db.internal.example:5432/app"], secret=True) | |
| def _(s): | |
| s.add("opt-homebrew/bin/python3.13", s.shell(), s.minutes(2, 60 * 4), args=["python3.13", "summarize.py", "--key", "sk-" + _secret(s.rng, 20) + "7"], secret=True) | |
| def _(s): s.no_launchctl = True | |
| # ---------------------------------------------------------------- only looks like something | |
| def _(s): _pile(s, 19) | |
| def _(s): | |
| app = s.rng.choice([a for a in APPS if not os.path.exists(s.fx.p(f"Applications/{a}.app"))]) | |
| base = f"Applications/{app}.app/Contents" | |
| main = s.add(f"{base}/MacOS/{app}", 1, s.minutes(60, 60 * 30)) | |
| for _ in range(s.rng.randint(22, 27)): | |
| s.add(f"{base}/Frameworks/{app} Helper (Renderer).app/Contents/MacOS/{app} Helper (Renderer)", main, s.minutes(1, 600)) | |
| def _(s): | |
| parent = s.add(s.tool(), s.shell(), s.minutes(60, 60 * 20), args=["build", "--jobs", "24"]) | |
| for child, args in (("opt-homebrew/bin/node", ["node", "worker.js"]), ("opt-homebrew/bin/git", ["git", "fetch", "--all"])): | |
| for _ in range(12): | |
| s.add(child, parent, s.minutes(0, 50), args=args) | |
| def _(s): _orphan(s, datetime.timedelta(hours=5, minutes=s.rng.randint(40, 59))) | |
| def _(s): | |
| s.add(s.tool(), 1, s.minutes(60 * 8, 60 * 24 * 10), job=True, args=["agent", "--launchd"]) | |
| def _(s): | |
| path, args = s.rng.choice([("opt-homebrew/bin/gpg-agent", ["gpg-agent", "--homedir", f"/Users/{s.fx.user}/.gnupg", "--daemon"]), | |
| ("opt-homebrew/bin/tmux", ["tmux", "new-session", "-d", "-s", "work"]), | |
| ("/usr/bin/ssh-agent", ["ssh-agent", "-s"])]) | |
| s.add(path, 1, s.minutes(60 * 8, 60 * 24 * 15), args=args) | |
| def _(s): | |
| app = s.rng.choice([a for a in APPS if not os.path.exists(s.fx.p(f"Applications/{a}.app"))]) | |
| s.add(f"Applications/{app}.app/Contents/XPCServices/{app}Sync.xpc/Contents/MacOS/{app}Sync", 1, s.minutes(60 * 8, 60 * 24 * 5)) | |
| def _(s): _listening(s, s.rng.choice(["127.0.0.1", "::1", "::ffff:127.0.0.1"])) | |
| def _(s): | |
| have = [p for p in ("/usr/libexec/rapportd", "/usr/libexec/sharingd", "/System/Library/CoreServices/ControlCenter.app/Contents/MacOS/ControlCenter") | |
| if os.path.exists(p) and not any(q["path"] == p for q in s.procs)] | |
| if have: | |
| s.add(have[0], 1, s.session - s.minutes(1, 30), job=True, listen=[{"port": s.rng.choice([5000, 7000, 49152]), "address": "0.0.0.0"}]) | |
| def _(s): | |
| args = s.rng.choice([["sync", "--password-file", f"/Users/{s.fx.user}/.config/syncferry/pass"], ["sync", "--token", "$SYNC_TOKEN"], | |
| ["sync", "--api-key", "@/run/secrets/api_key"], ["sync", "--token-file=/Users/" + s.fx.user + "/.token"]]) | |
| s.add(s.tool(), s.shell(), s.minutes(2, 60 * 6), args=args) | |
| def _(s): | |
| s.add("opt-homebrew/bin/mysql", s.shell(), s.minutes(2, 60 * 3), args=["mysql", "-h", "db.internal.example", "-u", "report", "-p", "sales"]) | |
| def _(s): | |
| s.add("/usr/bin/ssh", s.shell(), s.minutes(2, 60 * 3), args=["ssh", "-p2222", "deploy@build.internal.example"]) | |
| def _(s): | |
| s.add("/usr/bin/curl", s.shell(), s.minutes(0, 20), args=["curl", "-sO", "https://deploy@files.internal.example/sk-learn-notes/data.tar.gz"]) | |
| def _(s): | |
| s.add(s.tool(), s.shell(), s.minutes(2, 60 * 6), env=["DYLD_LIBRARY_PATH=/opt/homebrew/lib", "DYLD_FALLBACK_FRAMEWORK_PATH=/Library/Frameworks"]) | |
| def _(s): | |
| s.add(s.tool(), s.shell(), s.minutes(2, 60 * 6), env=["DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib"], args=["test", "--guard-malloc"]) | |
| def _(s): | |
| lib = s.lib("Applications/Xcode.app/Contents/Developer/usr/lib/libMainThreadChecker.dylib", "apple") | |
| s.add(s.tool(), s.shell(), s.minutes(2, 60 * 2), env=["DYLD_INSERT_LIBRARIES=" + lib], args=["--debug"]) | |
| def _(s): | |
| app = s.rng.choice([a for a in APPS if not os.path.exists(s.fx.p(f"Applications/{a}.app"))]) | |
| base = f"$TMPDIR/AppTranslocation/0A1B2C3D-0000-4000-8000-{s.rng.randint(10**11, 10**12 - 1)}/d/{app}.app/Contents" | |
| s.add(f"{base}/MacOS/{app}", 1, s.minutes(5, 300), libs=[s.lib(f"{base}/Frameworks/{app}Kit.framework/{app}Kit")]) | |
| def _(s): | |
| s.add(s.tool(), s.shell(), s.minutes(5, 300), libs=[s.lib(f"$TMPDIR/com.apple.dt.cache-{_secret(s.rng, 6)}/libPreview.dylib", "apple")]) | |
| def _(s): | |
| lib = "/System/Library/PrivateFrameworks/OldSupport.framework/Versions/A/OldSupport" | |
| s.add(s.tool(), s.shell(), s.minutes(60 * 30, 60 * 24 * 9), libs=[lib, "/usr/lib/libz.1.dylib"]) | |
| s.procs[-1]["libs_deleted"] = {lib} | |
| def _(s): | |
| s.add("/opt/harborline/bin/gatewayd", 1, s.session, uid=0, gone=True, args=["gatewayd", "--config", "/opt/harborline/etc/gateway.toml"]) | |
| def _(s): | |
| s.add("/usr/local/sbin/metricsd", 1, s.session, uid=0, listen=[{"port": 9100, "address": "0.0.0.0"}], args=["metricsd"]) | |
| # ---------------------------------------------------------------- which questions | |
| def _pick(rng: random.Random, table: dict, n: int, kinds: set, names: set) -> list: | |
| out, pool = [], list(table) | |
| rng.shuffle(pool) | |
| for name in pool: | |
| if len(out) >= n: | |
| break | |
| expected, _, alone = table[name] | |
| if set(expected) & kinds or alone & names or any(name in table[o][2] for o in names if o in table): | |
| continue | |
| if name in BIG and names & BIG: # one long run of rows a table: it has 80 at most | |
| continue | |
| out.append(name) | |
| kinds |= set(expected) | |
| names.add(name) | |
| if len(out) == n: | |
| break | |
| return out | |
| def recipes(rng: random.Random) -> list: | |
| """100 tables: 20 with only things that look like something, each planted thing twice on its own (48, most with one | |
| or two look-alikes beside it), 32 with two or three planted things.""" | |
| out = [{"group": "near", "plant": [], "near": _pick(rng, NEAR, rng.randint(2, 3), set(), set())} for _ in range(20)] | |
| for name in list(PLANT) * 2: | |
| out.append({"group": "single", "plant": [name], "near": _pick(rng, NEAR, rng.randint(0, 2), set(), {name})}) | |
| for _ in range(32): | |
| names: set = set() | |
| plant = _pick(rng, PLANT, rng.randint(2, 3), set(), names) | |
| out.append({"group": "multi", "plant": plant, "near": _pick(rng, NEAR, rng.randint(0, 2), set(), names)}) | |
| rng.shuffle(out) | |
| return out | |
| # ---------------------------------------------------------------- one table | |
| def _age(d: datetime.timedelta) -> str: | |
| minutes = int(d.total_seconds()) // 60 | |
| days, hours, mins = minutes // 1440, minutes % 1440 // 60, minutes % 60 | |
| if days: | |
| return f"{days}天{hours}小时" | |
| if hours: | |
| return f"{hours}小时{mins}分" | |
| return f"{mins}分" | |
| def _signed(s: Snap, path: str) -> str: | |
| sig = s.codesign.get(path) | |
| if sig is None: | |
| return "" | |
| return "签名:" + (SIGNED.get(sig) or "开发者签名,团队 " + sig.split(":", 1)[1]) | |
| def _render(s: Snap) -> str: | |
| lines = [f"这台 Mac 现在登录的用户是 {s.fx.user}。下面是它此刻的进程表:进程号、父进程号、用户、已经运行多久、程序;" | |
| "读得到的还有命令行、DYLD_ 开头的环境变量、载入的库(程序自己和系统自带的大多略去)、监听的地址和端口。", ""] | |
| for p in sorted(s.procs, key=lambda p: p["pid"]): | |
| user = s.fx.user if p["uid"] == s.me else ACCOUNTS.get(p["uid"], str(p["uid"])) | |
| head = f"PID {p['pid']} 父进程 {p['ppid']} 用户 {user} 已运行 {_age(p['age'])} 程序 {p['path']}" | |
| if p["gone"]: | |
| head += " 【程序文件已经不在盘上】" | |
| lines.append(head) | |
| if p["args"]: | |
| lines.append(" 命令行:" + " ".join(p["args"])) | |
| for e in p["env"] or []: | |
| name, _, value = e.partition("=") | |
| notes = [_signed(s, lib) or ("这个库的文件不在盘上" if not os.path.exists(lib) else "") | |
| for lib in value.split(":") if lib.startswith(s.fx.root)] if name == "DYLD_INSERT_LIBRARIES" else [] | |
| notes = [n for n in notes if n] | |
| lines.append(" 环境变量:" + e + (f"({';'.join(notes)})" if notes else "")) | |
| if p["libs"]: | |
| shown = [] | |
| for lib in p["libs"]: | |
| marks = [m for m in ("文件已经被删掉" if lib in p.get("libs_deleted", ()) else "", _signed(s, lib)) if m] | |
| shown.append(lib + (f"({','.join(marks)})" if marks else "")) | |
| lines.append(" 载入的库:" + ";".join(shown)) | |
| if p["listen"]: | |
| lines.append(" 监听:" + "、".join(f"[{x['address']}]:{x['port']}" if ":" in x["address"] else f"{x['address']}:{x['port']}" | |
| for x in p["listen"])) | |
| lines.append("") | |
| if s.no_launchctl: | |
| lines.append("launchd 管着的任务(launchctl list):没有答复,这一次没读到。") | |
| else: | |
| lines.append("launchd 管着的任务(launchctl list 里有的进程号):" + "、".join(str(x) for x in sorted(s.jobs))) | |
| return "\n".join(lines) + "\n" | |
| def build(fx, recipe: dict, rng: random.Random) -> dict: | |
| s = Snap(fx, rng) | |
| _population(s) | |
| expected, boundary = [], set() | |
| for table, names in ((PLANT, recipe["plant"]), (NEAR, recipe["near"])): | |
| for name in names: | |
| exp, plant, _ = table[name] | |
| plant(s) | |
| expected += exp | |
| if name in BOUNDARY: | |
| boundary.add(name) | |
| # 30 to 80 rows: more helpers of an app when short, fewer of the ordinary ones when long | |
| parents = {p["ppid"] for p in s.procs} | |
| extra = [p for p in s.procs if p["filler"] and p["pid"] not in parents] | |
| rng.shuffle(extra) | |
| while len(s.procs) > 80 and extra: | |
| gone = extra.pop() | |
| s.procs.remove(gone) | |
| if gone["pid"] in s.jobs: | |
| s.jobs.remove(gone["pid"]) | |
| apps = [p for p in s.procs if p["ppid"] == 1 and "/Applications/" in p["path"] and p["path"].endswith(tuple(APPS))] | |
| while len(s.procs) < 30 and apps: | |
| main = rng.choice(apps) | |
| app = os.path.basename(main["path"]) | |
| s.add(os.path.dirname(os.path.dirname(main["path"])) + f"/Frameworks/{app} Helper (Renderer).app/Contents/MacOS/{app} Helper (Renderer)", | |
| main["pid"], s.minutes(1, 600), filler=True) | |
| if not 30 <= len(s.procs) <= 80: | |
| raise ValueError(f"{len(s.procs)} rows: a table has 30 to 80") | |
| fx.fakes["processes"] = [] | |
| for p in s.procs: | |
| row = {"pid": p["pid"], "ppid": p["ppid"], "uid": p["uid"], "path": p["path"], "started": p["started"]} | |
| if p["args"] is not None: | |
| row["arguments"] = p["args"] | |
| if p["env"] is not None: | |
| row["environment"] = p["env"] | |
| if p["libs"] is not None: | |
| row["libraries"] = [{"path": lib, "deleted": lib in p.get("libs_deleted", ())} for lib in p["libs"]] | |
| if p["listen"]: | |
| row["listening"] = p["listen"] | |
| fx.fakes["processes"].append(row) | |
| fx.fakes["launchdPIDs"] = None if s.no_launchctl else sorted(s.jobs) | |
| fx.fakes["codesign"] = s.codesign | |
| return {"facts": _render(s), "expected": expected, "boundary": boundary, "snap": s} | |
| def _same(a: str, b: str) -> bool: | |
| strip = lambda p: p[len("/private"):] if p.startswith(("/private/var/", "/private/tmp/")) else p # noqa: E731 | |
| return strip(a) == strip(b) | |
| def answer(fx, report: dict, made: dict) -> tuple: | |
| """(the rules' findings as the answer, the other rules that said something). targets: the processes a finding is | |
| about (any one of them names it): the ones the rule lists, and the others it means (it lists at most 20).""" | |
| s: Snap = made["snap"] | |
| mine = [p for p in s.procs if p["uid"] == s.me] | |
| out, others = [], set() | |
| for f in report.get("findings") or []: | |
| rule = f["rule"] | |
| kind = rule.split(".", 1)[1] if rule.startswith("process.") else EXPOSURE.get(rule) | |
| if kind is None: | |
| others.add(rule) | |
| continue | |
| ev, path = f.get("evidence") or {}, f.get("path") or "" | |
| pids = {int(x) for x in (ev.get("pids") or "").split(",") if x} | |
| if kind == "deleted-binary": | |
| pids |= {p["pid"] for p in mine if _same(p["path"], path)} | |
| elif kind == "pile-up": | |
| parent = int(ev["parent_pid"]) | |
| pids |= {parent} | {p["pid"] for p in mine if p["ppid"] == parent and _same(p["path"], path)} | |
| elif kind == "listening": | |
| pids |= {p["pid"] for p in mine if _same(p["path"], path) and any(not x["address"].startswith(("127.", "::1", "::ffff:127.")) for x in p["listen"])} | |
| elif kind == "argv-secret": | |
| same = [p for p in mine if _same(p["path"], path) and p["args"]] | |
| pids |= {p["pid"] for p in same if p["secret"]} or {p["pid"] for p in same} | |
| elif kind == "dyld-insert": | |
| pids |= {p["pid"] for p in mine if any(e.startswith("DYLD_INSERT_LIBRARIES=") and any(_same(x, path) for x in e.split("=", 1)[1].split(":")) | |
| for e in p["env"] or [])} | |
| if not pids and kind != "partial": | |
| raise ValueError(f"no process found for {rule} at {path}") | |
| out.append({"rule": rule, "kind": kind, "severity": f["severity"], "verdict": f["verdict"], | |
| "targets": sorted((str(x) for x in pids), key=int), "title": fx.shown(f.get("title", ""))}) | |
| return out, others | |