okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
10.1 KiB233 linesraw
1"""Owner-only files: 0600/0700 on POSIX, a one-entry protected ACL for the current user on NTFS."""
2
3from __future__ import annotations
4
5import json
6import os
7import re
8import stat
9import sys
10import tempfile
11import unittest
12from pathlib import Path
13from unittest import mock
14
15sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
16
17from strata_control import private_files as pf  # noqa: E402
18
19
20def resolved(sddl: str) -> str:
21    """``sddl`` with every trustee alias (``LA`` is the built-in Administrator) written as its string SID."""
22    return re.sub(r";;;([^)]*)\)", lambda match: f";;;{pf._string_sid(match.group(1))})", sddl)
23
24
25class PrivateFileTests(unittest.TestCase):
26    def setUp(self):
27        self.tmp = tempfile.TemporaryDirectory()
28        self.addCleanup(self.tmp.cleanup)
29        self.root = Path(self.tmp.name)
30
31    def test_a_file_becomes_private_and_stays_readable_by_us(self):
32        path = self.root / "key.json"
33        path.write_text('{"apiKey": "x"}')
34        pf.restrict_to_current_user(path)
35        self.assertTrue(pf.is_private(path))
36        self.assertEqual(path.read_text(), '{"apiKey": "x"}')
37        path.write_text("{}")  # the owner can still replace it
38
39    def test_a_directory_becomes_private_and_its_children_inherit(self):
40        folder = self.root / "app-data"
41        folder.mkdir()
42        pf.restrict_to_current_user(folder)
43        self.assertTrue(pf.is_private(folder))
44        child = folder / "child.json"
45        child.write_text("{}")
46        if pf.WINDOWS:
47            # the child inherits the directory's single entry rather than the profile's
48            sddl = pf.dacl_sddl(child)
49            self.assertIn(pf.current_user_sid(), resolved(sddl))
50            self.assertNotIn("S-1-1-0", sddl)
51            self.assertNotIn(";;;SY)", sddl)
52            self.assertNotIn(";;;BA)", sddl)
53        else:
54            self.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700)
55
56    @unittest.skipIf(pf.WINDOWS, "POSIX mode bits")
57    def test_posix_modes_are_exact(self):
58        path = self.root / "key.json"
59        path.write_text("{}")
60        os.chmod(path, 0o666)
61        pf.restrict_to_current_user(path)
62        self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
63        os.chmod(path, 0o644)
64        self.assertFalse(pf.is_private(path))
65
66    @unittest.skipUnless(pf.WINDOWS, "NTFS ACLs")
67    def test_the_effective_acl_is_one_protected_entry_for_the_current_user(self):
68        path = self.root / "key.json"
69        path.write_text("{}")
70        self.assertFalse(pf.is_private(path), "a fresh file inherits SYSTEM/Administrators entries")
71        pf.restrict_to_current_user(path)
72        sddl = pf.dacl_sddl(path)
73        self.assertEqual(resolved(sddl), f"D:PAI(A;;FA;;;{pf.current_user_sid()})")
74        # nobody else: no Everyone, Users, Authenticated Users, SYSTEM or Administrators
75        for sid in ("WD", "BU", "AU", "SY", "BA", "S-1-1-0", "S-1-5-32-545"):
76            self.assertNotIn(f";;;{sid})", sddl)
77
78    def test_a_file_made_in_the_profile_is_unshared_but_not_strictly_private(self):
79        path = self.root / "inherited.json"
80        path.write_text("{}")
81        if not pf.WINDOWS:
82            # POSIX files have mode bits rather than an inherited profile ACL.
83            # Specify the private mode instead of depending on the process umask.
84            path.chmod(0o600)
85        self.assertTrue(pf.is_unshared(path))
86        if pf.WINDOWS:
87            self.assertFalse(pf.is_private(path))   # SYSTEM and Administrators still inherit
88        else:
89            self.assertTrue(pf.is_private(path))
90            path.chmod(0o644)
91            self.assertFalse(pf.is_unshared(path))
92            self.assertFalse(pf.is_private(path))
93
94    @unittest.skipUnless(pf.WINDOWS, "NTFS ACLs")
95    def test_everyone_is_noticed_by_the_relaxed_check_too(self):
96        import subprocess
97        path = self.root / "shared.json"
98        path.write_text("{}")
99        subprocess.run(["icacls", str(path), "/grant", "*S-1-1-0:R"], check=True, capture_output=True)
100        self.assertFalse(pf.is_unshared(path))
101
102    @unittest.skipUnless(pf.WINDOWS, "NTFS ACLs")
103    def test_widening_the_acl_is_noticed(self):
104        path = self.root / "key.json"
105        path.write_text("{}")
106        pf.restrict_to_current_user(path)
107        import subprocess
108        subprocess.run(["icacls", str(path), "/grant", "*S-1-1-0:R"], check=True, capture_output=True)
109        self.assertFalse(pf.is_private(path))
110
111
112if __name__ == "__main__":
113    unittest.main()
114
115
116@unittest.skipUnless(pf.WINDOWS, "NTFS ACLs")
117class ElevatedRunLockoutTests(unittest.TestCase):
118    """A file or folder an elevated run made names only SYSTEM and Administrators: the user's normal session cannot open it."""
119
120    def setUp(self):
121        self.tmp = tempfile.TemporaryDirectory()
122        self.addCleanup(self.tmp.cleanup)
123        self.root = Path(self.tmp.name)
124        # repair_access only touches the user's own folders (user_roots): the scratch folder is the "profile" here, wherever TEMP points
125        env = mock.patch.dict(os.environ, {"STRATA_HOME": str(self.root)})
126        env.start()
127        self.addCleanup(env.stop)
128
129    @staticmethod
130    def lock_out(path):
131        """Replace the rule with SYSTEM only: this session may be elevated itself, so Administrators is left out to make the lock-out real."""
132        import ctypes
133        from ctypes import wintypes
134        descriptor = ctypes.c_void_p()
135        assert pf._advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW(
136            "D:P(A;OICI;FA;;;SY)", 1, ctypes.byref(descriptor), None)
137        present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), ctypes.c_void_p()
138        pf._advapi.GetSecurityDescriptorDacl(descriptor, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted))
139        code = pf._advapi.SetNamedSecurityInfoW(str(path), 1, 0x4 | 0x80000000, None, None, dacl, None)
140        assert code == 0, code
141
142    def test_a_locked_file_is_read_again_after_the_repair(self):
143        path = self.root / "profile.json"
144        path.write_text('{"name": "x"}')
145        self.lock_out(path)
146        with self.assertRaises(PermissionError):
147            path.read_bytes()
148        self.assertEqual(pf.read_bytes_repairing(path), b'{"name": "x"}')
149        self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(path)))
150        self.assertEqual(path.read_bytes(), b'{"name": "x"}')
151
152    def test_a_locked_folder_and_what_is_inside_are_repaired_as_a_tree(self):
153        folder = self.root / "profiles"
154        folder.mkdir()
155        (folder / "a.json").write_text("{}")
156        (folder / "sub").mkdir()
157        (folder / "sub" / "b.json").write_text("{}")
158        for item in (folder / "sub" / "b.json", folder / "sub", folder / "a.json", folder):
159            self.lock_out(item)
160        with self.assertRaises(PermissionError):
161            (folder / "a.json").read_bytes()
162        os.environ["STRATA_HOME"] = str(self.root)
163        self.addCleanup(os.environ.pop, "STRATA_HOME", None)
164        report = pf.repair_known_roots()
165        self.assertGreaterEqual(report["repaired"], 1)
166        self.assertEqual(report["failed"], 0)
167        self.assertEqual((folder / "a.json").read_bytes(), b"{}")
168        self.assertEqual((folder / "sub" / "b.json").read_bytes(), b"{}")
169        self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(folder / "sub" / "b.json")))
170
171    def test_a_folder_made_with_private_mkdir_names_the_user_explicitly(self):
172        made = pf.private_mkdir(self.root / "x" / "y", parents=True)
173        self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(made)))
174        self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(made.parent)))
175        (made / "file.json").write_text("{}")
176        self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(made / "file.json")))
177        self.assertEqual((made / "file.json").read_text(), "{}")
178
179    def test_the_process_defaults_can_be_set_for_the_user(self):
180        self.assertTrue(pf.adopt_user_defaults())
181        self.assertTrue(pf.adopt_user_defaults())       # again: nothing breaks
182        path = self.root / "new.json"
183        path.write_text("{}")
184        self.assertEqual(path.read_text(), "{}")
185
186    def test_default_dacl_allows_reopening_child_process_for_qos(self):
187        import subprocess
188        import sys
189        # Isolate token changes and keep this test independent of the test runner's defaults.
190        script = '''
191import ctypes
192from ctypes import wintypes
193import subprocess
194import sys
195from strata_control import private_files as pf
196from serve import winjob
197assert pf.adopt_user_defaults()
198k32 = ctypes.WinDLL("kernel32", use_last_error=True)
199k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
200k32.OpenProcess.restype = wintypes.HANDLE
201k32.CloseHandle.argtypes = (wintypes.HANDLE,)
202child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
203try:
204    handle = k32.OpenProcess(0x1000 | 0x0200, False, child.pid)
205    assert handle, "OpenProcess failed: %s" % ctypes.get_last_error()
206    try:
207        assert winjob.no_throttle(handle), "Setting child QoS failed"
208    finally:
209        k32.CloseHandle(handle)
210finally:
211    child.terminate()
212    child.wait()
213'''
214        result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=40)
215        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
216
217    def test_only_the_users_own_folders_are_ever_repaired(self):
218        self.assertFalse(pf.repair_access(os.environ.get("SystemRoot", "C:\Windows") + "\System32\drivers"))
219
220    def test_a_profile_that_was_locked_loads(self):
221        from strata_control import profiles
222        os.environ["STRATA_PROFILE_DIR"] = str(self.root / "profiles")
223        self.addCleanup(os.environ.pop, "STRATA_PROFILE_DIR", None)
224        directory = self.root / "profiles"
225        directory.mkdir()
226        run_config = self.root / "strata-x.json"
227        run_config.write_text("{}")
228        (directory / "app-1.json").write_text(json.dumps({"schema": 1, "name": "app-1", "source_config": str(run_config)}))
229        self.lock_out(directory / "app-1.json")
230        try:
231            profiles.load("app-1")
232        except profiles.ProfileError as exc:
233            self.assertNotIn("PermissionError", str(exc))     # any other complaint is the sample's shape, not access