File size: 31,170 Bytes
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
"""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

@_plant("deleted-tool", ["deleted-binary"])
def _(s):
    s.add(s.tool(), s.shell(), s.minutes(30, 60 * 40), exists=False, args=["serve", "--config", "dev.toml"])


@_plant("deleted-app", ["deleted-binary"])
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)


@_plant("deleted-with-deleted-library", ["deleted-binary"])
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"])


@_plant("dyld-insert-adhoc", ["dyld-insert"])
def _(s): _dyld(s, s.rng.choice(["adhoc", "unsigned"]))


@_plant("dyld-insert-developer", ["dyld-insert"])
def _(s): _dyld(s, "developer:" + s.rng.choice(TEAMS))


@_plant("dyld-insert-missing", ["dyld-insert"])
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"])


@_plant("library-temp", ["library-temp"])
def _(s): _temp_lib(s, f"$TMPDIR/io.example.unpack-{_secret(s.rng, 6)}/libpayload.dylib", s.rng.choice(["adhoc", "unsigned"]))


@_plant("library-temp-broken-signature", ["library-temp"])
def _(s): _temp_lib(s, f"$TMPDIR/.{_secret(s.rng, 8)}/libhelper.dylib", "invalid")


@_plant("library-downloads", ["library-temp"])
def _(s): _temp_lib(s, "~/Downloads/plugin-pack/libplugin.dylib", s.rng.choice(["adhoc", "developer:" + s.rng.choice(TEAMS)]))


@_plant("library-deleted", ["library-deleted"])
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


@_plant("pile-up-20", ["pile-up"])
def _(s): _pile(s, 20)


@_plant("pile-up-many", ["pile-up"])
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)


@_plant("orphan", ["orphan"], alone={"no-launchctl"})
def _(s): _orphan(s, s.minutes(60 * 7, 60 * 24 * 12))


@_plant("orphans", ["orphan"], alone={"no-launchctl"})
def _(s):
    for _ in range(s.rng.randint(2, 3)):
        _orphan(s, s.minutes(60 * 7, 60 * 24 * 12))


@_plant("orphan-exactly-6-hours", ["orphan"], alone={"no-launchctl"})
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}])


@_plant("listening-everywhere", ["listening"])
def _(s): _listening(s, "0.0.0.0")


@_plant("listening-everywhere-v6", ["listening"])
def _(s): _listening(s, "::")


@_plant("listening-lan", ["listening"])
def _(s): _listening(s, f"192.168.{s.rng.randint(0, 20)}.{s.rng.randint(2, 250)}")


@_plant("secret-flag", ["argv-secret"])
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)


@_plant("secret-mysql", ["argv-secret"])
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)


@_plant("secret-curl", ["argv-secret"])
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)


@_plant("secret-url", ["argv-secret"])
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)


@_plant("secret-sk-key", ["argv-secret"])
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)


@_plant("no-launchctl", ["partial"])
def _(s): s.no_launchctl = True


# ---------------------------------------------------------------- only looks like something

@_near("pile-19")
def _(s): _pile(s, 19)


@_near("app-helpers-25")
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))


@_near("two-programs-12-each")
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)


@_near("orphan-5-hours-50")
def _(s): _orphan(s, datetime.timedelta(hours=5, minutes=s.rng.randint(40, 59)))


@_near("launchd-job")
def _(s):
    s.add(s.tool(), 1, s.minutes(60 * 8, 60 * 24 * 10), job=True, args=["agent", "--launchd"])


@_near("detached-on-purpose")
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)


@_near("app-service-under-launchd")
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))


@_near("listening-loopback")
def _(s): _listening(s, s.rng.choice(["127.0.0.1", "::1", "::ffff:127.0.0.1"]))


@_near("system-listening-everywhere")
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"}])


@_near("secret-kept-elsewhere")
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)


@_near("mysql-asks-for-password")
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"])


@_near("port-not-password")
def _(s):
    s.add("/usr/bin/ssh", s.shell(), s.minutes(2, 60 * 3), args=["ssh", "-p2222", "deploy@build.internal.example"])


@_near("url-without-password")
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"])


@_near("other-dyld-variable")
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"])


@_near("dyld-insert-system-library")
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"])


@_near("dyld-insert-apple-signed")
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"])


@_near("library-in-own-bundle")
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")])


@_near("apple-library-in-temp")
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")])


@_near("system-library-deleted")
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}


@_near("other-user-gone")
def _(s):
    s.add("/opt/harborline/bin/gatewayd", 1, s.session, uid=0, gone=True, args=["gatewayd", "--config", "/opt/harborline/etc/gateway.toml"])


@_near("other-user-listening")
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