"""The posture set: firewall and the other basic security settings, as the answers of the system commands luoke-scan's `posture` rule asks. A question is one Mac: the output of each command, when it started, how many system updates wait, when XProtect's definitions last changed. Built from a state (what is on, what is off), a few things planted into it (PLANT: what the question is for) and a few that only look like something (NEAR: at a threshold, worded differently, not what the rule looks at). What the rules say of it is the answer; EXPECTED here is only what each planted thing was meant to give, so make_sets.py can tell when the rules say something else. """ from __future__ import annotations import datetime import random from fakemac import LOCAL, T0, iso RULES = {"posture"} KINDS = ["filevault", "firewall", "stealth", "sip", "gatekeeper", "screen-lock", "screen-lock-delay", "autoupdate", "pending-updates", "remote-login", "screen-sharing", "file-sharing", "internet-sharing", "airdrop-everyone", "auto-login", "guest", "trusted-roots", "xprotect-stale", "partial"] FIREWALL = "/usr/libexec/ApplicationFirewall/socketfilterfw" SHARING = {"remote-login": "com.openssh.sshd", "screen-sharing": "com.apple.screensharing", "file-sharing": "com.apple.smbd", "internet-sharing": "com.apple.NetworkSharing"} # services the rule does not look at; some of them on OTHER_SERVICES = ["com.apple.ftpd", "com.apple.AEServer", "com.apple.CSCSupportd", "com.apple.mdmclient.daemon.runatboot", "com.apple.ftp-proxy", "com.apple.rexecd", "com.apple.uucp", "com.apple.telnetd", "com.apple.ODSAgent", "com.apple.rpmuxd", "com.apple.tftpd", "com.apple.nfsd"] CERT_NAMES = ["mkcert {user}@studio-mini", "Harborline Proxy Root CA", "Tidewater Labs Internal CA", "Charles Proxy CA ({user})", "Brackenfield Dev Root", "Mossgate Office Gateway CA", "localhost dev CA", "Quillbay Debug Root"] HOSTS = ["nas.home.example", "router.lan.example", "printer.office.example", "git.internal.example"] # ---------------------------------------------------------------- what can be planted # name -> (the state's keys it sets, what the rule is meant to say, how it changes the state) PLANT: dict = {} NEAR: dict = {} BOUNDARY = {"filevault-deferred", "sip-custom", "filevault-decrypting", "other-service-on", "long-uptime-no-updates"} def _plant(name, keys, expected): def deco(f): PLANT[name] = (set(keys), list(expected), f) return f return deco def _near(name, keys): def deco(f): NEAR[name] = (set(keys), [], f) return f return deco def _cert(rng, s, kind): used = {c["name"] for c in s["certs_user"] + s["certs_admin"]} name = rng.choice([n for n in CERT_NAMES if n.format(user=s["user"]) not in used]).format(user=s["user"]) return {"name": name, "kind": kind, "host": rng.choice(HOSTS)} @_plant("filevault-off", ["filevault"], ["filevault"]) def _(s, rng): s["filevault"] = "off" @_plant("filevault-deferred", ["filevault"], ["filevault"]) def _(s, rng): s["filevault"] = "deferred" @_plant("firewall-off", ["firewall"], ["firewall"]) def _(s, rng): s["firewall"] = "off" @_plant("firewall-and-stealth-off", ["firewall", "stealth"], ["firewall"]) def _(s, rng): s["firewall"], s["stealth"] = "off", rng.choice(["off", "off2"]) @_plant("stealth-off", ["firewall", "stealth"], ["stealth"]) def _(s, rng): s["stealth"] = "off" @_plant("stealth-off-new-wording", ["firewall", "stealth"], ["stealth"]) def _(s, rng): s["stealth"] = "off2" @_plant("sip-off", ["sip"], ["sip"]) def _(s, rng): s["sip"] = "off" @_plant("sip-custom", ["sip"], ["sip"]) def _(s, rng): s["sip"] = "custom" @_plant("gatekeeper-off", ["gatekeeper"], ["gatekeeper"]) def _(s, rng): s["gatekeeper"] = "off" @_plant("screen-lock-off", ["screenlock"], ["screen-lock"]) def _(s, rng): s["screenlock"] = "off" @_plant("screen-lock-delay", ["screenlock"], ["screen-lock-delay"]) def _(s, rng): s["screenlock"] = rng.choice(["301", "600", "900", "1800", "3600", "14400"]) @_plant("autoupdate-off", ["autoupdate"], ["autoupdate"]) def _(s, rng): s["autoupdate"] = "0" @_plant("pending-updates", ["uptime"], ["pending-updates"]) def _(s, rng): s["uptime"], s["pending"] = datetime.timedelta(days=rng.randint(31, 140), minutes=rng.randint(1, 1400)), rng.randint(1, 4) @_plant("pending-updates-exactly-30-days", ["uptime"], ["pending-updates"]) def _(s, rng): s["uptime"], s["pending"] = datetime.timedelta(days=30), rng.randint(1, 3) @_plant("remote-login", ["sshd"], ["remote-login"]) def _(s, rng): s["services"][SHARING["remote-login"]] = True @_plant("remote-login-old-format", ["sshd", "format"], ["remote-login"]) def _(s, rng): s["services"][SHARING["remote-login"]], s["old_format"] = True, True @_plant("screen-sharing", ["screensharing"], ["screen-sharing"]) def _(s, rng): s["services"][SHARING["screen-sharing"]] = True @_plant("file-sharing", ["smbd"], ["file-sharing"]) def _(s, rng): s["services"][SHARING["file-sharing"]] = True @_plant("internet-sharing", ["networksharing"], ["internet-sharing"]) def _(s, rng): s["services"][SHARING["internet-sharing"]] = True @_plant("airdrop-everyone", ["airdrop"], ["airdrop-everyone"]) def _(s, rng): s["airdrop"] = "Everyone" @_plant("auto-login", ["autologin"], ["auto-login"]) def _(s, rng): s["autologin"] = s["user"] @_plant("guest", ["guest"], ["guest"]) def _(s, rng): s["guest"] = "1" @_plant("trusted-root-always", ["certs"], ["trusted-roots"]) def _(s, rng): s["certs_user"].append(_cert(rng, s, "always")) @_plant("trusted-root-admin", ["certs"], ["trusted-roots"]) def _(s, rng): s["certs_admin"].append(_cert(rng, s, "root")) @_plant("trusted-root-both-domains", ["certs"], ["trusted-roots"]) def _(s, rng): c = _cert(rng, s, "root") s["certs_user"].append(c) s["certs_admin"].append(dict(c)) @_plant("xprotect-stale", ["xprotect"], ["xprotect-stale"]) def _(s, rng): s["xprotect"] = datetime.timedelta(days=rng.randint(61, 240), hours=rng.randint(1, 23)) @_plant("probe-failed", ["probe"], ["partial"]) def _(s, rng): # not a setting something else in this question sets; not stealth mode when the firewall may be off (it is not asked then) free = [k for k in ("filevault", "firewall", "sip", "gatekeeper", "launchctl", "stealth") if k not in s["touched"]] if "firewall" in s["touched"] and "stealth" in free: free.remove("stealth") key = rng.choice(free) s["touched"].add(key) if key == "launchctl": s["launchctl_fail"] = True else: s[key] = "fail" @_plant("screen-lock-unknown", ["screenlock"], ["partial"]) def _(s, rng): s["screenlock"] = "unknown" @_near("screen-lock-delay-300", ["screenlock"]) def _(s, rng): s["screenlock"] = "300" @_near("uptime-29-days-with-updates", ["uptime"]) def _(s, rng): s["uptime"], s["pending"] = datetime.timedelta(days=29, hours=rng.randint(12, 23), minutes=rng.randint(0, 59)), rng.randint(1, 3) @_near("long-uptime-no-updates", ["uptime"]) def _(s, rng): s["uptime"], s["pending"] = datetime.timedelta(days=rng.randint(40, 200), hours=rng.randint(0, 23)), 0 @_near("xprotect-59-days", ["xprotect"]) def _(s, rng): s["xprotect"] = datetime.timedelta(days=59, hours=rng.randint(0, 22)) @_near("xprotect-exactly-60-days", ["xprotect"]) def _(s, rng): s["xprotect"] = datetime.timedelta(days=60) @_near("cert-for-one-host", ["certs"]) def _(s, rng): s["certs_user"].append(_cert(rng, s, "limited")) @_near("cert-denied", ["certs"]) def _(s, rng): s["certs_admin"].append(_cert(rng, s, "deny")) @_near("old-format-all-off", ["sshd", "screensharing", "smbd", "networksharing", "format"]) def _(s, rng): s["old_format"] = True @_near("other-service-on", ["other-services"]) def _(s, rng): for label in rng.sample(OTHER_SERVICES, 2): s["services"][label] = True @_near("firewall-blocks-all", ["firewall"]) def _(s, rng): s["firewall"] = "block-all" @_near("filevault-encrypting", ["filevault"]) def _(s, rng): s["filevault"] = "encrypting" @_near("filevault-decrypting", ["filevault"]) def _(s, rng): s["filevault"] = "decrypting" @_near("airdrop-off", ["airdrop"]) def _(s, rng): s["airdrop"] = "Off" @_near("screen-lock-short-delay", ["screenlock"]) def _(s, rng): s["screenlock"] = rng.choice(["5", "60", "120"]) # ---------------------------------------------------------------- which questions def _pick(rng: random.Random, table: dict, n: int, taken: set, kinds: set | None = None) -> list: """n names from table whose keys do not meet (two things cannot set the same setting), nor the ones taken.""" out, names = [], list(table) rng.shuffle(names) for name in names: if len(out) >= n: break keys, expected, _ = table[name] if keys & taken or (kinds is not None and set(expected) & kinds): continue out.append(name) taken |= keys if kinds is not None: kinds |= set(expected) if len(out) == n: break return out def recipes(rng: random.Random) -> list: """80 questions: 8 with nothing wrong, each planted thing once on its own (28), 22 with two to four of them, 14 with only things that look like something, 8 with both kinds.""" out = [{"group": "clean", "plant": [], "near": []} for _ in range(8)] out += [{"group": "single", "plant": [name], "near": []} for name in PLANT] for _ in range(22): out.append({"group": "multi", "plant": _pick(rng, PLANT, rng.randint(2, 4), set(), set()), "near": []}) for _ in range(14): out.append({"group": "near", "plant": [], "near": _pick(rng, NEAR, rng.randint(1, 3), set())}) for _ in range(8): taken: set = set() plant = _pick(rng, PLANT, rng.randint(1, 2), taken, set()) out.append({"group": "mixed", "plant": plant, "near": _pick(rng, NEAR, rng.randint(1, 2), taken)}) rng.shuffle(out) return out # ---------------------------------------------------------------- one Mac def _state(rng: random.Random, user: str) -> dict: services = {label: False for label in SHARING.values()} for label in rng.sample(OTHER_SERVICES, rng.randint(2, 5)): services[label] = False return {"user": user, "touched": set(), "filevault": "on", "firewall": "on", "stealth": rng.choice(["on", "on2"]), "sip": "on", "gatekeeper": "on", "screenlock": rng.choice(["immediate", "immediate", "5"]), "autoupdate": rng.choice(["1", "missing"]), "services": services, "old_format": False, "launchctl_fail": False, "airdrop": rng.choice(["Contacts Only", "Contacts Only", "Off"]), "autologin": None, "guest": rng.choice(["0", "missing"]), "certs_user": [], "certs_admin": [], "uptime": datetime.timedelta(days=rng.randint(0, 20), hours=rng.randint(1, 23), minutes=rng.randint(0, 59)), "pending": rng.choice([0, 0, 0, 1]), "xprotect": datetime.timedelta(days=rng.randint(1, 40), hours=rng.randint(0, 23))} FAIL = (-1, "", "") # the command did not finish def _trust(certs: list) -> tuple: if not certs: return 1, "SecTrustSettings: No Trust Settings were found.\n", "" lines = [f"Number of trusted certs = {len(certs)}"] for i, c in enumerate(certs): lines.append(f"Cert {i}: {c['name']}") if c["kind"] == "always": lines.append(" Number of trust settings : 0") continue result = "kSecTrustSettingsResultDeny" if c["kind"] == "deny" else "kSecTrustSettingsResultTrustRoot" lines += [" Number of trust settings : 2", " Trust Setting 0:", " Policy OID : SSL"] if c["kind"] == "limited": lines.append(f" Policy String : {c['host']}") lines += [" Allowed Error : CSSMERR_TP_CERT_EXPIRED", f" Result Type : {result}", " Trust Setting 1:", " Policy OID : Basic X509"] if c["kind"] == "limited": lines.append(f" Policy String : {c['host']}") lines.append(f" Result Type : {result}") return 0, "\n".join(lines) + "\n", "" def _commands(s: dict, rng: random.Random) -> list: """(what is shown as typed, tool, the arguments that tell it apart, status, stdout, stderr), in the order shown.""" stamp = f"sysadminctl[{rng.randint(900, 60000)}:{rng.randint(10000, 900000)}] " defaults_missing = lambda domain, key: (1, "", f"The domain/default pair of ({domain}, {key}) does not exist\n") # noqa: E731 fv = {"on": (0, "FileVault is On.\n", ""), "off": (0, "FileVault is Off.\n", ""), "deferred": (0, f"FileVault is Off.\nDeferred enablement appears to be active for user '{s['user']}'.\n", ""), "encrypting": (0, f"FileVault is On.\nEncryption in progress: Percent completed = {rng.randint(3, 96)}\n", ""), "decrypting": (0, f"FileVault is On.\nDecryption in progress: Percent completed = {rng.randint(3, 96)}\n", ""), "fail": FAIL}[s["filevault"]] fw = {"on": (0, "Firewall is enabled. (State = 1)\n", ""), "off": (0, "Firewall is disabled. (State = 0)\n", ""), "block-all": (0, "Firewall is set to block all non-essential incoming connections. (State = 2)\n", ""), "fail": FAIL}[s["firewall"]] st = {"on": (0, "Firewall stealth mode is on\n", ""), "on2": (0, "Stealth mode enabled\n", ""), "off": (0, "Firewall stealth mode is off\n", ""), "off2": (0, "Stealth mode disabled\n", ""), "fail": FAIL}[s["stealth"]] # custom: Filesystem Protections is off; "Apple Internal: disabled" is what every Mac not Apple's own shows sip = {"on": (0, "System Integrity Protection status: enabled.\n", ""), "off": (0, "System Integrity Protection status: disabled.\n", ""), "custom": (0, "System Integrity Protection status: unknown (Custom Configuration).\n\nConfiguration:\n\tApple Internal: disabled\n" "\tKext Signing: enabled\n\tFilesystem Protections: disabled\n\tDebugging Restrictions: enabled\n\tDTrace Restrictions: enabled\n" "\tNVRAM Protections: enabled\n\tBaseSystem Verification: enabled\n\nThis is an unsupported configuration, likely to break in " "the future and leave your machine in an unknown state.\n", ""), "fail": FAIL}[s["sip"]] gk = {"on": (0, "assessments enabled\n", ""), "off": (0, "assessments disabled\n", ""), "fail": FAIL}[s["gatekeeper"]] lock = s["screenlock"] sl = (0, stamp + ("screenLock is off\n" if lock == "off" else "Unable to read the screenLock setting\n" if lock == "unknown" else "screenLock delay is immediate\n" if lock == "immediate" else f"screenLock delay is {lock} seconds\n"), "") au = defaults_missing("/Library/Preferences/com.apple.SoftwareUpdate", "AutomaticCheckEnabled") if s["autoupdate"] == "missing" \ else (0, s["autoupdate"] + "\n", "") if s["launchctl_fail"]: lc = FAIL else: labels = list(s["services"]) rng.shuffle(labels) word = (lambda on: "false" if on else "true") if s["old_format"] else (lambda on: "enabled" if on else "disabled") lc = (0, "disabled services = {\n" + "".join(f"\t\"{label}\" => {word(s['services'][label])}\n" for label in labels) + "}\n", "") ad = (0, s["airdrop"] + "\n", "") al = (0, s["autologin"] + "\n", "") if s["autologin"] else defaults_missing("/Library/Preferences/com.apple.loginwindow", "autoLoginUser") gu = defaults_missing("/Library/Preferences/com.apple.loginwindow", "GuestEnabled") if s["guest"] == "missing" else (0, s["guest"] + "\n", "") return [ ("fdesetup status", "/usr/bin/fdesetup", [], *fv), (FIREWALL + " --getglobalstate", FIREWALL, ["--getglobalstate"], *fw), (FIREWALL + " --getstealthmode", FIREWALL, ["--getstealthmode"], *st), ("csrutil status", "/usr/bin/csrutil", [], *sip), ("spctl --status", "/usr/sbin/spctl", [], *gk), ("sysadminctl -screenLock status", "/bin/sh", [], *sl), ("defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled", "/usr/bin/defaults", ["AutomaticCheckEnabled"], *au), ("launchctl print-disabled system", "/bin/launchctl", [], *lc), ("defaults read com.apple.sharingd DiscoverableMode", "/usr/bin/defaults", ["DiscoverableMode"], *ad), ("defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser", "/usr/bin/defaults", ["autoLoginUser"], *al), ("defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled", "/usr/bin/defaults", ["GuestEnabled"], *gu), # the entry with -d first: an entry answers every call that has all of its arguments ("security dump-trust-settings -d", "/usr/bin/security", ["dump-trust-settings", "-d"], *_trust(s["certs_admin"])), ("security dump-trust-settings", "/usr/bin/security", ["dump-trust-settings"], *_trust(s["certs_user"])), ] def _uptime(up: datetime.timedelta) -> str: hours, minutes = up.seconds // 3600, up.seconds % 3600 // 60 clock = f"{hours}:{minutes:02d}" if hours else f"{minutes} mins" days = f"{up.days} day{'s' if up.days != 1 else ''}, " if up.days else "" return f"{T0.astimezone(LOCAL):%H:%M} up {days}{clock}, 2 users, load averages: 1.42 1.31 1.25" def build(fx, recipe: dict, rng: random.Random) -> dict: s = _state(rng, fx.user) expected, boundary = [], set() todo = [(PLANT, n) for n in recipe["plant"]] + [(NEAR, n) for n in recipe["near"]] # what the question's things set, known before any of them is applied (probe-failed takes a probe none of them needs; # the sharing services are all read from launchctl's one answer) one_answer = {"sshd": "launchctl", "screensharing": "launchctl", "smbd": "launchctl", "networksharing": "launchctl", "format": "launchctl", "other-services": "launchctl"} for table, name in todo: s["touched"] |= {one_answer.get(k, k) for k in table[name][0]} for table, name in todo: _, exp, change = table[name] change(s, rng) expected += exp if name in BOUNDARY: boundary.add(name) commands = _commands(s, rng) fx.fakes["commands"] = [{"tool": tool, "args": args, "status": status, "output": out} for _, tool, args, status, out, _ in commands] fx.fakes["bootTime"] = iso(T0 - s["uptime"]) fx.fakes["pendingUpdates"] = s["pending"] fx.fakes["xprotectUpdated"] = iso(T0 - s["xprotect"]) lines = [f"现在是 {T0.astimezone(LOCAL):%Y-%m-%d %H:%M}(UTC+8)。下面是在这台 Mac 上运行几条系统命令得到的输出,和另外读到的三样。", ""] for typed, _, _, status, out, err in commands: lines.append("$ " + typed) if status == -1: lines.append("(没有答复:15 秒没跑完)") else: body = (out + err).rstrip("\n") if body: lines.append(body) if status != 0: lines.append(f"(退出码 {status}" + ("" if body else ",没有输出") + ")") lines.append("") lines += ["$ uptime", _uptime(s["uptime"]), "", f"等着安装的系统更新(软件更新的推荐列表):{s['pending']} 个", f"XProtect 特征库上次更新:{(T0 - s['xprotect']).astimezone(LOCAL):%Y-%m-%d %H:%M}"] return {"facts": "\n".join(lines) + "\n", "expected": expected, "boundary": boundary} def answer(fx, report: dict, made: dict) -> tuple: """(the rule's findings as the answer, the other rules that said something).""" out, others = [], set() for f in report.get("findings") or []: rule = f["rule"] if not rule.startswith("posture."): others.add(rule) continue out.append({"rule": rule, "kind": rule.split(".", 1)[1], "severity": f["severity"], "verdict": f["verdict"], "targets": [], "title": fx.shown(f.get("title", ""))}) return out, others