Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: an audit for voice, ACR and telemetry, with the evidence (#444)

xbshengfef5edb234e3
diff --git a/PROMPT.md b/PROMPT.md
index 9b192574b..211eb839b 100644
--- a/PROMPT.md
+++ b/PROMPT.md
@@ -60,6 +60,11 @@ Debloat
still unclear.
- Before touching streaming apps, voice assistant, Chromecast, Miracast or the update service, ask me
which ones I use with a checklist question and disable only what I don't tick.
+- When I ask whether the TV is listening, run `tools/privacy.py` (it needs the venv, like the other
+ Python tools) and report what it found: the packages, what each one does, and whether `appops`
+ shows the microphone was used. Never say a package records or listens — the audit shows what the
+ firmware and the packages declare, and on many sets the microphone is in the remote. `--write`
+ gives me a list `tools/disable.sh` and `tools/restore.sh` already handle.
- Run `pm` commands one per shell call, chained commands may silently stop after the first.
- If `pm disable-user` is refused for every package, stop and tell me: some firmware (Fire OS 5 on a
Fire TV Box, for one) refuses `pm disable-user` with a `SecurityException`, `pm uninstall --user 0`
diff --git a/README.md b/README.md
index 8b6bd4dca..443e8d499 100644
--- a/README.md
+++ b/README.md
@@ -291,6 +291,7 @@ tools/theme.sh themes/aurora # push a theme; --r
| [`tools/disable.sh`](tools/disable.sh), [`restore.sh`](tools/restore.sh) | Apply or undo a debloat list, the undo from the state recorded before the change. |
| [`tools/recovery.py`](tools/recovery.py) | Writes the record `disable.sh` needs to undo itself, and prints the restore batch. |
| [`tools/check.py`](tools/check.py) | Compares the TV with the list that was applied, for what a firmware update undid; `--fix` puts it back. |
+| [`tools/privacy.py`](tools/privacy.py) | Audits the TV for voice, ACR and telemetry candidates and prints the evidence for each; `--write` turns the findings into a list `disable.sh` and `restore.sh` already understand. |
| [`tools/theme.sh`](tools/theme.sh) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. |
| [`tools/race_calendar.py`](tools/race_calendar.py) | Writes this season's F1 calendar into a theme for race-weekend mode, from the free Jolpica API. |
| [`launcher/build-and-install.sh`](launcher/build-and-install.sh) | Builds a shrunk release (about 429 KB), installs it, switches Home, and rolls back if Home does not land on it. |
@@ -317,6 +318,32 @@ why, and disables the rest of the list. So a list applied before the launcher ha
the TV with nothing to start. Run the same list again once `launcher/build-and-install.sh` has made
the new launcher Home and the entry is applied; `FORCE_HOME=1` (`$env:FORCE_HOME`) disables it anyway.
+## The microphone, and what can be said about it
+
+"Which of these packages is listening?" has no honest one-line answer, and a permission scan makes
+it worse: on many sets most packages run as `android.uid.system`, so fifty of them show
+`RECORD_AUDIO: granted=true` and none of them record anything. On others the microphone is in the
+remote, not the panel, and a package with no audio permission at all still sees everything on screen
+— ACR clients such as `tv.inscape.tvclient.inscapeacr` identify content from the picture and need
+only `INTERNET`.
+
+`tools/privacy.py` reports what the TV actually says instead of guessing:
+`TV_HOST=192.168.1.50 tools/venv/bin/python -I tools/privacy.py` prints voice, ACR and telemetry
+candidates in three groups, each with its evidence — named by the firmware's own
+`voice_interaction_service`, a known component from [`examples/`](examples/), or nothing but a
+matching name — plus whether the package declares `RECORD_AUDIO`, whether it shares the system UID,
+and whether `appops` shows the microphone op was ever used since boot.
+
+`--write privacy.txt` turns the identified candidates into a normal debloat list, so applying it and
+undoing it are the commands you already use (`tools/disable.sh`, `tools/restore.sh`). Packages that
+only matched by name stay out unless you pass `--include-low`; they are the ones to check with
+`dumpsys package <name>` first.
+
+What the audit cannot do is prove intent. `appops` shows an op was touched, not what happened to the
+stream afterwards, and no scan of package names proves a TV is or is not recording. Disabling an
+assistant is a trade you make with a specific loss (the remote's mic button, voice search inside
+apps), which is why the report names that loss per package instead of calling it a win.
+
## The launcher
A small native Android TV app (`com.gathin.tvhome`, about 429 KB installed) in plain Java with
diff --git a/tests/test_privacy_audit.py b/tests/test_privacy_audit.py
new file mode 100644
index 000000000..ecb03f6c5
--- /dev/null
+++ b/tests/test_privacy_audit.py
@@ -0,0 +1,297 @@
+"""tools/privacy.py against a simulated TV (#444).
+
+The point of the audit is what it refuses to claim, and no TV reproduces that on demand: on firmware
+where most packages share android.uid.system, a permission scan flags fifty packages that record
+nothing. tools/tv.py is replaced by a fake that answers from a JSON file, so the real audit logic
+runs and only the ADB transport is simulated.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+"""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+FAKE_TV = r'''
+import json
+import os
+import sys
+
+STATE_PATH = os.environ["FAKE_TV_STATE"]
+
+
+def load():
+ with open(STATE_PATH) as f:
+ return json.load(f)
+
+
+state = load()
+
+
+def answer(command):
+ if command == "pm list packages":
+ return "".join(f"package:{name}\n" for name in state["installed"])
+ if command == "pm list packages -d":
+ return "".join(f"package:{name}\n" for name in state["disabled"])
+ if command.startswith("settings get secure "):
+ key = command.split()[-1]
+ value = state.get("voice", {}).get(key)
+ return ("null" if not value else value) + "\n"
+ if command.startswith("dumpsys package "):
+ return state.get("dumps", {}).get(command.split()[-1], "") + "\n"
+ if command.startswith("appops get "):
+ name = command.split()[2]
+ return state.get("appops", {}).get(name, "No operations.") + "\n"
+ return ""
+
+
+class Device:
+ def shell(self, command, read_timeout_s=None):
+ return answer(command)
+
+ def close(self):
+ pass
+
+
+def connect():
+ if state.get("unreachable"):
+ raise ConnectionError("could not connect to 192.168.1.50:5555")
+ return Device()
+
+
+def main():
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
+'''
+
+SYSTEM_DUMP = "userId=1000\nrequested permissions:\n android.permission.RECORD_AUDIO: granted=true\n"
+OWN_DUMP = "userId=10123\nrequested permissions:\n android.permission.RECORD_AUDIO: granted=true\n"
+INTERNET_DUMP = "userId=10124\nrequested permissions:\n android.permission.INTERNET: granted=true\n"
+
+
+class PrivacyAuditTest(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.base = Path(tmp.name)
+ self.repo = self.base / "repo"
+ tools = self.repo / "tools"
+ tools.mkdir(parents=True)
+ shutil.copy2(ROOT / "tools" / "privacy.py", tools / "privacy.py")
+ (tools / "tv.py").write_text(FAKE_TV)
+ self.script = tools / "privacy.py"
+ self.state_path = self.base / "tv-state.json"
+ self.tv()
+
+ def tv(self, **overrides):
+ state = {
+ "installed": [
+ "com.google.android.katniss",
+ "tv.inscape.tvclient.inscapeacr",
+ "org.droidtv.usagelogger",
+ "com.example.voicecontrol",
+ "com.example.plain",
+ ],
+ "disabled": ["org.droidtv.usagelogger"],
+ "voice": {"voice_interaction_service":
+ "com.google.android.katniss/.search.serviceapi.KatnissVoiceInteractionService",
+ "voice_recognition_service":
+ "com.google.android.katniss/.search.serviceapi.KatnissVoiceInteractionService",
+ "assistant": "null"},
+ "dumps": {
+ "com.google.android.katniss": OWN_DUMP,
+ "tv.inscape.tvclient.inscapeacr": INTERNET_DUMP,
+ "com.example.voicecontrol": SYSTEM_DUMP,
+ "org.droidtv.usagelogger": "userId=10125\n",
+ },
+ "appops": {
+ "com.google.android.katniss": "No operations.",
+ "tv.inscape.tvclient.inscapeacr": "RECORD_AUDIO: time=+1m23s ago",
+ },
+ "unreachable": False,
+ }
+ state.update(overrides)
+ self.state_path.write_text(json.dumps(state))
+
+ def run_script(self, *args, host="192.168.1.50"):
+ env = dict(os.environ, TV_HOST=host, FAKE_TV_STATE=str(self.state_path))
+ return subprocess.run([sys.executable, str(self.script), *args], cwd=self.repo, env=env,
+ capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=120)
+
+ # The report
+
+ def test_firmware_nomination_outranks_the_package_name(self):
+ out = self.run_script().stdout
+ self.assertIn("Voice assistants and wake word", out)
+ self.assertIn("named by the TV: voice_interaction_service, voice_recognition_service", out)
+
+ def test_system_uid_is_reported_once_not_as_a_permission_claim(self):
+ out = self.run_script().stdout
+ self.assertIn("shares the system UID (uid 1000)", out)
+ # The same package must not also be advertised as holding the microphone permission.
+ entry = out.split("com.example.voicecontrol", 1)[1].split("\n\n", 1)[0]
+ self.assertNotIn("declares RECORD_AUDIO", entry)
+
+ def test_appops_separates_declared_from_used(self):
+ out = self.run_script().stdout
+ katniss = out.split("com.google.android.katniss", 1)[1].split("\n\n", 1)[0]
+ self.assertIn("declares RECORD_AUDIO", katniss)
+ self.assertIn("appops: no RECORD_AUDIO use since boot", katniss)
+ inscape = out.split("tv.inscape.tvclient.inscapeacr", 1)[1].split("\n\n", 1)[0]
+ self.assertIn("appops: RECORD_AUDIO was used since boot", inscape)
+ self.assertNotIn("declares RECORD_AUDIO", inscape)
+
+ def test_acr_is_kept_apart_from_the_microphone(self):
+ out = self.run_script().stdout
+ self.assertIn("ACR (identifies what is on screen, no microphone needed)", out)
+ self.assertIn("INTERNET, not RECORD_AUDIO", out)
+
+ def test_name_matches_are_not_presented_as_findings(self):
+ out = self.run_script().stdout
+ self.assertIn("Matched by name only, nothing else known", out)
+ self.assertIn("matched by name only", out)
+
+ def test_never_claims_a_package_is_listening(self):
+ out = self.run_script().stdout
+ self.assertIn("What this audit cannot tell you: whether audio ever leaves the TV", out)
+ self.assertIn("the microphone is in the remote rather than the panel", out)
+ for claim in ("is recording", "listens in the background", "spy"):
+ self.assertNotIn(claim, out)
+
+ def test_disabled_packages_are_shown_as_disabled(self):
+ out = self.run_script().stdout
+ self.assertIn("disabled org.droidtv.usagelogger", out)
+
+ def test_names_from_the_tv_are_not_passed_back_into_commands(self):
+ self.tv(installed=["com.example.ok; rm -rf /", "com.google.android.katniss"])
+ out = self.run_script().stdout
+ self.assertNotIn("rm -rf", out)
+
+ # The list it writes
+
+ def write(self, *args):
+ target = self.base / "privacy.txt"
+ return target, self.run_script("--write", str(target), *args)
+
+ def test_write_leaves_out_name_matches_and_already_disabled_packages(self):
+ target, result = self.write()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ text = target.read_text()
+ self.assertIn("com.google.android.katniss", text)
+ self.assertIn("tv.inscape.tvclient.inscapeacr", text)
+ self.assertNotIn("com.example.voicecontrol", text)
+ self.assertNotIn("org.droidtv.usagelogger", text)
+ self.assertEqual([line for line in text.splitlines() if line.startswith("com.example.plain")],
+ [])
+
+ def test_written_list_is_a_list_disable_and_restore_accept(self):
+ target, _ = self.write()
+ lines = [line.split("#", 1)[0].strip() for line in target.read_text().splitlines()]
+ packages = [line for line in lines if line]
+ self.assertEqual(packages, ["com.google.android.katniss",
+ "tv.inscape.tvclient.inscapeacr"])
+ # The header has to spell out both commands, because the undo is the reason this is safe.
+ self.assertIn("tools/disable.sh", target.read_text())
+ self.assertIn("tools/restore.sh", target.read_text())
+ # And the list has to survive the parser the two scripts share, not just look right.
+ sys.path.insert(0, str(ROOT / "tools"))
+ import recovery
+ self.assertEqual(recovery.read_list(target), packages)
+
+ def test_write_refuses_to_overwrite_a_list(self):
+ target, _ = self.write()
+ target.write_text("# mine\n")
+ _, second = self.write()
+ self.assertNotEqual(second.returncode, 0)
+ self.assertIn("already exists", second.stderr)
+ self.assertEqual(target.read_text(), "# mine\n")
+
+ def test_include_low_writes_the_name_matches_too(self):
+ target, result = self.write("--include-low")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("com.example.voicecontrol", target.read_text())
+
+ def test_write_says_nothing_to_do_when_only_name_matches_were_found(self):
+ self.tv(installed=["com.example.voicecontrol"],
+ voice={}, dumps={"com.example.voicecontrol": SYSTEM_DUMP})
+ target, result = self.write()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("nothing identified to write", result.stderr)
+ self.assertFalse(target.exists())
+
+ # Failure modes
+
+ def test_unreachable_tv_names_the_setting_to_check(self):
+ self.tv(unreachable=True)
+ result = self.run_script()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("cannot reach the TV", result.stderr)
+ self.assertIn("tools/tv.py --probe", result.stderr)
+
+ def test_an_empty_package_list_is_an_error_not_an_empty_report(self):
+ self.tv(installed=[], disabled=[])
+ result = self.run_script()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("returned no packages", result.stderr)
+
+ def test_usage_error_for_unknown_arguments(self):
+ result = self.run_script("--write")
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("usage: privacy.py", result.stderr)
+
+
+class CatalogueTest(unittest.TestCase):
+ """The catalogue is the part a reader trusts; keep it honest and small."""
+
+ @classmethod
+ def setUpClass(cls):
+ sys.path.insert(0, str(ROOT / "tools"))
+ import privacy
+ cls.privacy = privacy
+
+ def test_every_entry_says_what_the_package_does(self):
+ for name, (category, note) in self.privacy.CATALOGUE.items():
+ with self.subTest(package=name):
+ self.assertIn(category, ("voice", "acr", "telemetry"))
+ self.assertGreater(len(note), 20, "a note has to say something")
+ self.assertRegex(name, self.privacy.PACKAGE_RE)
+
+ def test_voice_entries_are_assistants_and_acr_entries_are_not(self):
+ # An ACR package that reads the picture is useless to list under the microphone.
+ for name, (category, note) in self.privacy.CATALOGUE.items():
+ if category == "acr":
+ with self.subTest(package=name):
+ self.assertNotIn("microphone", note.split(",")[0])
+
+ def test_name_hint_does_not_match_ordinary_bloat(self):
+ for name in ("com.android.vending", "com.example.playground", "com.example.streaming"):
+ self.assertFalse(self.privacy.NAME_HINT.search(name), name)
+ for name in ("com.example.voice", "com.example.voicecontrol", "tv.example.acr.client",
+ "com.example.speech.service"):
+ self.assertTrue(self.privacy.NAME_HINT.search(name), name)
+
+
+class DocumentationTest(unittest.TestCase):
+ def test_readme_lists_the_tool_and_what_it_cannot_say(self):
+ readme = (ROOT / "README.md").read_text(encoding="utf-8")
+ self.assertIn("[`tools/privacy.py`](tools/privacy.py)", readme)
+ self.assertIn("What the audit cannot do is prove intent", readme)
+
+ def test_prompt_tells_the_assistant_to_audit_instead_of_guessing(self):
+ prompt = (ROOT / "PROMPT.md").read_text(encoding="utf-8")
+ self.assertIn("tools/privacy.py", prompt)
+ self.assertIn("Never say a package records", prompt)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/privacy.py b/tools/privacy.py
new file mode 100644
index 000000000..19b260fb4
--- /dev/null
+++ b/tools/privacy.py
@@ -0,0 +1,333 @@
+#!/usr/bin/env python3
+"""What this TV runs for voice, ACR and telemetry, with the evidence for each name (#444).
+
+ privacy.py audit the connected TV and print the report
+ privacy.py --write <file> write the candidates as a debloat list for tools/disable.sh
+ privacy.py --write <file> --include-low
+ also the packages that only matched by name
+
+The honest part is the evidence, not the category. On firmware where most packages run under
+`android.uid.system`, about fifty of them "have" RECORD_AUDIO and none of them record anything;
+a per-package permission scan would call all fifty listeners. So this audit says which names the
+firmware itself nominated, which ones are known components with a known job, which ones only matched
+by name, and which ones actually touched the microphone op since boot (`appops`). It never claims a
+package is listening.
+
+Disabling is left to `tools/disable.sh`, so the undo path is the one every list already uses: the
+record written before the first change, replayed by `tools/restore.sh`.
+"""
+import os
+import re
+import sys
+
+# Names from the TV end up inside commands run by its shell, so nothing that could carry shell syntax
+# goes through. Same rule as tools/recovery.py.
+PACKAGE_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+")
+
+# What we know about specific packages, from reports in examples/ and docs/ rather than from the name.
+# `category` drives the section in the report; `note` is what the owner reads before disabling it.
+CATALOGUE = {
+ "com.google.android.katniss": (
+ "voice",
+ "Google Assistant and voice search; the remote's mic button and voice search inside apps go "
+ "dead without it",
+ ),
+ "com.google.android.speech.pumpkin": (
+ "voice",
+ "offline hotword model, unused once the assistant above is off",
+ ),
+ "org.droidtv.amazonalexa": (
+ "voice",
+ "Amazon Alexa on Philips sets; the microphone is in the remote, not the panel",
+ ),
+ "tv.inscape.tvclient.inscapeacr": (
+ "acr",
+ "Inscape ACR client: identifies what is on screen, HDMI included, from the picture, and needs "
+ "only INTERNET, not RECORD_AUDIO",
+ ),
+ "com.skyworth.aisense": (
+ "acr",
+ "Coocaa/Skyworth ACR, used to target the ads pushed to the set",
+ ),
+ "org.droidtv.candeebug": (
+ "telemetry",
+ "\"DAC\" analytics on Philips sets",
+ ),
+ "org.droidtv.gel": (
+ "telemetry",
+ "\"GEL\" analytics; it runs inside the candeebug process, so both go together",
+ ),
+ "org.droidtv.usagelogger": (
+ "telemetry",
+ "boot stats, remote keypress counts and panel telemetry",
+ ),
+ "org.droidtv.tv.frameworklogger": (
+ "telemetry",
+ "framework and reboot logging",
+ ),
+ "com.google.android.feedback": (
+ "telemetry",
+ "feedback reports to Google",
+ ),
+}
+
+# A package found only by its name is reported apart and never written into the list by default:
+# `com.example.voicecontrol` may be the panel's own audio routing, and nothing here can tell. The
+# stem matches at the start of a name segment, which catches `voicecontrol` and `micd` while leaving
+# `vending` or `playground` alone; the probe cap keeps the noise bounded.
+NAME_HINT = re.compile(
+ r"(?:^|\.)(acr|analytics|assistant|alexa|hotword|inscape|listen|microphone|privacy|speech|"
+ r"telemetry|tracker|tracking|voice)",
+ re.IGNORECASE,
+)
+
+VOICE_SETTINGS = ("voice_interaction_service", "voice_recognition_service", "assistant")
+TITLES = (
+ ("voice", "Voice assistants and wake word"),
+ ("acr", "ACR (identifies what is on screen, no microphone needed)"),
+ ("telemetry", "Telemetry and analytics"),
+ ("unknown", "Matched by name only, nothing else known"),
+)
+# `dumpsys package` is slow on old firmware; a TV with fifty name matches is not worth ten minutes.
+MAX_PROBES = 25
+SYSTEM_UID = 1000
+
+
+def shell(dev, command):
+ return (dev.shell(command, read_timeout_s=120.0) or "").strip()
+
+
+def connect():
+ # Imported here so the module can be imported (tests, --help) without adb_shell installed.
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ try:
+ import tv
+ except ImportError as e:
+ raise SystemExit(f"cannot load tools/tv.py ({e}).\nrun: python3 -m venv tools/venv && "
+ "tools/venv/bin/pip install -r tools/requirements.txt")
+ try:
+ return tv.connect()
+ except Exception as e:
+ raise SystemExit(f"cannot reach the TV at {os.environ.get('TV_HOST', 'TV_HOST')}: {e}\n"
+ "Check TV_HOST and that USB debugging is still on (tools/tv.py --probe).")
+
+
+def query_packages(dev):
+ installed = []
+ for line in shell(dev, "pm list packages").splitlines():
+ if not line.startswith("package:"):
+ continue
+ name = line.split(":", 1)[1].strip()
+ if PACKAGE_RE.fullmatch(name) and name not in installed:
+ installed.append(name)
+ if not installed:
+ raise SystemExit("the TV returned no packages, so there is nothing to audit. Check the "
+ "connection (tools/tv.py --probe) and try again.")
+ disabled = {line.split(":", 1)[1].strip()
+ for line in shell(dev, "pm list packages -d").splitlines()
+ if line.startswith("package:")}
+ return installed, disabled
+
+
+def voice_setting_owners(dev):
+ """package name -> the secure settings that name it (the firmware's own pick for the assistant)."""
+ owners = {}
+ for key in VOICE_SETTINGS:
+ value = shell(dev, f"settings get secure {key}")
+ if not value or value == "null" or "/" not in value:
+ continue
+ package = value.split("/", 1)[0].strip()
+ if PACKAGE_RE.fullmatch(package):
+ owners.setdefault(package, []).append(key)
+ return owners
+
+
+def probe(dev, name):
+ """What the package declares about the microphone, and whether it used it since boot."""
+ dump = shell(dev, f"dumpsys package {name}")
+ uid = None
+ declared = None
+ if dump:
+ found = re.search(r"\buserId=(\d+)", dump)
+ uid = int(found.group(1)) if found else None
+ declared = "RECORD_AUDIO" in dump
+ ops = shell(dev, f"appops get {name} RECORD_AUDIO")
+ return {"uid": uid, "declared": declared, "appops": ops}
+
+
+def used_microphone(ops):
+ """True / False / None (the TV did not answer) from `appops get <pkg> RECORD_AUDIO`."""
+ if not ops or "error" in ops.lower() or "exception" in ops.lower():
+ return None
+ if "no operations" in ops.lower():
+ return False
+ return "RECORD_AUDIO" in ops
+
+
+def classify(name, owners, probed):
+ """(category, note, evidence lines) for one package."""
+ category, note = CATALOGUE.get(name, ("unknown", "matched by name only"))
+ evidence = []
+ if name in owners:
+ # The firmware nominated it, which outranks both the catalogue and the name.
+ category = "voice" if category == "unknown" else category
+ if name not in CATALOGUE:
+ note = "the TV's own speech service"
+ evidence.append(f"named by the TV: {', '.join(owners[name])}")
+
+ uid = probed.get("uid")
+ if uid == SYSTEM_UID:
+ # About fifty packages on such firmware show RECORD_AUDIO granted because they share the
+ # system UID; listing that per package is how a permission scan ends up crying wolf.
+ evidence.append("shares the system UID (uid 1000): the permissions it shows are the system's, "
+ "not evidence that it records")
+ elif probed.get("declared"):
+ evidence.append("declares RECORD_AUDIO")
+
+ used = used_microphone(probed.get("appops", ""))
+ if used is False:
+ evidence.append("appops: no RECORD_AUDIO use since boot")
+ elif used is True:
+ evidence.append("appops: RECORD_AUDIO was used since boot, which is the one line worth "
+ "reading in full (`appops get <package> RECORD_AUDIO`)")
+ return category, note, evidence
+
+
+def audit(dev):
+ installed, disabled = query_packages(dev)
+ owners = voice_setting_owners(dev)
+
+ candidates = [name for name in installed if name in CATALOGUE or name in owners]
+ hinted = [name for name in installed if name not in candidates and NAME_HINT.search(name)]
+ probes = (candidates + hinted)[:MAX_PROBES]
+
+ entries = []
+ for name in probes:
+ category, note, evidence = classify(name, owners, probe(dev, name))
+ entries.append({
+ "name": name,
+ "category": category,
+ "state": "disabled" if name in disabled else "enabled",
+ "note": note,
+ "evidence": evidence,
+ })
+ return {
+ "installed": installed,
+ "disabled": disabled,
+ "entries": entries,
+ "skipped": max(0, len(candidates) + len(hinted) - len(probes)),
+ }
+
+
+def sections(entries):
+ for category, title in TITLES:
+ group = [e for e in entries if e["category"] == category]
+ if group:
+ yield title, group
+
+
+def print_report(result):
+ installed = len(result["installed"])
+ enabled = installed - len(result["disabled"])
+ print(f"Audit of the TV at {os.environ.get('TV_HOST', 'TV_HOST')}: {installed} packages, "
+ f"{enabled} enabled.\n")
+ for title, group in sections(result["entries"]):
+ print(title)
+ for entry in group:
+ print(f" {entry['state']:<9} {entry['name']}")
+ print(f" {entry['note']}")
+ for line in entry["evidence"]:
+ print(f" {line}")
+ print()
+ if not result["entries"]:
+ print("No voice assistant, ACR client or telemetry package was found by name on this TV.")
+ print("That is not a clean bill of health: it only means nothing here recognised the names.")
+ print()
+ if result["skipped"]:
+ print(f"{result['skipped']} more name matches were not probed (the audit stops at "
+ f"{MAX_PROBES}); check them by hand with `dumpsys package <name>`.")
+ print()
+ print("What to do with it")
+ print(" tools/privacy.py --write privacy.txt # the voice, ACR and telemetry rows above")
+ print(" TV_HOST=<tv ip> tools/disable.sh privacy.txt # applies it, records the undo first")
+ print(" TV_HOST=<tv ip> tools/restore.sh privacy.txt # undo")
+ print()
+ print("What this audit cannot tell you: whether audio ever leaves the TV. `appops` shows the op "
+ "was touched, not what was done with the stream, and on many sets the microphone is in the "
+ "remote rather than the panel. Nothing on this list is proven to be recording, and nothing "
+ "here proves it is not.")
+
+
+def list_lines(result, include_low):
+ """The debloat list for the candidates the audit actually identified."""
+ keep = [e for e in result["entries"]
+ if e["category"] != "unknown" or include_low]
+ if not keep:
+ raise SystemExit("nothing identified to write: only name matches were found. Run the audit "
+ "again to read them, or pass --include-low to write those too.")
+ host = os.environ.get("TV_HOST", "")
+ lines = [
+ f"# Privacy audit of the TV at {host or 'TV_HOST'}, written by tools/privacy.py.",
+ "# Voice, ACR and telemetry candidates this TV answered for. Everything is DISABLED, not",
+ "# uninstalled, and the undo is the one every list uses:",
+ f"# TV_HOST={host or '<tv ip>'} tools/disable.sh privacy.txt",
+ f"# TV_HOST={host or '<tv ip>'} tools/restore.sh privacy.txt",
+ "#",
+ "# Each line says what the package is and why it is here. Nothing below is proven to record",
+ "# anything: the audit reports what the firmware and the packages declare.",
+ ]
+ for title, group in sections(keep):
+ lines.append("")
+ lines.append(f"# {title}")
+ for entry in group:
+ if entry["state"] == "disabled":
+ # Already off: writing it would only make restore.sh re-enable what the owner
+ # disabled on purpose.
+ continue
+ why = entry["note"]
+ if entry["evidence"]:
+ why += f" ({entry['evidence'][0]})"
+ lines.append(f"{entry['name']:<45} # {why}")
+ return lines
+
+
+def write_list(path, result, include_low):
+ if os.path.exists(path):
+ # A second audit of the same TV may legitimately differ, but silently replacing a list the
+ # owner is about to apply is how a hand edit disappears.
+ raise SystemExit(f"{path} already exists; move it aside or choose another name.")
+ lines = list_lines(result, include_low)
+ with open(path, "w") as f:
+ f.write("\n".join(lines) + "\n")
+ names = sum(1 for line in lines if line and not line.startswith("#"))
+ print(f"wrote {names} packages to {path}")
+ print(f"apply: TV_HOST={os.environ.get('TV_HOST', '<tv ip>')} tools/disable.sh {path}")
+ print(f"undo: TV_HOST={os.environ.get('TV_HOST', '<tv ip>')} tools/restore.sh {path}")
+ print(f"read it first: the comments say what each one takes with it.")
+
+
+def main():
+ args = sys.argv[1:]
+ include_low = "--include-low" in args
+ args = [a for a in args if a != "--include-low"]
+ if args and (len(args) != 2 or args[0] != "--write"):
+ sys.stderr.write("usage: privacy.py audit the connected TV\n"
+ " privacy.py --write <file> [--include-low]\n"
+ " write the candidates as a debloat list\n")
+ return 2
+
+ dev = connect()
+ try:
+ result = audit(dev)
+ finally:
+ dev.close()
+
+ if args:
+ write_list(args[1], result, include_low)
+ else:
+ print_report(result)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())