Skip to content

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

tools: prevent privacy list overwrites during creation

Sandiv Dathunarachchi546696791c0f
diff --git a/tests/test_privacy_write_name.py b/tests/test_privacy_write_name.py
index d6e5532e4..5f710392f 100644
--- a/tests/test_privacy_write_name.py
+++ b/tests/test_privacy_write_name.py
@@ -16,7 +16,7 @@ the usage block and exit 2, and a folder is named as a folder with the file name
path it is: refused when it is there, "there is no folder" when it is not.
The write itself is guarded too, because the audit is the expensive half: a file that cannot be created
-(a symlink pointing into a folder that is not there is the one that can be written in a test) answered
+(a controlled filesystem failure after the audit is used in the test) answered
"could not be written" with the path and the reason, and the list that was to go into it is printed on
stdout first, so the audited TV does not have to be audited again.
@@ -38,6 +38,7 @@ ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(ROOT / "tools"))
from test_privacy_audit import FAKE_TV, OWN_DUMP # noqa: E402
+from test_privacy_write_target_first import SENTINEL, WRITE_HOOK # noqa: E402
import recovery # noqa: E402
KATNISS = "com.google.android.katniss"
@@ -68,9 +69,13 @@ class PrivacyWriteNameTest(unittest.TestCase):
state.update(overrides)
self.state_path.write_text(json.dumps(state))
- def write(self, *args):
+ def write(self, *args, hook=None):
env = dict(os.environ, TV_HOST="192.168.1.50", FAKE_TV_STATE=str(self.state_path))
- return subprocess.run([sys.executable, str(self.repo / "tools" / "privacy.py"), *args],
+ command = [sys.executable, str(self.repo / "tools" / "privacy.py"), *args]
+ if hook:
+ env.update(PRIVACY_WRITE_HOOK=hook, PRIVACY_SENTINEL=SENTINEL.hex())
+ command = [sys.executable, "-c", WRITE_HOOK, *command[1:]]
+ return subprocess.run(command,
cwd=self.repo, env=env, capture_output=True, text=True,
stdin=subprocess.DEVNULL, timeout=120)
@@ -140,13 +145,8 @@ class PrivacyWriteNameTest(unittest.TestCase):
# The write, when the folder took the check and not the file
- @unittest.skipUnless(hasattr(os, "symlink"), "no symlinks on this platform")
def test_a_file_that_cannot_be_created_keeps_the_audit_on_stdout(self):
- try:
- os.symlink("no-such-folder/privacy.txt", self.repo / "privacy.txt")
- except (OSError, NotImplementedError) as error: # Windows without the symlink privilege
- self.skipTest(f"cannot make a symlink here: {error}")
- result = self.write("--write", "privacy.txt")
+ result = self.write("--write", "privacy.txt", hook="creation_error")
self.assertEqual(result.returncode, 1, result.stderr)
self.assertNotIn("Traceback", result.stderr)
self.assertIn("privacy.txt could not be written", result.stderr)
@@ -158,6 +158,9 @@ class PrivacyWriteNameTest(unittest.TestCase):
copy.write_text(result.stdout)
self.assertEqual(recovery.read_list(copy), [KATNISS])
self.assertNotIn("wrote", result.stderr)
+ self.assertNotIn("wrote", result.stdout)
+ self.assertFalse((self.repo / "privacy.txt").exists())
+ self.assertEqual(list(self.repo.glob(".privacy-*")), [])
if __name__ == "__main__":
diff --git a/tests/test_privacy_write_target_first.py b/tests/test_privacy_write_target_first.py
index 780448a77..1a020cc9b 100644
--- a/tests/test_privacy_write_target_first.py
+++ b/tests/test_privacy_write_target_first.py
@@ -15,10 +15,12 @@ An unreachable fake TV is how a test sees that the TV was not asked: connecting
Run from the repository root: python3 -m unittest discover -s tests -v
"""
+import hashlib
import json
import os
from pathlib import Path
import shutil
+import stat
import subprocess
import sys
import tempfile
@@ -37,6 +39,9 @@ APPEARING_TV = FAKE_TV.replace("def main():", '''_connect = connect
def connect():
+ if state.get("connect_log"):
+ with open(state["connect_log"], "a") as f:
+ f.write("connect\\n")
device = _connect()
if state.get("appears"):
with open(state["appears"], "w") as f:
@@ -47,6 +52,94 @@ def connect():
def main():''', 1)
KATNISS = "com.google.android.katniss"
MATCHES = [f"com.example.voice{i:02d}" for i in range(30)]
+SENTINEL = b"# existing hand edits\ncom.example.keep\n"
+
+# Exercise the CLI with entries inserted at the actual creation/publication operation, after both
+# preflight checks. The audit still runs against the same fake TV as the ordinary subprocess tests.
+WRITE_HOOK = r'''
+import builtins
+import errno
+import importlib.util
+import os
+from pathlib import Path
+import sys
+import tempfile
+
+script = sys.argv.pop(1)
+sys.argv[0] = script
+sys.path.insert(0, str(Path(script).parent))
+spec = importlib.util.spec_from_file_location("privacy_probe", script)
+privacy = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(privacy)
+target = Path(sys.argv[2]).absolute()
+action = os.environ["PRIVACY_WRITE_HOOK"]
+checks = []
+original_check = privacy.target_problem
+
+def checked(path):
+ problem = original_check(path)
+ checks.append(problem)
+ return problem
+
+def before_publication():
+ assert checks == [None, None], checks
+ if action == "file":
+ target.write_bytes(bytes.fromhex(os.environ["PRIVACY_SENTINEL"]))
+ elif action in ("symlink", "dangling"):
+ target.symlink_to(target.parent / "referent.txt")
+ elif action == "deny":
+ raise PermissionError(errno.EACCES, os.strerror(errno.EACCES))
+
+class FailedWriter:
+ def __init__(self, stream):
+ self.stream = stream
+ self.name = stream.name
+ def __enter__(self):
+ return self
+ def write(self, text):
+ if action == "write_error":
+ self.stream.write(text[:12])
+ self.stream.flush()
+ raise OSError(errno.ENOSPC, os.strerror(errno.ENOSPC))
+ return self.stream.write(text)
+ def __exit__(self, *exc):
+ try:
+ if action == "close_error" and exc[0] is None:
+ self.stream.flush()
+ raise OSError(errno.ENOSPC, os.strerror(errno.ENOSPC))
+ finally:
+ self.stream.close()
+
+original_open = builtins.open
+def opening(path, mode="r", *args, **kwargs):
+ if os.path.abspath(path) == str(target) and mode in ("w", "x"):
+ before_publication()
+ if action == "creation_error":
+ raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT))
+ stream = original_open(path, mode, *args, **kwargs)
+ return FailedWriter(stream) if action in ("write_error", "close_error") else stream
+ return original_open(path, mode, *args, **kwargs)
+
+original_rename = os.rename
+def rename(source, destination, *args, **kwargs):
+ if os.path.abspath(destination) == str(target):
+ before_publication()
+ return original_rename(source, destination, *args, **kwargs)
+
+original_temporary_file = tempfile.NamedTemporaryFile
+def temporary_file(*args, **kwargs):
+ assert checks == [None, None], checks
+ if action == "creation_error":
+ raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT))
+ stream = original_temporary_file(*args, **kwargs)
+ return FailedWriter(stream) if action in ("write_error", "close_error") else stream
+
+privacy.target_problem = checked
+privacy.open = opening
+os.rename = rename
+tempfile.NamedTemporaryFile = temporary_file
+sys.exit(privacy.main())
+'''
class PrivacyWriteTargetTest(unittest.TestCase):
@@ -75,12 +168,32 @@ class PrivacyWriteTargetTest(unittest.TestCase):
state.update(overrides)
self.state_path.write_text(json.dumps(state))
- def write(self, target, *args):
+ def write(self, target, *args, hook=None):
env = dict(os.environ, TV_HOST="192.168.1.50", FAKE_TV_STATE=str(self.state_path))
- return subprocess.run([sys.executable, str(self.script), "--write", str(target), *args],
+ command = [sys.executable, str(self.script), "--write", str(target), *args]
+ if hook:
+ env.update(PRIVACY_WRITE_HOOK=hook, PRIVACY_SENTINEL=SENTINEL.hex())
+ command = [sys.executable, "-c", WRITE_HOOK, *command[1:]]
+ return subprocess.run(command,
cwd=self.repo, env=env, capture_output=True, text=True,
stdin=subprocess.DEVNULL, timeout=120)
+ def symlink(self, link, target):
+ try:
+ link.symlink_to(target)
+ except (OSError, NotImplementedError) as error:
+ self.skipTest(f"cannot make a symlink here: {error}")
+
+ def assert_recoverable_failure(self, result):
+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
+ self.assertIn("could not be written", result.stderr)
+ self.assertNotIn("Traceback", result.stderr)
+ self.assertNotIn("wrote", result.stdout)
+ self.assertIn("Privacy audit written by tools/privacy.py", result.stdout)
+ saved = self.base / "saved.txt"
+ saved.write_text(result.stdout)
+ self.assertEqual(recovery.read_list(saved), [KATNISS])
+
# The file, before the TV
def test_an_existing_file_is_refused_before_the_tv_is_asked(self):
@@ -133,6 +246,159 @@ class PrivacyWriteTargetTest(unittest.TestCase):
self.assertNotIn("Nothing was asked of the TV", result.stderr)
self.assertEqual(target.read_text(), "# written during the audit\n")
+ def test_symlinks_are_refused_before_the_tv_is_asked(self):
+ for kind in ("existing", "dangling", "missing_parent"):
+ with self.subTest(kind=kind):
+ folder = self.repo / kind
+ if kind != "missing_parent":
+ folder.mkdir()
+ referent = folder / "referent.txt"
+ if kind == "existing":
+ referent.write_bytes(SENTINEL)
+ target = self.repo / f"{kind}.txt"
+ self.symlink(target, referent)
+ link_value = os.readlink(target)
+ marker = self.base / f"{kind}-connect.txt"
+ self.tv(connect_log=str(marker))
+ result = self.write(target)
+ self.assertEqual(result.returncode, 2,
+ f"referent exists: {referent.exists()}\n"
+ + result.stdout + result.stderr)
+ self.assertIn("already exists", result.stderr)
+ self.assertIn("Nothing was asked of the TV", result.stderr)
+ self.assertEqual(result.stdout, "")
+ self.assertFalse(marker.exists())
+ self.assertTrue(target.is_symlink())
+ self.assertEqual(os.readlink(target), link_value)
+ if kind == "existing":
+ self.assertEqual(referent.read_bytes(), SENTINEL)
+ else:
+ self.assertFalse(referent.exists())
+
+ def test_entries_created_at_publication_are_not_replaced(self):
+ for kind in ("file", "symlink", "dangling"):
+ with self.subTest(kind=kind):
+ folder = self.repo / kind
+ folder.mkdir()
+ target = folder / "privacy.txt"
+ referent = folder / "referent.txt"
+ if kind != "file":
+ probe = folder / "probe.txt"
+ self.symlink(probe, referent)
+ link_value = os.readlink(probe)
+ probe.unlink()
+ if kind == "symlink":
+ referent.write_bytes(SENTINEL)
+ unrelated = folder / "unrelated.txt"
+ unrelated.write_bytes(SENTINEL)
+ result = self.write(target, hook=kind)
+ expected = hashlib.sha256(SENTINEL).hexdigest()
+ actual = hashlib.sha256(target.read_bytes()).hexdigest() if target.is_file() else None
+ self.assertEqual(result.returncode, 1,
+ f"sentinel SHA-256: {expected}; after: {actual}\n"
+ + result.stdout + result.stderr)
+ self.assert_recoverable_failure(result)
+ if kind == "file":
+ self.assertEqual(target.read_bytes(), SENTINEL)
+ self.assertEqual(actual, expected)
+ else:
+ self.assertTrue(target.is_symlink())
+ self.assertEqual(os.readlink(target), link_value)
+ if kind == "symlink":
+ self.assertEqual(referent.read_bytes(), SENTINEL)
+ self.assertEqual(actual, expected)
+ else:
+ self.assertFalse(referent.exists())
+ self.assertEqual(unrelated.read_bytes(), SENTINEL)
+ self.assertEqual(list(folder.glob(".privacy-*")), [])
+
+ def test_failed_publication_keeps_the_audit_and_cleans_staging(self):
+ target = self.repo / "privacy.txt"
+ unrelated = self.repo / "unrelated.txt"
+ unrelated.write_bytes(SENTINEL)
+ result = self.write(target, hook="deny")
+ self.assert_recoverable_failure(result)
+ self.assertIn(os.strerror(13), result.stderr)
+ self.assertFalse(target.exists())
+ self.assertEqual(unrelated.read_bytes(), SENTINEL)
+ self.assertEqual(list(self.repo.glob(".privacy-*")), [])
+
+ @unittest.skipUnless(os.name == "nt", "Windows stages the output before publication")
+ def test_windows_write_and_close_failures_leave_no_staging_files(self):
+ for action in ("write_error", "close_error"):
+ with self.subTest(action=action):
+ target = self.repo / f"{action}.txt"
+ result = self.write(target, hook=action)
+ self.assert_recoverable_failure(result)
+ self.assertFalse(target.exists())
+ self.assertEqual(list(self.repo.glob(".privacy-*")), [])
+
+ def test_unicode_paths_keep_output_bytes_and_creation_permissions(self):
+ name = "audit-客廳-Trịnh.txt"
+ normal = self.repo / name
+ result = self.write(normal)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ folder = self.repo / "客廳 Trịnh"
+ folder.mkdir()
+ target = folder / name
+ result = self.write(target)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stderr, "")
+ self.assertIn(f"wrote 1 packages to {target}", result.stdout)
+ self.assertIn(f"tools/disable.sh {target}", result.stdout)
+ self.assertIn(f"tools/restore.sh {target}", result.stdout)
+ self.assertEqual(target.read_bytes(), normal.read_bytes())
+ self.assertEqual(recovery.read_list(target), [KATNISS])
+ ordinary = folder / "ordinary.txt"
+ with open(ordinary, "w") as stream:
+ stream.write("ordinary creation\n")
+ self.assertEqual(stat.S_IMODE(target.stat().st_mode), stat.S_IMODE(ordinary.stat().st_mode))
+ self.assertEqual(list(folder.glob(".privacy-*")), [])
+
+ @unittest.skipUnless(os.name == "nt" and shutil.which("powershell"), "needs Windows ACLs")
+ def test_windows_creation_inherits_the_destination_acl(self):
+ prepare = r'''
+$ErrorActionPreference='Stop'
+$folder=[Console]::In.ReadToEnd() | ConvertFrom-Json
+$acl=Get-Acl -LiteralPath $folder
+$users=New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')
+$rule=New-Object System.Security.AccessControl.FileSystemAccessRule($users,'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')
+$acl.AddAccessRule($rule)
+Set-Acl -LiteralPath $folder -AclObject $acl
+'''
+ command = ["powershell", "-NoProfile", "-NonInteractive", "-Command"]
+ prepared = subprocess.run(command + [prepare], input=json.dumps(str(self.repo)),
+ capture_output=True, text=True, timeout=30)
+ self.assertEqual(prepared.returncode, 0, prepared.stderr)
+ ordinary = self.repo / "ordinary.txt"
+ with open(ordinary, "w") as stream:
+ stream.write("ordinary creation\n")
+ target = self.repo / "privacy.txt"
+ result = self.write(target)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ inspect = r'''
+$ErrorActionPreference='Stop'
+$paths=[Console]::In.ReadToEnd() | ConvertFrom-Json
+$normal=Get-Acl -LiteralPath $paths[0]
+$written=Get-Acl -LiteralPath $paths[1]
+$access=[System.Security.AccessControl.AccessControlSections]::Access
+$users=@($written.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) | Where-Object {$_.IdentityReference.Value -eq 'S-1-5-32-545' -and $_.AccessControlType -eq 'Allow' -and $_.IsInherited -and (($_.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::ReadData) -ne 0)})
+[pscustomobject]@{
+ same_rules=($normal.GetSecurityDescriptorSddlForm($access) -ceq $written.GetSecurityDescriptorSddlForm($access))
+ same_owner=($normal.Owner -ceq $written.Owner)
+ normal_protected=$normal.AreAccessRulesProtected
+ written_protected=$written.AreAccessRulesProtected
+ inherited_users_read=($users.Count -gt 0)
+} | ConvertTo-Json -Compress
+'''
+ inspected = subprocess.run(command + [inspect], input=json.dumps([str(ordinary), str(target)]),
+ capture_output=True, text=True, timeout=30)
+ self.assertEqual(inspected.returncode, 0, inspected.stderr)
+ self.assertEqual(json.loads(inspected.stdout), {
+ "same_rules": True, "same_owner": True, "normal_protected": False,
+ "written_protected": False, "inherited_users_read": True,
+ })
+
# What the probe cap left out
def test_include_low_says_how_many_name_matches_were_not_probed(self):
diff --git a/tools/privacy.py b/tools/privacy.py
index 93f83cb6f..cce717fc5 100644
--- a/tools/privacy.py
+++ b/tools/privacy.py
@@ -32,6 +32,7 @@ stdout away still shows.
import os
import re
import sys
+import tempfile
# 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.
@@ -417,7 +418,7 @@ def target_problem(path):
# it through is an IsADirectoryError after the whole audit.
return (f"{path} is a folder, and --write takes a file name to create, "
f"e.g. {os.path.join(path, 'privacy.txt')}.")
- if os.path.exists(path):
+ if os.path.lexists(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.
return f"{path} already exists; move it aside or choose another name."
@@ -437,8 +438,28 @@ def write_list(path, result, include_low):
lines = list_lines(result, include_low, os.path.basename(path) if os.path.isabs(path) else path)
text = "\n".join(lines) + "\n"
try:
- with open(path, "w") as f:
- f.write(text)
+ if os.name == "nt":
+ # A sibling inherits the destination folder's ACL. Windows rename refuses existing
+ # entries, including dangling symlinks which open("x") can follow on Windows.
+ staged = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", prefix=".privacy-", suffix=".tmp",
+ dir=os.path.dirname(path) or ".", delete=False) as f:
+ staged = f.name
+ f.write(text)
+ os.rename(staged, path)
+ staged = None
+ finally:
+ if staged is not None:
+ try:
+ os.unlink(staged)
+ except FileNotFoundError:
+ pass
+ else:
+ # A failed write may leave this newly created file. Do not unlink a path another
+ # process could have replaced after creation.
+ with open(path, "x") as f:
+ f.write(text)
except OSError as error:
# The audit is two shell calls for each package it probed, slow on old firmware: a file the
# folder would not take should not cost the owner a second run of it. What was to be written