secpol-audit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. secpol_audit/__init__.py +5 -0
  2. secpol_audit/__main__.py +8 -0
  3. secpol_audit/api_server.py +137 -0
  4. secpol_audit/assets/fallback_dashboard.html +42 -0
  5. secpol_audit/bench.py +741 -0
  6. secpol_audit/blast.py +1533 -0
  7. secpol_audit/blast_html.py +1186 -0
  8. secpol_audit/build_doctor/__init__.py +481 -0
  9. secpol_audit/checks.py +976 -0
  10. secpol_audit/cli.py +1004 -0
  11. secpol_audit/compile_wrap.py +137 -0
  12. secpol_audit/demo.py +416 -0
  13. secpol_audit/diff.py +352 -0
  14. secpol_audit/equiv.py +107 -0
  15. secpol_audit/events.py +920 -0
  16. secpol_audit/explain.py +442 -0
  17. secpol_audit/extras.py +19 -0
  18. secpol_audit/firmware.py +776 -0
  19. secpol_audit/graph_html.py +1372 -0
  20. secpol_audit/ipc/__init__.py +215 -0
  21. secpol_audit/ir.py +430 -0
  22. secpol_audit/mcp_server/__init__.py +411 -0
  23. secpol_audit/mcp_server/__main__.py +4 -0
  24. secpol_audit/mkifs_conformance.py +234 -0
  25. secpol_audit/oracle_diff.py +246 -0
  26. secpol_audit/parser_ifs.py +1185 -0
  27. secpol_audit/parser_secpol.py +1086 -0
  28. secpol_audit/paths.py +653 -0
  29. secpol_audit/perf/__init__.py +94 -0
  30. secpol_audit/provenance/__init__.py +480 -0
  31. secpol_audit/prune.py +282 -0
  32. secpol_audit/remediate.py +846 -0
  33. secpol_audit/replay/__init__.py +157 -0
  34. secpol_audit/runtime.py +408 -0
  35. secpol_audit/sarif.py +237 -0
  36. secpol_audit/service.py +393 -0
  37. secpol_audit/target/__init__.py +339 -0
  38. secpol_audit/trace.py +389 -0
  39. secpol_audit/tui/__init__.py +57 -0
  40. secpol_audit/tui/__main__.py +4 -0
  41. secpol_audit-1.0.0.dist-info/METADATA +100 -0
  42. secpol_audit-1.0.0.dist-info/RECORD +46 -0
  43. secpol_audit-1.0.0.dist-info/WHEEL +5 -0
  44. secpol_audit-1.0.0.dist-info/entry_points.txt +5 -0
  45. secpol_audit-1.0.0.dist-info/licenses/LICENSE +21 -0
  46. secpol_audit-1.0.0.dist-info/top_level.txt +1 -0
secpol_audit/bench.py ADDED
@@ -0,0 +1,741 @@
1
+ """Differential benchmark and fuzz harness for the static analyzer (host only).
2
+
3
+ This module answers a narrow, checkable question: *does the analyzer agree with
4
+ an independent implementation of the same semantics?* It does **not** touch a
5
+ QNX target and says nothing about runtime behaviour; the QEMU captures under
6
+ ``evidence/`` remain the only target evidence in this repository.
7
+
8
+ Design
9
+ ------
10
+ * A seeded generator builds random policies **from a ground-truth model**
11
+ (types, privilege tokens, ``settypeid`` / ``derive_type`` /
12
+ ``default_spawn_type`` edges, attribute-mediated edges, ``channel connect``
13
+ edges) and renders them as ``.secpol`` text.
14
+ * The *oracle* works on the model (never on ``secpol_audit`` code):
15
+ - escalating pairs by plain graph reachability,
16
+ - a brute-force minimum-weight edge cut (exhaustive over edge subsets),
17
+ - a regex-based reader for the rewritten policy, so the remediation result is
18
+ re-checked without trusting ``parser_secpol``.
19
+ * The tool is compared on: pair-level precision/recall, remediation soundness,
20
+ remediation optimality, collateral removals, preservation of unrelated rules,
21
+ determinism, and global-mode coverage.
22
+ * A mutation fuzzer feeds corrupted ``.secpol``/``.ifs`` text to the parsers,
23
+ analyzers and the CLI entry point and counts anything that is neither a clean
24
+ result nor a structured ``ParseDiagnostic`` (those are "unhandled").
25
+
26
+ The edge cost model is the one published in ``remediate.EDGE_KIND_WEIGHTS``;
27
+ the oracle re-implements the *solver*, not the cost table.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import contextlib
33
+ import io
34
+ import itertools
35
+ import json
36
+ import random
37
+ import re
38
+ import sys
39
+ import tempfile
40
+ import time
41
+ from dataclasses import dataclass, field
42
+ from pathlib import Path
43
+ from typing import Any, Iterable
44
+
45
+ from secpol_audit.ir import ParseDiagnostic
46
+ from secpol_audit.parser_ifs import parse_ifs_text
47
+ from secpol_audit.parser_secpol import parse_secpol_text
48
+ from secpol_audit.paths import analyze_paths
49
+ from secpol_audit.remediate import EDGE_KIND_WEIGHTS, remediate_policy_text
50
+
51
+ BENCH_SCHEMA = "secpol-audit.bench/1"
52
+
53
+ # Privilege tokens the generator can attach to a type. They map 1:1 onto the
54
+ # default sink definition documented in ``paths.DEFAULT_PRIVILEGED_ABILITIES``.
55
+ ABILITY_TOKENS = ("mem_phys", "prot_exec", "mac_policy", "pathspace", "io")
56
+ ATTACH_TOKEN = "attach:/dev/can_ctrl"
57
+ ALL_TOKENS = ABILITY_TOKENS + (ATTACH_TOKEN,)
58
+
59
+ MAX_TYPES = 7 # keeps every simple path <= 6 hops, i.e. inside the tool's depth bound
60
+ MAX_BRUTE_EDGES = 14
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Ground-truth model
65
+ # ---------------------------------------------------------------------------
66
+
67
+
68
+ @dataclass
69
+ class Model:
70
+ types: list[str]
71
+ privs: dict[str, set[str]]
72
+ settype: set[tuple[str, str]] = field(default_factory=set)
73
+ attr_members: dict[str, list[str]] = field(default_factory=dict)
74
+ attr_settype: list[tuple[str, str]] = field(default_factory=list) # (attribute, target)
75
+ dspawn: set[tuple[str, str]] = field(default_factory=set)
76
+ derive: set[tuple[str, str]] = field(default_factory=set)
77
+ channel: set[tuple[str, str]] = field(default_factory=set)
78
+
79
+ def edges(self) -> dict[tuple[str, str], tuple[set[str], list[bool]]]:
80
+ """pair -> (mechanisms, per-edge 'via attribute' flags)."""
81
+ out: dict[tuple[str, str], tuple[set[str], list[bool]]] = {}
82
+
83
+ def add(u: str, v: str, mech: str, via_attr: bool) -> None:
84
+ if u == v:
85
+ return
86
+ mechs, flags = out.setdefault((u, v), (set(), []))
87
+ mechs.add(mech)
88
+ flags.append(via_attr)
89
+
90
+ for u, v in self.settype:
91
+ add(u, v, "settypeid", False)
92
+ for attr, target in self.attr_settype:
93
+ for member in self.attr_members.get(attr, []):
94
+ add(member, target, "settypeid", True)
95
+ for u, v in self.dspawn:
96
+ add(u, v, "default_spawn_type", False)
97
+ settype_pairs = set(self.settype) | {
98
+ (m, t) for a, t in self.attr_settype for m in self.attr_members.get(a, [])
99
+ }
100
+ for u, v in self.derive:
101
+ if (u, v) in settype_pairs: # a derive_type without settypeid is dangling, not an edge
102
+ add(u, v, "derive_type", False)
103
+ return out
104
+
105
+
106
+ def pair_weight(mechs: set[str], flags: list[bool]) -> int:
107
+ base = sum(EDGE_KIND_WEIGHTS.get(m, 10) for m in sorted(mechs))
108
+ return base + (1 if flags and all(flags) else 0)
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # Oracle
113
+ # ---------------------------------------------------------------------------
114
+
115
+
116
+ def _reach(adj: dict[str, set[str]], start: str) -> set[str]:
117
+ seen = {start}
118
+ stack = [start]
119
+ while stack:
120
+ cur = stack.pop()
121
+ for nxt in adj.get(cur, ()):
122
+ if nxt not in seen:
123
+ seen.add(nxt)
124
+ stack.append(nxt)
125
+ return seen
126
+
127
+
128
+ def escalating_pairs(types: Iterable[str], privs: dict[str, set[str]], pairs: Iterable[tuple[str, str]]) -> set[tuple[str, str]]:
129
+ adj: dict[str, set[str]] = {}
130
+ for u, v in pairs:
131
+ adj.setdefault(u, set()).add(v)
132
+ out: set[tuple[str, str]] = set()
133
+ for u in types:
134
+ for s in _reach(adj, u) - {u}:
135
+ if privs.get(s, set()) - privs.get(u, set()):
136
+ out.add((u, s))
137
+ return out
138
+
139
+
140
+ def oracle_min_cut(model: Model, max_weight: int | None) -> tuple[int | None, list[tuple[str, str]]]:
141
+ """Exhaustive minimum-weight cut. Returns (weight, pairs) or (None, []) if skipped.
142
+
143
+ ``max_weight`` bounds the search (anything heavier cannot beat the tool).
144
+ """
145
+ edges = model.edges()
146
+ pairs = sorted(edges)
147
+ if len(pairs) > MAX_BRUTE_EDGES:
148
+ return None, []
149
+ weights = {p: pair_weight(*edges[p]) for p in pairs}
150
+ bound = max_weight if max_weight is not None else sum(weights.values())
151
+ min_edge = min(weights.values(), default=10)
152
+ kmax = min(len(pairs), bound // max(min_edge, 1))
153
+ best: tuple[int, tuple[tuple[str, str], ...]] | None = None
154
+ for k in range(0, kmax + 1):
155
+ for combo in itertools.combinations(pairs, k):
156
+ w = sum(weights[p] for p in combo)
157
+ if best is not None and w >= best[0]:
158
+ continue
159
+ if w > bound:
160
+ continue
161
+ remaining = [p for p in pairs if p not in combo]
162
+ if not escalating_pairs(model.types, model.privs, remaining):
163
+ best = (w, combo)
164
+ if best is None:
165
+ return None, []
166
+ return best[0], list(best[1])
167
+
168
+
169
+ # ---------------------------------------------------------------------------
170
+ # Generator + renderer
171
+ # ---------------------------------------------------------------------------
172
+
173
+
174
+ def generate_model(rng: random.Random, max_types: int = MAX_TYPES, *, chain: bool = False) -> Model:
175
+ if chain:
176
+ return _generate_chain_model(rng, max_types)
177
+ n = rng.randint(3, max_types)
178
+ types = [f"t{i}_t" for i in range(n)]
179
+ privs: dict[str, set[str]] = {t: set() for t in types}
180
+ for t in types:
181
+ if rng.random() < 0.45:
182
+ for tok in rng.sample(ALL_TOKENS, rng.randint(1, 3)):
183
+ privs[t].add(tok)
184
+ m = Model(types=types, privs=privs)
185
+ density = rng.choice((0.12, 0.18, 0.25))
186
+ for u in types:
187
+ for v in types:
188
+ if u == v or rng.random() > density:
189
+ continue
190
+ kind = rng.random()
191
+ if kind < 0.65:
192
+ m.settype.add((u, v))
193
+ elif kind < 0.85:
194
+ m.dspawn.add((u, v))
195
+ else:
196
+ m.settype.add((u, v))
197
+ m.derive.add((u, v))
198
+ if n >= 4 and rng.random() < 0.35:
199
+ members = rng.sample(types, rng.randint(2, min(3, n - 1)))
200
+ m.attr_members["grp0"] = sorted(members)
201
+ target = rng.choice([t for t in types if t not in members] or types)
202
+ m.attr_settype.append(("grp0", target))
203
+ for u in types:
204
+ for v in types:
205
+ if u != v and rng.random() < 0.15:
206
+ m.channel.add((u, v))
207
+ return m
208
+
209
+
210
+ def _generate_chain_model(rng: random.Random, max_types: int) -> Model:
211
+ """A long settypeid line ending in a privileged sink, plus sparse noise edges.
212
+
213
+ Deliberately exceeds the analyzer's display depth (6 hops) to prove that detection
214
+ does not silently truncate.
215
+ """
216
+ n = rng.randint(8, max(8, max_types))
217
+ names = [f"t{i}_t" for i in range(n)]
218
+ order = names[:]
219
+ rng.shuffle(order)
220
+ privs: dict[str, set[str]] = {t: set() for t in names}
221
+ privs[order[-1]] = set(rng.sample(ALL_TOKENS, rng.randint(1, 3)))
222
+ m = Model(types=names, privs=privs)
223
+ for a, b in zip(order, order[1:]):
224
+ m.settype.add((a, b))
225
+ for u in names:
226
+ for v in names:
227
+ if u != v and rng.random() < 0.03:
228
+ m.settype.add((u, v))
229
+ if u != v and rng.random() < 0.08:
230
+ m.channel.add((u, v))
231
+ return m
232
+
233
+
234
+ def render_secpol(m: Model, rng: random.Random | None = None) -> str:
235
+ rng = rng or random.Random(0)
236
+ lines = ["# generated by secpol_audit.bench (ground-truth model)"]
237
+ member_of: dict[str, list[str]] = {}
238
+ for attr, members in m.attr_members.items():
239
+ lines.append(f"attribute {attr};")
240
+ for mem in members:
241
+ member_of.setdefault(mem, []).append(attr)
242
+ for t in m.types:
243
+ attrs = "".join(f", {a}" for a in member_of.get(t, []))
244
+ lines.append(f"type {t}{attrs};")
245
+ lines.append("")
246
+ targets: dict[str, list[str]] = {}
247
+ for u, v in sorted(m.settype):
248
+ targets.setdefault(u, []).append(v)
249
+ for t in m.types:
250
+ want_nonroot = rng.random() < 0.5
251
+ body: list[str] = []
252
+ for tok in ABILITY_TOKENS:
253
+ if tok in m.privs[t]:
254
+ body.append(" mem_phys:0xfe000000-0xfe010000" if tok == "mem_phys" else f" {tok}")
255
+ tg = targets.get(t, [])
256
+ if tg:
257
+ if rng.random() < 0.5:
258
+ body.append(" settypeid:" + ",".join(tg))
259
+ else:
260
+ body.extend(f" settypeid:{x}" for x in tg)
261
+ if ATTACH_TOKEN in m.privs[t]:
262
+ lines.append(f"allow_attach {t} /dev/can_ctrl;")
263
+ if want_nonroot and body: # a bare modifier without an ability is invalid QNX policy
264
+ body.insert(0, " nonroot")
265
+ if body:
266
+ lines.append(f"allow {t} self:ability {{")
267
+ lines.extend(body)
268
+ lines.append("};")
269
+ for attr, target in m.attr_settype:
270
+ lines.append(f"allow {attr} self:ability {{\n settypeid:{target}\n}};")
271
+ for u, v in sorted(m.derive):
272
+ lines.append(f"derive_type {u} sub {v};")
273
+ for u, v in sorted(m.dspawn):
274
+ lines.append(f"default_spawn_type {u} {v};")
275
+ for u, v in sorted(m.channel):
276
+ lines.append(f"allow {u} {v} : channel connect;")
277
+ return "\n".join(lines) + "\n"
278
+
279
+
280
+ # ---------------------------------------------------------------------------
281
+ # Independent text reader (oracle side): rewritten policy -> edges, without parser_secpol
282
+ # ---------------------------------------------------------------------------
283
+
284
+ _BLOCK_RE = re.compile(
285
+ r"allow\s+([A-Za-z0-9_]+)\s+self\s*:\s*ability\s*(?:\{(.*?)\}|([^{};]+?))\s*;", re.S
286
+ )
287
+ _DERIVE_RE = re.compile(r"^\s*derive_type\s+(\w+)\s+\w+\s+(\w+)\s*;", re.M)
288
+ _DSPAWN_RE = re.compile(r"^\s*default_spawn_type\s+(\w+)\s+(\w+)\s*;", re.M)
289
+ _CHAN_RE = re.compile(r"^\s*allow\s+(\w+)\s+(\w+)\s*:\s*channel\s+connect\s*;", re.M)
290
+ _TYPE_RE = re.compile(r"^\s*type\s+(\w+)((?:\s*,\s*\w+)*)\s*;", re.M)
291
+ _ATTACH_RE = re.compile(r"^\s*allow_attach\s+(\w+)\s+(\S+)\s*;", re.M)
292
+
293
+
294
+ def read_model_from_text(text: str) -> Model:
295
+ clean = re.sub(r"#[^\n]*", "", text)
296
+ types: list[str] = []
297
+ attr_members: dict[str, list[str]] = {}
298
+ for mt in _TYPE_RE.finditer(clean):
299
+ types.append(mt.group(1))
300
+ for a in re.findall(r"\w+", mt.group(2)):
301
+ attr_members.setdefault(a, []).append(mt.group(1))
302
+ privs: dict[str, set[str]] = {t: set() for t in types}
303
+ m = Model(types=types, privs=privs, attr_members={a: sorted(v) for a, v in attr_members.items()})
304
+ for owner, braced, bare in _BLOCK_RE.findall(clean):
305
+ body = braced or bare # the rewriter emits the brace-less single-ability form
306
+ for tok in re.findall(r"[A-Za-z_][\w]*(?::[^\s]+)?", body):
307
+ name, _, arg = tok.partition(":")
308
+ if name in ABILITY_TOKENS and owner in privs:
309
+ privs[owner].add(name)
310
+ elif name == "settypeid":
311
+ for tgt in filter(None, arg.split(",")):
312
+ if owner in privs:
313
+ m.settype.add((owner, tgt))
314
+ else: # an attribute subject
315
+ m.attr_settype.append((owner, tgt))
316
+ for t, path in _ATTACH_RE.findall(clean):
317
+ if path == "/dev/can_ctrl" and t in privs:
318
+ privs[t].add(ATTACH_TOKEN)
319
+ m.derive = {(a, b) for a, b in _DERIVE_RE.findall(clean)}
320
+ m.dspawn = {(a, b) for a, b in _DSPAWN_RE.findall(clean)}
321
+ m.channel = {(a, b) for a, b in _CHAN_RE.findall(clean)}
322
+ return m
323
+
324
+
325
+ # ---------------------------------------------------------------------------
326
+ # Tool-side adapters
327
+ # ---------------------------------------------------------------------------
328
+
329
+
330
+ def tool_pairs(text: str) -> tuple[set[tuple[str, str]], list[list[str]]]:
331
+ policy = parse_secpol_text(text, "<bench>")
332
+ per_source: set[tuple[str, str]] = set()
333
+ for src in sorted(policy.types):
334
+ res = analyze_paths(policy, from_type=src)
335
+ per_source |= {(p.source, p.sink) for p in res.escalation_paths}
336
+ glob = analyze_paths(policy)
337
+ chains = [list(p.nodes) for p in glob.escalation_paths]
338
+ return per_source, chains
339
+
340
+
341
+ def _covered(pair: tuple[str, str], chains: list[list[str]]) -> bool:
342
+ u, s = pair
343
+ for ch in chains:
344
+ if u in ch and s in ch and ch.index(u) < ch.index(s):
345
+ return True
346
+ return False
347
+
348
+
349
+ # ---------------------------------------------------------------------------
350
+ # Case evaluation
351
+ # ---------------------------------------------------------------------------
352
+
353
+
354
+ @dataclass
355
+ class CaseResult:
356
+ seed: int
357
+ n_types: int
358
+ n_pair_edges: int
359
+ oracle_pairs: int
360
+ tp: int
361
+ fp: int
362
+ fn: int
363
+ uncovered_in_global: int
364
+ remediated: bool
365
+ sound: bool | None
366
+ preserved: bool | None
367
+ collateral_pairs: int | None
368
+ tool_weight: int | None
369
+ optimal_weight: int | None
370
+ optimal: bool | None
371
+ deterministic: bool
372
+ detail: dict[str, Any] = field(default_factory=dict)
373
+
374
+
375
+ def shortest_hops(model: Model, pairs: Iterable[tuple[str, str]]) -> int:
376
+ adj: dict[str, set[str]] = {}
377
+ for u, v in model.edges():
378
+ adj.setdefault(u, set()).add(v)
379
+ deepest = 0
380
+ for u, s in pairs:
381
+ dist = {u: 0}
382
+ frontier = [u]
383
+ while frontier and s not in dist:
384
+ nxt = []
385
+ for cur in frontier:
386
+ for w in adj.get(cur, ()):
387
+ if w not in dist:
388
+ dist[w] = dist[cur] + 1
389
+ nxt.append(w)
390
+ frontier = nxt
391
+ deepest = max(deepest, dist.get(s, 0))
392
+ return deepest
393
+
394
+
395
+ def evaluate_case(seed: int, *, brute_force: bool = True, max_types: int = MAX_TYPES, chain: bool = False) -> CaseResult:
396
+ rng = random.Random(seed)
397
+ model = generate_model(rng, max_types, chain=chain)
398
+ text = render_secpol(model, rng)
399
+ edges = model.edges()
400
+ truth = escalating_pairs(model.types, model.privs, edges)
401
+ got, chains = tool_pairs(text)
402
+ tp, fp, fn = len(truth & got), len(got - truth), len(truth - got)
403
+ uncovered = sum(1 for p in truth if not _covered(p, chains))
404
+ detail: dict[str, Any] = {"deepest_required_hops": shortest_hops(model, truth)}
405
+ if fp:
406
+ detail["false_positives"] = sorted(got - truth)
407
+ if fn:
408
+ detail["false_negatives"] = sorted(truth - got)
409
+
410
+ # determinism
411
+ r1 = remediate_policy_text(text, "<bench>")
412
+ r2 = remediate_policy_text(text, "<bench>")
413
+ deterministic = json.dumps(r1.to_dict(), sort_keys=True) == json.dumps(r2.to_dict(), sort_keys=True) and r1.fixed_text == r2.fixed_text
414
+
415
+ sound = preserved = optimal = None
416
+ collateral = tool_w = opt_w = None
417
+ remediated = bool(truth)
418
+ if truth:
419
+ after = read_model_from_text(r1.fixed_text)
420
+ after_edges = after.edges()
421
+ remaining = escalating_pairs(after.types, after.privs, after_edges)
422
+ sound = not remaining
423
+ if remaining:
424
+ detail["remaining_after_fix"] = sorted(remaining)
425
+ preserved = (
426
+ after.channel == model.channel
427
+ and set(after.types) == set(model.types)
428
+ and after.privs == model.privs
429
+ )
430
+ if not preserved:
431
+ detail["preservation_diff"] = {
432
+ "channel_lost": sorted(model.channel - after.channel),
433
+ "channel_added": sorted(after.channel - model.channel),
434
+ "priv_changed": sorted(t for t in model.types if after.privs.get(t) != model.privs[t]),
435
+ }
436
+ cut = {(c.source, c.target) for c in r1.cut_edges}
437
+ removed = set(edges) - set(after_edges)
438
+ collateral = len(removed - cut)
439
+ if collateral:
440
+ detail["collateral"] = sorted(removed - cut)
441
+ tool_w = int(r1.total_cut_weight)
442
+ if brute_force:
443
+ opt_w, opt_set = oracle_min_cut(model, tool_w)
444
+ if opt_w is not None:
445
+ optimal = tool_w <= opt_w
446
+ if not optimal:
447
+ detail["optimal_cut"] = opt_set
448
+ detail["tool_cut"] = sorted(cut)
449
+ elif len(edges) <= MAX_BRUTE_EDGES:
450
+ # no valid cut at or below the tool's weight was found by the oracle
451
+ opt_w, optimal = None, None
452
+ return CaseResult(
453
+ seed=seed,
454
+ n_types=len(model.types),
455
+ n_pair_edges=len(edges),
456
+ oracle_pairs=len(truth),
457
+ tp=tp,
458
+ fp=fp,
459
+ fn=fn,
460
+ uncovered_in_global=uncovered,
461
+ remediated=remediated,
462
+ sound=sound,
463
+ preserved=preserved,
464
+ collateral_pairs=collateral,
465
+ tool_weight=tool_w,
466
+ optimal_weight=opt_w,
467
+ optimal=optimal,
468
+ deterministic=deterministic,
469
+ detail=detail,
470
+ )
471
+
472
+
473
+ # ---------------------------------------------------------------------------
474
+ # Fuzzer
475
+ # ---------------------------------------------------------------------------
476
+
477
+ _VOCAB = [
478
+ "{", "}", ";", ":", ",", "settypeid:", "allow", "type", "attribute", "self", "ability", "include ",
479
+ "derive_type", "default_spawn_type", "gain_priv:", "\x00", "\ufffd", "\u202e", "/dev/", "#", "\\",
480
+ "\"", "'", "*", "A" * 4096, "0x", "-", "mount_point", "range", "channel connect",
481
+ ]
482
+
483
+
484
+ def mutate(text: str, rng: random.Random) -> str:
485
+ if not text:
486
+ return rng.choice(_VOCAB)
487
+ s = text
488
+ for _ in range(rng.randint(1, 4)):
489
+ op = rng.randrange(8)
490
+ if op == 0 and len(s) > 2: # delete span
491
+ a = rng.randrange(len(s)); b = min(len(s), a + rng.randint(1, 40)); s = s[:a] + s[b:]
492
+ elif op == 1: # insert vocab
493
+ a = rng.randrange(len(s) + 1); s = s[:a] + rng.choice(_VOCAB) + s[a:]
494
+ elif op == 2: # truncate
495
+ s = s[: rng.randrange(len(s) + 1)]
496
+ elif op == 3: # duplicate a line
497
+ ls = s.splitlines(keepends=True)
498
+ if ls:
499
+ i = rng.randrange(len(ls)); ls.insert(i, ls[i]); s = "".join(ls)
500
+ elif op == 4: # swap two lines
501
+ ls = s.splitlines(keepends=True)
502
+ if len(ls) > 1:
503
+ i, j = rng.sample(range(len(ls)), 2); ls[i], ls[j] = ls[j], ls[i]; s = "".join(ls)
504
+ elif op == 5: # flip a char
505
+ a = rng.randrange(len(s)); s = s[:a] + chr(rng.randrange(32, 0x250)) + s[a + 1 :]
506
+ elif op == 6: # replace identifier
507
+ ids = re.findall(r"[A-Za-z_]\w*", s)
508
+ if ids:
509
+ old = rng.choice(ids); s = s.replace(old, rng.choice(ids + ["self", "default"]), 1)
510
+ else: # nested braces
511
+ a = rng.randrange(len(s) + 1); s = s[:a] + "{" * rng.randint(1, 200) + s[a:]
512
+ return s
513
+
514
+
515
+ @dataclass
516
+ class FuzzOutcome:
517
+ accepted: int = 0
518
+ diagnostics: int = 0
519
+ unhandled: list[dict[str, str]] = field(default_factory=list)
520
+ slowest_s: float = 0.0
521
+ total: int = 0
522
+
523
+ def to_dict(self) -> dict[str, Any]:
524
+ return {
525
+ "total": self.total,
526
+ "accepted": self.accepted,
527
+ "structured_diagnostic": self.diagnostics,
528
+ "unhandled": len(self.unhandled),
529
+ "unhandled_samples": self.unhandled[:5],
530
+ "slowest_case_seconds": round(self.slowest_s, 4),
531
+ }
532
+
533
+
534
+ def _fuzz_one(kind: str, text: str, out: FuzzOutcome) -> None:
535
+ t0 = time.perf_counter()
536
+ out.total += 1
537
+ try:
538
+ if kind == "secpol":
539
+ pol = parse_secpol_text(text, "<fuzz>")
540
+ analyze_paths(pol)
541
+ remediate_policy_text(text, "<fuzz>")
542
+ else:
543
+ parse_ifs_text(text, "<fuzz>")
544
+ out.accepted += 1
545
+ except ParseDiagnostic:
546
+ out.diagnostics += 1
547
+ except RecursionError as exc: # unbounded nesting must be a diagnostic, not a crash
548
+ out.unhandled.append({"kind": kind, "exc": "RecursionError", "msg": str(exc)[:120], "input": text[:160]})
549
+ except Exception as exc: # noqa: BLE001 - the whole point is to catch everything
550
+ out.unhandled.append({"kind": kind, "exc": type(exc).__name__, "msg": str(exc)[:120], "input": text[:160]})
551
+ out.slowest_s = max(out.slowest_s, time.perf_counter() - t0)
552
+
553
+
554
+ def _fuzz_cli_one(argv_builder: Any, text: str, out: FuzzOutcome) -> None:
555
+ """Drive the real CLI entry point; exit code must be 0, 1 or 2 and never an exception."""
556
+ from secpol_audit import cli
557
+
558
+ out.total += 1
559
+ t0 = time.perf_counter()
560
+ with tempfile.TemporaryDirectory() as d:
561
+ p = Path(d) / "fuzz.secpol"
562
+ p.write_bytes(text.encode("utf-8", "surrogatepass") if text else b"")
563
+ try:
564
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
565
+ code = cli.main(argv_builder(str(p)))
566
+ if code in (0, 1, 2):
567
+ out.accepted += 1 if code in (0, 1) else 0
568
+ out.diagnostics += 1 if code == 2 else 0
569
+ else:
570
+ out.unhandled.append({"kind": "cli", "exc": "BadExitCode", "msg": str(code), "input": text[:160]})
571
+ except SystemExit as exc:
572
+ out.diagnostics += 1 if exc.code == 2 else 0
573
+ if exc.code not in (0, 1, 2):
574
+ out.unhandled.append({"kind": "cli", "exc": "SystemExit", "msg": str(exc.code), "input": text[:160]})
575
+ except BaseException as exc: # noqa: BLE001
576
+ out.unhandled.append({"kind": "cli", "exc": type(exc).__name__, "msg": str(exc)[:120], "input": text[:160]})
577
+ out.slowest_s = max(out.slowest_s, time.perf_counter() - t0)
578
+
579
+
580
+ def run_fuzz(seed: int, rounds: int, corpus_secpol: list[str], corpus_ifs: list[str], *, cli_rounds: int = 0) -> dict[str, Any]:
581
+ rng = random.Random(seed ^ 0x5EC9017)
582
+ sp, ifs, cl = FuzzOutcome(), FuzzOutcome(), FuzzOutcome()
583
+ for i in range(rounds):
584
+ if corpus_secpol:
585
+ _fuzz_one("secpol", mutate(rng.choice(corpus_secpol), rng), sp)
586
+ if corpus_ifs:
587
+ _fuzz_one("ifs", mutate(rng.choice(corpus_ifs), rng), ifs)
588
+ for i in range(cli_rounds):
589
+ if corpus_secpol:
590
+ txt = mutate(rng.choice(corpus_secpol), rng)
591
+ cmd = ("check", "paths", "fix")[i % 3]
592
+ _fuzz_cli_one(lambda p, c=cmd: [c, p] + (["--no-secpolcompile"] if c == "check" else []), txt, cl)
593
+ return {"secpol": sp.to_dict(), "ifs": ifs.to_dict(), "cli": cl.to_dict()}
594
+
595
+
596
+ # ---------------------------------------------------------------------------
597
+ # Driver
598
+ # ---------------------------------------------------------------------------
599
+
600
+
601
+ def run_benchmark(
602
+ *,
603
+ seed: int = 1,
604
+ cases: int = 300,
605
+ fuzz_rounds: int = 1500,
606
+ cli_rounds: int = 150,
607
+ corpus_dir: Path | None = None,
608
+ brute_force: bool = True,
609
+ ) -> dict[str, Any]:
610
+ t0 = time.perf_counter()
611
+ results = [evaluate_case(seed * 1_000_003 + i, brute_force=brute_force) for i in range(cases)]
612
+ stress_cases = max(10, cases // 10)
613
+ stress = [
614
+ evaluate_case(seed * 7_000_001 + i, brute_force=False, max_types=13, chain=True)
615
+ for i in range(stress_cases)
616
+ ]
617
+ results = results + stress
618
+ tp = sum(r.tp for r in results); fp = sum(r.fp for r in results); fn = sum(r.fn for r in results)
619
+ rem = [r for r in results if r.remediated]
620
+ sound = [r for r in rem if r.sound is not None]
621
+ pres = [r for r in rem if r.preserved is not None]
622
+ opt = [r for r in rem if r.optimal is not None]
623
+ subopt = [r for r in opt if not r.optimal]
624
+ gaps = [r.tool_weight - r.optimal_weight for r in subopt if r.tool_weight is not None and r.optimal_weight is not None]
625
+
626
+ secpol_corpus: list[str] = [render_secpol(generate_model(random.Random(seed + k))) for k in range(8)]
627
+ ifs_corpus: list[str] = []
628
+ if corpus_dir is not None and corpus_dir.exists():
629
+ secpol_corpus += [p.read_text(errors="replace") for p in sorted(corpus_dir.rglob("*.secpol"))][:40]
630
+ ifs_corpus += [p.read_text(errors="replace") for p in sorted(corpus_dir.rglob("*.ifs*"))][:40]
631
+ ifs_corpus += [p.read_text(errors="replace") for p in sorted(corpus_dir.rglob("*.build"))][:20]
632
+ fuzz = run_fuzz(seed, fuzz_rounds, secpol_corpus, ifs_corpus, cli_rounds=cli_rounds)
633
+
634
+ failures = [
635
+ {"seed": r.seed, **r.detail} for r in results
636
+ if r.fp or r.fn or r.sound is False or r.preserved is False or not r.deterministic
637
+ ]
638
+ report: dict[str, Any] = {
639
+ "schema": BENCH_SCHEMA,
640
+ "scope": "host-side differential test against an independent oracle; no QNX target involved",
641
+ "seed": seed,
642
+ "cases": cases,
643
+ "deep_chain_stress_cases": stress_cases,
644
+ "deepest_required_hops": max((r.detail.get("deepest_required_hops", 0) for r in results), default=0),
645
+ "elapsed_seconds": round(time.perf_counter() - t0, 2),
646
+ "detection": {
647
+ "oracle_escalating_pairs": sum(r.oracle_pairs for r in results),
648
+ "true_positive": tp, "false_positive": fp, "false_negative": fn,
649
+ "precision": round(tp / (tp + fp), 6) if tp + fp else 1.0,
650
+ "recall": round(tp / (tp + fn), 6) if tp + fn else 1.0,
651
+ "global_mode_uncovered_pairs": sum(r.uncovered_in_global for r in results),
652
+ },
653
+ "remediation": {
654
+ "policies_with_escalation": len(rem),
655
+ "sound_after_rewrite": sum(1 for r in sound if r.sound),
656
+ "unsound": sum(1 for r in sound if r.sound is False),
657
+ "unrelated_rules_preserved": sum(1 for r in pres if r.preserved),
658
+ "preservation_violations": sum(1 for r in pres if r.preserved is False),
659
+ "policies_with_collateral_removal": sum(1 for r in rem if r.collateral_pairs),
660
+ "collateral_pairs_total": sum(r.collateral_pairs or 0 for r in rem),
661
+ "optimality_checked": len(opt),
662
+ "optimal": sum(1 for r in opt if r.optimal),
663
+ "suboptimal": len(subopt),
664
+ "max_weight_gap": max(gaps) if gaps else 0,
665
+ "suboptimal_seeds": [r.seed for r in subopt][:20],
666
+ },
667
+ "determinism": {"nondeterministic": sum(1 for r in results if not r.deterministic)},
668
+ "fuzz": fuzz,
669
+ "failures": failures[:25],
670
+ "verdict": "PASS" if not failures and all(v["unhandled"] == 0 for v in fuzz.values()) else "FAIL",
671
+ "limits": [
672
+ "Generated policies use the documented dialect subset; real policies may use constructs the generator never emits.",
673
+ "The oracle shares the published edge-cost table (remediate.EDGE_KIND_WEIGHTS) but not the solver or the parser.",
674
+ "Optimality is verified exhaustively only for policies with <= 14 distinct escalation pair-edges.",
675
+ "Agreement with the oracle is evidence of internal consistency, not of agreement with QNX; target behaviour is established only by evidence/.",
676
+ ],
677
+ }
678
+ return report
679
+
680
+
681
+ def format_report(rep: dict[str, Any]) -> str:
682
+ d, r, f = rep["detection"], rep["remediation"], rep["fuzz"]
683
+ lines = [
684
+ f"secpol-audit bench seed={rep['seed']} cases={rep['cases']}+{rep['deep_chain_stress_cases']} deep-chain "
685
+ f"(deepest required chain: {rep['deepest_required_hops']} hops; {rep['elapsed_seconds']}s)",
686
+ "",
687
+ f"detection precision={d['precision']:.4f} recall={d['recall']:.4f} "
688
+ f"(TP={d['true_positive']} FP={d['false_positive']} FN={d['false_negative']}; pairs={d['oracle_escalating_pairs']})",
689
+ f"remediation sound={r['sound_after_rewrite']}/{r['policies_with_escalation']} "
690
+ f"preserved={r['unrelated_rules_preserved']}/{r['policies_with_escalation']} "
691
+ f"collateral={r['policies_with_collateral_removal']}",
692
+ f"optimality optimal={r['optimal']}/{r['optimality_checked']} suboptimal={r['suboptimal']} max_gap={r['max_weight_gap']}",
693
+ f"determinism nondeterministic={rep['determinism']['nondeterministic']}",
694
+ f"fuzz.secpol {f['secpol']['total']} inputs: accepted={f['secpol']['accepted']} diag={f['secpol']['structured_diagnostic']} UNHANDLED={f['secpol']['unhandled']}",
695
+ f"fuzz.ifs {f['ifs']['total']} inputs: accepted={f['ifs']['accepted']} diag={f['ifs']['structured_diagnostic']} UNHANDLED={f['ifs']['unhandled']}",
696
+ f"fuzz.cli {f['cli']['total']} runs: ok={f['cli']['accepted']} exit2={f['cli']['structured_diagnostic']} UNHANDLED={f['cli']['unhandled']}",
697
+ "",
698
+ f"VERDICT: {rep['verdict']}",
699
+ "Scope: host-side oracle comparison only; see docs/BENCHMARK.md for limits.",
700
+ ]
701
+ return "\n".join(lines) + "\n"
702
+
703
+
704
+ # ---------------------------------------------------------------------------
705
+ # CLI
706
+ # ---------------------------------------------------------------------------
707
+
708
+
709
+ def register(sub: Any) -> None:
710
+ p = sub.add_parser(
711
+ "bench",
712
+ help="Differential benchmark + fuzz: compare the analyzer with an independent oracle (host only)",
713
+ )
714
+ p.add_argument("--seed", type=int, default=1, help="Master seed (reports are reproducible)")
715
+ p.add_argument("--cases", type=int, default=300, help="Random policies to generate")
716
+ p.add_argument("--fuzz-rounds", type=int, default=1500, help="Mutated parser inputs per language")
717
+ p.add_argument("--cli-rounds", type=int, default=150, help="Mutated inputs driven through the real CLI")
718
+ p.add_argument("--corpus-dir", help="Seed corpus for the fuzzer (default: ./examples if present)")
719
+ p.add_argument("--no-brute-force", action="store_true", help="Skip exhaustive min-cut optimality check")
720
+ p.add_argument("--format", choices=("text", "json"), default="text")
721
+ p.add_argument("--output", "-o", help="Write the report to a file instead of stdout")
722
+ p.set_defaults(func=_cmd_bench)
723
+
724
+
725
+ def _cmd_bench(args: Any) -> int:
726
+ corpus = Path(args.corpus_dir) if args.corpus_dir else Path("examples")
727
+ rep = run_benchmark(
728
+ seed=args.seed,
729
+ cases=args.cases,
730
+ fuzz_rounds=args.fuzz_rounds,
731
+ cli_rounds=args.cli_rounds,
732
+ corpus_dir=corpus if corpus.exists() else None,
733
+ brute_force=not args.no_brute_force,
734
+ )
735
+ out = json.dumps(rep, indent=2, sort_keys=True) + "\n" if args.format == "json" else format_report(rep)
736
+ if args.output:
737
+ Path(args.output).parent.mkdir(parents=True, exist_ok=True)
738
+ Path(args.output).write_text(out, encoding="utf-8")
739
+ else:
740
+ sys.stdout.write(out)
741
+ return 0 if rep["verdict"] == "PASS" else 1