acrionix-cli 0.4.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.
acrionix/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Acrionix CLI - AOSP, Embedded Android & Linux Kernel log triage and patch synthesis."""
2
+
3
+ __version__ = "0.4.0"
acrionix/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from acrionix.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
acrionix/adb.py ADDED
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ import subprocess
5
+ from dataclasses import dataclass
6
+ from typing import Iterator
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class AdbDevice:
11
+ serial: str
12
+ state: str
13
+ model: str = ""
14
+ device: str = ""
15
+
16
+
17
+ class AdbError(RuntimeError):
18
+ pass
19
+
20
+
21
+ def build_adb_cmd(
22
+ args: list[str],
23
+ serial: str | None = None,
24
+ port: int | None = None,
25
+ ) -> list[str]:
26
+ adb_bin = shutil.which("adb")
27
+ if not adb_bin:
28
+ raise AdbError("adb binary not found on PATH. Install Android platform-tools.")
29
+ cmd = [adb_bin]
30
+ if port is not None:
31
+ cmd.extend(["-P", str(port)])
32
+ if serial:
33
+ cmd.extend(["-s", serial])
34
+ cmd.extend(args)
35
+ return cmd
36
+
37
+
38
+ def list_devices(port: int | None = None) -> list[AdbDevice]:
39
+ cmd = build_adb_cmd(["devices", "-l"], port=port)
40
+ proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
41
+ if proc.returncode != 0:
42
+ raise AdbError(proc.stderr.strip() or "Failed to query adb devices.")
43
+
44
+ devices: list[AdbDevice] = []
45
+ for line in proc.stdout.splitlines()[1:]:
46
+ line = line.strip()
47
+ if not line:
48
+ continue
49
+ parts = line.split()
50
+ if len(parts) < 2:
51
+ continue
52
+ serial, state = parts[0], parts[1]
53
+ model = ""
54
+ device = ""
55
+ for token in parts[2:]:
56
+ if token.startswith("model:"):
57
+ model = token.split(":", 1)[1]
58
+ elif token.startswith("device:"):
59
+ device = token.split(":", 1)[1]
60
+ devices.append(AdbDevice(serial=serial, state=state, model=model, device=device))
61
+ return devices
62
+
63
+
64
+ def pick_device(serial: str | None = None, port: int | None = None) -> tuple[str, int | None]:
65
+ devices = list_devices(port=port)
66
+ online = [d for d in devices if d.state == "device"]
67
+ if serial:
68
+ return (serial, port)
69
+ if online:
70
+ return (online[0].serial, port)
71
+ raise AdbError(
72
+ "No online ADB devices found. Check USB debugging or pass --port / --serial."
73
+ )
74
+
75
+
76
+ def run_shell(shell_cmd: str, serial: str, port: int | None = None, timeout: int = 15) -> str:
77
+ cmd = build_adb_cmd(["shell", shell_cmd], serial=serial, port=port)
78
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
79
+ return proc.stdout
80
+
81
+
82
+ def capture_snapshot(serial: str, port: int | None = None, root: bool = False) -> tuple[dict[str, str], list[str]]:
83
+ """Collect read-only device metadata + recent logcat, dmesg, and DSU status."""
84
+ prop_script = (
85
+ "echo model=$(getprop ro.product.model);"
86
+ "echo device=$(getprop ro.product.device);"
87
+ "echo android=$(getprop ro.build.version.release);"
88
+ "echo sdk=$(getprop ro.build.version.sdk);"
89
+ "echo display=$(getprop ro.build.display.id);"
90
+ "echo selinux=$(getenforce 2>/dev/null);"
91
+ "echo kernel=$(uname -r);"
92
+ "echo slot=$(getprop ro.boot.slot_suffix);"
93
+ "echo verity=$(getprop ro.boot.veritymode);"
94
+ )
95
+ raw_props = run_shell(prop_script, serial=serial, port=port)
96
+ props: dict[str, str] = {}
97
+ for line in raw_props.splitlines():
98
+ if "=" in line:
99
+ k, v = line.split("=", 1)
100
+ props[k.strip()] = v.strip()
101
+
102
+ lines: list[str] = []
103
+ logcat_out = run_shell("logcat -d -t 500 2>/dev/null", serial=serial, port=port, timeout=20)
104
+ lines.extend(logcat_out.splitlines())
105
+
106
+ if root:
107
+ dmesg_out = run_shell("su -c 'dmesg | tail -n 300' 2>/dev/null", serial=serial, port=port, timeout=20)
108
+ lines.extend(dmesg_out.splitlines())
109
+ last_kmsg = run_shell(
110
+ "su -c 'f=$(ls -t /data/system/dropbox/SYSTEM_LAST_KMSG*.gz 2>/dev/null | head -n 1); [ -n \"$f\" ] && zcat \"$f\" | tail -n 120' 2>/dev/null",
111
+ serial=serial,
112
+ port=port,
113
+ timeout=20,
114
+ )
115
+ lines.extend(last_kmsg.splitlines())
116
+ tombstone = run_shell(
117
+ "su -c 'f=$(ls -t /data/tombstones/tombstone_* 2>/dev/null | grep -v \"\\.pb$\" | head -n 1); [ -n \"$f\" ] && head -n 45 \"$f\"' 2>/dev/null",
118
+ serial=serial,
119
+ port=port,
120
+ timeout=20,
121
+ )
122
+ lines.extend(tombstone.splitlines())
123
+
124
+ return (props, lines)
125
+
126
+
127
+ def stream_logcat(serial: str, port: int | None = None) -> Iterator[str]:
128
+ cmd = build_adb_cmd(["logcat", "-v", "threadtime"], serial=serial, port=port)
129
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
130
+ assert proc.stdout is not None
131
+ try:
132
+ for line in proc.stdout:
133
+ yield line.rstrip("\n")
134
+ finally:
135
+ proc.terminate()
136
+ proc.wait(timeout=3)
acrionix/cli.py ADDED
@@ -0,0 +1,281 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ from acrionix import __version__
10
+ from acrionix.adb import AdbError, capture_snapshot, pick_device, stream_logcat
11
+ from acrionix.models import AnalysisReport
12
+ from acrionix.parsers import (
13
+ DeviceTreeIndex,
14
+ audit_sepolicy_dir,
15
+ parse_crashes,
16
+ parse_selinux_denials,
17
+ parse_vintf_mismatches,
18
+ )
19
+ from acrionix.patcher import format_patch_bundle, generate_patches
20
+
21
+ USE_COLOR = sys.stdout.isatty()
22
+
23
+
24
+ def _c(text: str, code: str) -> str:
25
+ if not USE_COLOR:
26
+ return text
27
+ return f"\033[{code}m{text}\033[0m"
28
+
29
+
30
+ def analyze_lines(lines: list[str], source: str, tree_root: Path | None = None) -> AnalysisReport:
31
+ tree = DeviceTreeIndex(tree_root)
32
+ findings = []
33
+ findings.extend(parse_selinux_denials(lines))
34
+ findings.extend(parse_vintf_mismatches(lines))
35
+ findings.extend(parse_crashes(lines))
36
+
37
+ patches = generate_patches(findings, tree)
38
+ warnings = [
39
+ f"{f.title}: {f.metadata['neverallow_warning']}"
40
+ for f in findings
41
+ if f.metadata.get("neverallow_warning")
42
+ ]
43
+ return AnalysisReport(
44
+ source=source,
45
+ lines_scanned=len(lines),
46
+ findings=findings,
47
+ patches=patches,
48
+ warnings=warnings,
49
+ )
50
+
51
+
52
+ def _print_report(report: AnalysisReport, elapsed_ms: int) -> None:
53
+ print(_c("Acrionix", "1;32") + f" v{__version__} - analyzed {report.lines_scanned} lines from {report.source} ({elapsed_ms}ms)")
54
+ print()
55
+
56
+ if not report.findings:
57
+ print(_c("No critical SELinux, VINTF, init, firmware, tombstone, or DSU failures detected.", "32"))
58
+ return
59
+
60
+ print(_c(f"Findings ({len(report.findings)}):", "1;36"))
61
+ for idx, f in enumerate(report.findings, 1):
62
+ sev_color = "31" if f.severity == "critical" else ("33" if f.severity == "high" else "36")
63
+ print(f" {idx}. [{_c(f.severity.upper(), sev_color)}] {f.title}")
64
+ print(f" {f.summary}")
65
+ print(f" target: {f.target_file} ({f.partition}, {int(f.confidence * 100)}% confidence)")
66
+ if f.security_note:
67
+ print(f" note: {_c(f.security_note, '32')}")
68
+ print()
69
+
70
+ if report.warnings:
71
+ print(_c("Neverallow / Safety Warnings:", "1;33"))
72
+ for w in report.warnings:
73
+ print(f" ! {w}")
74
+ print()
75
+
76
+ if report.patches:
77
+ print(_c(f"Synthesized Git Diffs ({len(report.patches)}):", "1;32"))
78
+ for p in report.patches:
79
+ print(_c(f"--- {p.file_path} (+{p.added} -{p.removed}) ---", "1"))
80
+ for line in p.unified_diff.splitlines():
81
+ if line.startswith("+") and not line.startswith("+++"):
82
+ print(_c(line, "32"))
83
+ elif line.startswith("-") and not line.startswith("---"):
84
+ print(_c(line, "31"))
85
+ elif line.startswith("@@"):
86
+ print(_c(line, "36"))
87
+ else:
88
+ print(line)
89
+ print()
90
+
91
+
92
+ def cmd_triage(args: argparse.Namespace) -> int:
93
+ start = time.monotonic()
94
+ if args.log == "-":
95
+ lines = sys.stdin.read().splitlines()
96
+ source = "stdin"
97
+ else:
98
+ log_path = Path(args.log)
99
+ if not log_path.exists():
100
+ print(f"error: log file not found: {log_path}", file=sys.stderr)
101
+ return 2
102
+ lines = log_path.read_text(encoding="utf-8", errors="ignore").splitlines()
103
+ source = str(log_path)
104
+
105
+ tree_root = Path(args.tree) if args.tree else None
106
+ report = analyze_lines(lines, source=source, tree_root=tree_root)
107
+ elapsed_ms = int((time.monotonic() - start) * 1000)
108
+
109
+ if args.out and report.patches:
110
+ out_path = Path(args.out)
111
+ out_path.parent.mkdir(parents=True, exist_ok=True)
112
+ out_path.write_text(format_patch_bundle(report.patches), encoding="utf-8")
113
+
114
+ if args.json:
115
+ print(json.dumps(report.to_dict(), indent=2))
116
+ else:
117
+ _print_report(report, elapsed_ms)
118
+ if args.out and report.patches:
119
+ print(_c(f"Wrote unified patch -> {args.out}", "1;32"))
120
+ print(f"Verify with: git apply --check {args.out}")
121
+ return 0
122
+
123
+
124
+ def cmd_sepolicy_audit(args: argparse.Namespace) -> int:
125
+ start = time.monotonic()
126
+ sepolicy_dir = Path(args.sepolicy_dir)
127
+ if not sepolicy_dir.exists():
128
+ print(f"error: directory not found: {sepolicy_dir}", file=sys.stderr)
129
+ return 2
130
+
131
+ findings = audit_sepolicy_dir(sepolicy_dir)
132
+ if args.log:
133
+ log_path = Path(args.log)
134
+ if log_path.exists():
135
+ log_lines = log_path.read_text(encoding="utf-8", errors="ignore").splitlines()
136
+ findings.extend(parse_selinux_denials(log_lines))
137
+
138
+ tree = DeviceTreeIndex(sepolicy_dir.parent if sepolicy_dir.name == "sepolicy" else sepolicy_dir)
139
+ patches = generate_patches(findings, tree)
140
+ report = AnalysisReport(
141
+ source=str(sepolicy_dir),
142
+ lines_scanned=len(findings),
143
+ findings=findings,
144
+ patches=patches,
145
+ )
146
+ elapsed_ms = int((time.monotonic() - start) * 1000)
147
+
148
+ if args.out and patches:
149
+ Path(args.out).write_text(format_patch_bundle(patches, "Enforce vendor sepolicy"), encoding="utf-8")
150
+
151
+ if args.json:
152
+ print(json.dumps(report.to_dict(), indent=2))
153
+ else:
154
+ _print_report(report, elapsed_ms)
155
+
156
+ if args.strict and any(f.metadata.get("remove_permissive") for f in findings):
157
+ return 1
158
+ return 0
159
+
160
+
161
+ def cmd_doctor(args: argparse.Namespace) -> int:
162
+ start = time.monotonic()
163
+ try:
164
+ serial, port = pick_device(serial=args.serial, port=args.port)
165
+ except AdbError as exc:
166
+ print(f"error: {exc}", file=sys.stderr)
167
+ return 2
168
+
169
+ props, lines = capture_snapshot(serial=serial, port=port, root=args.root)
170
+ tree_root = Path(args.tree) if args.tree else None
171
+ report = analyze_lines(lines, source=f"adb:{serial}", tree_root=tree_root)
172
+ elapsed_ms = int((time.monotonic() - start) * 1000)
173
+
174
+ if args.out and report.patches:
175
+ Path(args.out).write_text(format_patch_bundle(report.patches), encoding="utf-8")
176
+
177
+ if args.json:
178
+ out = report.to_dict()
179
+ out["device"] = {"serial": serial, "props": props}
180
+ print(json.dumps(out, indent=2))
181
+ else:
182
+ print(
183
+ _c("Device:", "1;36"),
184
+ f"{props.get('model', 'unknown')} ({props.get('device', '?')}) · "
185
+ f"Android {props.get('android', '?')} (SDK {props.get('sdk', '?')}) · "
186
+ f"Kernel {props.get('kernel', '?')} · SELinux {props.get('selinux', '?')}",
187
+ )
188
+ print()
189
+ _print_report(report, elapsed_ms)
190
+ if args.out and report.patches:
191
+ print(_c(f"Wrote unified patch -> {args.out}", "1;32"))
192
+ return 0
193
+
194
+
195
+ def cmd_watch(args: argparse.Namespace) -> int:
196
+ try:
197
+ serial, port = pick_device(serial=args.serial, port=args.port)
198
+ except AdbError as exc:
199
+ print(f"error: {exc}", file=sys.stderr)
200
+ return 2
201
+
202
+ tree = DeviceTreeIndex(Path(args.tree) if args.tree else None)
203
+ out_dir = Path(args.out_dir)
204
+ print(_c("Acrionix watch", "1;32") + f" streaming adb:{serial} (Ctrl+C to stop)")
205
+ seen_titles: set[str] = set()
206
+ captured_lines: list[str] = []
207
+
208
+ try:
209
+ for line in stream_logcat(serial=serial, port=port):
210
+ captured_lines.append(line)
211
+ if len(captured_lines) > 2000:
212
+ captured_lines = captured_lines[-1000:]
213
+ findings = parse_selinux_denials([line]) + parse_vintf_mismatches([line]) + parse_crashes([line])
214
+ for f in findings:
215
+ if f.title in seen_titles:
216
+ continue
217
+ seen_titles.add(f.title)
218
+ print(f"[{_c(f.category.upper(), '36')}] {f.title}")
219
+ print(f" -> {f.summary}")
220
+ patches = generate_patches([f], tree)
221
+ if patches:
222
+ out_dir.mkdir(parents=True, exist_ok=True)
223
+ slug = f.category + "-" + str(len(seen_titles)).zfill(3) + ".patch"
224
+ patch_file = out_dir / slug
225
+ patch_file.write_text(format_patch_bundle(patches, f.title), encoding="utf-8")
226
+ print(f" -> synthesized {_c(str(patch_file), '32')}")
227
+ except KeyboardInterrupt:
228
+ print("\nStopped watching.")
229
+ return 0
230
+
231
+
232
+ def build_parser() -> argparse.ArgumentParser:
233
+ parser = argparse.ArgumentParser(
234
+ prog="acrionix",
235
+ description="Acrionix CLI - AOSP, Embedded Android & Linux Kernel log triage and git patch synthesizer",
236
+ )
237
+ parser.add_argument("--version", action="version", version=f"acrionix-cli {__version__}")
238
+ sub = parser.add_subparsers(dest="command", required=True)
239
+
240
+ p_triage = sub.add_parser("triage", help="Analyze a log file (or stdin '-') and generate git patches")
241
+ p_triage.add_argument("log", help="Path to logcat/dmesg/tombstone file, or '-' for stdin")
242
+ p_triage.add_argument("--tree", help="Path to local AOSP device/vendor tree for exact file patching")
243
+ p_triage.add_argument("--out", help="Write synthesized unified .patch file to this path")
244
+ p_triage.add_argument("--json", action="store_true", help="Output structured JSON report")
245
+ p_triage.set_defaults(func=cmd_triage)
246
+
247
+ p_doc = sub.add_parser("doctor", help="Inspect a connected ADB device (props, denials, crashes, DSU)")
248
+ p_doc.add_argument("--adb", action="store_true", help="Connect over ADB (default)")
249
+ p_doc.add_argument("--serial", help="Target ADB device serial")
250
+ p_doc.add_argument("--port", type=int, help="Custom ADB server port (e.g. 5038)")
251
+ p_doc.add_argument("--root", action="store_true", help="Use su to also inspect dmesg, tombstones & last_kmsg")
252
+ p_doc.add_argument("--tree", help="Path to local AOSP device tree")
253
+ p_doc.add_argument("--out", help="Write synthesized unified .patch file")
254
+ p_doc.add_argument("--json", action="store_true", help="Output JSON")
255
+ p_doc.set_defaults(func=cmd_doctor)
256
+
257
+ p_watch = sub.add_parser("watch", help="Stream live ADB logcat and synthesize patches on the fly")
258
+ p_watch.add_argument("--adb", action="store_true", help="Stream over ADB")
259
+ p_watch.add_argument("--serial", help="Target ADB device serial")
260
+ p_watch.add_argument("--port", type=int, help="Custom ADB server port")
261
+ p_watch.add_argument("--tree", help="Path to local AOSP device tree")
262
+ p_watch.add_argument("--out-dir", default=".acrionix", help="Directory for generated .patch files")
263
+ p_watch.set_defaults(func=cmd_watch)
264
+
265
+ p_sep = sub.add_parser("sepolicy", help="SELinux policy auditing tools")
266
+ sep_sub = p_sep.add_subparsers(dest="sepolicy_cmd", required=True)
267
+ p_audit = sep_sub.add_parser("audit", help="Scan .te policies for permissive domains and synthesize strict rules")
268
+ p_audit.add_argument("sepolicy_dir", help="Path to vendor sepolicy directory")
269
+ p_audit.add_argument("--log", help="Optional runtime audit log to synthesize replacement allow rules")
270
+ p_audit.add_argument("--strict", action="store_true", help="Exit with code 1 if any permissive domain is found")
271
+ p_audit.add_argument("--out", help="Write cleanup .patch file")
272
+ p_audit.add_argument("--json", action="store_true", help="Output JSON")
273
+ p_audit.set_defaults(func=cmd_sepolicy_audit)
274
+
275
+ return parser
276
+
277
+
278
+ def main(argv: list[str] | None = None) -> int:
279
+ parser = build_parser()
280
+ args = parser.parse_args(argv)
281
+ return int(args.func(args))
acrionix/models.py ADDED
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field, asdict
4
+ from typing import Any
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Finding:
9
+ category: str # "selinux" | "vintf" | "init" | "firmware" | "tombstone" | "dsu"
10
+ severity: str # "critical" | "high" | "medium" | "low"
11
+ title: str
12
+ summary: str
13
+ partition: str
14
+ target_file: str
15
+ confidence: float
16
+ raw_lines: tuple[str, ...] = ()
17
+ metadata: dict[str, Any] = field(default_factory=dict)
18
+ security_note: str = ""
19
+
20
+ def to_dict(self) -> dict[str, Any]:
21
+ data = asdict(self)
22
+ data["raw_lines"] = list(self.raw_lines)
23
+ return data
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class PatchDiff:
28
+ file_path: str
29
+ unified_diff: str
30
+ added: int
31
+ removed: int
32
+ finding_category: str
33
+ description: str
34
+
35
+ def to_dict(self) -> dict[str, Any]:
36
+ return asdict(self)
37
+
38
+
39
+ @dataclass
40
+ class AnalysisReport:
41
+ source: str
42
+ lines_scanned: int
43
+ findings: list[Finding] = field(default_factory=list)
44
+ patches: list[PatchDiff] = field(default_factory=list)
45
+ warnings: list[str] = field(default_factory=list)
46
+
47
+ def to_dict(self) -> dict[str, Any]:
48
+ return {
49
+ "source": self.source,
50
+ "lines_scanned": self.lines_scanned,
51
+ "findings": [f.to_dict() for f in self.findings],
52
+ "patches": [p.to_dict() for p in self.patches],
53
+ "warnings": self.warnings,
54
+ }
@@ -0,0 +1,12 @@
1
+ from acrionix.parsers.selinux import parse_selinux_denials, audit_sepolicy_dir
2
+ from acrionix.parsers.vintf import parse_vintf_mismatches
3
+ from acrionix.parsers.crashes import parse_crashes
4
+ from acrionix.parsers.tree import DeviceTreeIndex
5
+
6
+ __all__ = [
7
+ "parse_selinux_denials",
8
+ "audit_sepolicy_dir",
9
+ "parse_vintf_mismatches",
10
+ "parse_crashes",
11
+ "DeviceTreeIndex",
12
+ ]