kneepad 0.3.1__tar.gz → 0.3.2__tar.gz
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.
- {kneepad-0.3.1/src/kneepad.egg-info → kneepad-0.3.2}/PKG-INFO +3 -3
- {kneepad-0.3.1 → kneepad-0.3.2}/README.md +2 -2
- {kneepad-0.3.1 → kneepad-0.3.2}/pyproject.toml +1 -1
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/__init__.py +1 -1
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/audit.py +3 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/cli.py +39 -9
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/util.py +7 -1
- kneepad-0.3.2/src/kneepad/winacl.py +181 -0
- {kneepad-0.3.1 → kneepad-0.3.2/src/kneepad.egg-info}/PKG-INFO +3 -3
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad.egg-info/SOURCES.txt +2 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_audit_snapshots_hook.py +2 -2
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_branches.py +58 -11
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_platforms.py +1 -1
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_races.py +4 -10
- kneepad-0.3.2/tests/test_winacl.py +258 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/LICENSE +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/setup.cfg +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/__main__.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/adapters.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/api.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/argvtools.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/badge.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/config.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/data/footguns.toml +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/data/footguns_ext.toml +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/data/footguns_macos.toml +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/data/footguns_windows.toml +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/engine.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/hook.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/installer.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/integrations.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/rules.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/shellparse.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/snapshots.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/sqlscan.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad/winshell.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad.egg-info/dependency_links.txt +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad.egg-info/entry_points.txt +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/src/kneepad.egg-info/top_level.txt +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_allow_deny_matrix.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_corpus.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_engine.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_hardening.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_integrations.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_qa_corpus.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_qa_regressions.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_robustness.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_rules_db.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_shellparse.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_sqlscan.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_symlink_alias.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_verify_rules_fuzz.py +0 -0
- {kneepad-0.3.1 → kneepad-0.3.2}/tests/test_windows_parity.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: kneepad
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log.
|
|
5
5
|
License: MIT
|
|
6
6
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -41,7 +41,7 @@ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, an
|
|
|
41
41
|
|---|---|---|---|
|
|
42
42
|
| Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
|
|
43
43
|
| Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
|
|
44
|
-
| Continuous integration | full suite | full suite | rule examples and platform tests
|
|
44
|
+
| Continuous integration | full suite and end-to-end QA | full suite and end-to-end QA | rule examples and platform tests gate the build; the full suite and the end-to-end QA run as informational steps and passed on real Windows runners for 0.3.1 |
|
|
45
45
|
|
|
46
46
|
Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The full suite passes on real macOS runners, and the Windows-specific tests pass on real Windows runners (Windows does not run the whole suite). Neither has been used by a person on a real machine with a real agent, so treat both as lightly proven. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
|
47
47
|
|
|
@@ -99,6 +99,6 @@ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short
|
|
|
99
99
|
python3 -m unittest discover -s tests
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
|
|
102
|
+
441 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
|
|
103
103
|
|
|
104
104
|
Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
|
|
@@ -24,7 +24,7 @@ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, an
|
|
|
24
24
|
|---|---|---|---|
|
|
25
25
|
| Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
|
|
26
26
|
| Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
|
|
27
|
-
| Continuous integration | full suite | full suite | rule examples and platform tests
|
|
27
|
+
| Continuous integration | full suite and end-to-end QA | full suite and end-to-end QA | rule examples and platform tests gate the build; the full suite and the end-to-end QA run as informational steps and passed on real Windows runners for 0.3.1 |
|
|
28
28
|
|
|
29
29
|
Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The full suite passes on real macOS runners, and the Windows-specific tests pass on real Windows runners (Windows does not run the whole suite). Neither has been used by a person on a real machine with a real agent, so treat both as lightly proven. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
|
30
30
|
|
|
@@ -82,6 +82,6 @@ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short
|
|
|
82
82
|
python3 -m unittest discover -s tests
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
|
|
85
|
+
441 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
|
|
86
86
|
|
|
87
87
|
Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "kneepad"
|
|
7
|
-
version = "0.3.
|
|
7
|
+
version = "0.3.2"
|
|
8
8
|
description = "Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -125,6 +125,9 @@ class AuditLog:
|
|
|
125
125
|
except OSError:
|
|
126
126
|
pass
|
|
127
127
|
key = self._read_key()
|
|
128
|
+
if os.name == "nt": # 0o600 is ignored on NTFS; make sure inherited access is not wider than the owner
|
|
129
|
+
from . import winacl
|
|
130
|
+
winacl.tighten_if_exposed(self.key_path, False)
|
|
128
131
|
if key is None:
|
|
129
132
|
raise OSError("could not read the audit key")
|
|
130
133
|
return key
|
|
@@ -89,6 +89,14 @@ def cmd_init(args) -> int:
|
|
|
89
89
|
log.ensure_key()
|
|
90
90
|
log.append_if_empty("init", {"version": __version__})
|
|
91
91
|
print(f"Kneepad state directory: {home}")
|
|
92
|
+
if sys.platform == "win32":
|
|
93
|
+
from . import winacl
|
|
94
|
+
for p, is_dir in ((home, True), (log.key_path, False)):
|
|
95
|
+
fixed = winacl.tighten_if_exposed(p, is_dir)
|
|
96
|
+
if fixed is True:
|
|
97
|
+
print(f"Tightened access to {p}: now only you, SYSTEM and Administrators")
|
|
98
|
+
elif fixed is False:
|
|
99
|
+
print(f"warning: {p} is also accessible to other accounts and could not be tightened; fix it with icacls", file=sys.stderr)
|
|
92
100
|
targets = list(getattr(args, "target", None) or [])
|
|
93
101
|
if "all" in targets:
|
|
94
102
|
targets = list(TARGETS)
|
|
@@ -256,7 +264,10 @@ def run_doctor(cwd: str) -> List[tuple]:
|
|
|
256
264
|
items.append((False, "footgun database", str(exc)[:200]))
|
|
257
265
|
win = sys.platform == "win32"
|
|
258
266
|
if os.path.isdir(home) and win:
|
|
259
|
-
|
|
267
|
+
from . import winacl
|
|
268
|
+
rep = winacl.check(home)
|
|
269
|
+
items.append((True if rep.status == "private" else False if rep.status == "exposed" else None,
|
|
270
|
+
"state directory is private", f"{home} ({rep.detail or 'only you, SYSTEM and Administrators'})"))
|
|
260
271
|
elif os.path.isdir(home):
|
|
261
272
|
mode = stat.S_IMODE(os.stat(home).st_mode)
|
|
262
273
|
items.append((mode & 0o077 == 0 or None, "state directory is private", f"{home} mode {oct(mode)}"))
|
|
@@ -264,7 +275,10 @@ def run_doctor(cwd: str) -> List[tuple]:
|
|
|
264
275
|
items.append((None, "state directory exists", f"{home} not created yet; run kneepad init"))
|
|
265
276
|
log = AuditLog(home)
|
|
266
277
|
if os.path.exists(log.key_path) and win:
|
|
267
|
-
|
|
278
|
+
from . import winacl
|
|
279
|
+
rep = winacl.check(log.key_path)
|
|
280
|
+
items.append((True if rep.status == "private" else False if rep.status == "exposed" else None,
|
|
281
|
+
"audit key is private", rep.detail or "only you, SYSTEM and Administrators"))
|
|
268
282
|
elif os.path.exists(log.key_path):
|
|
269
283
|
mode = stat.S_IMODE(os.stat(log.key_path).st_mode)
|
|
270
284
|
items.append((mode & 0o077 == 0, "audit key is private", oct(mode)))
|
|
@@ -415,7 +429,7 @@ def cmd_shell(args) -> int:
|
|
|
415
429
|
cmd_text = _shell_command_arg(argv)
|
|
416
430
|
if cmd_text is not None and _vet_command(cmd_text, "shell", interactive_ask=False) != 0:
|
|
417
431
|
return 126
|
|
418
|
-
if
|
|
432
|
+
if _is_windows(): # os.execv on Windows detaches and loses the exit code
|
|
419
433
|
try:
|
|
420
434
|
return subprocess.call([real] + argv)
|
|
421
435
|
except OSError as exc:
|
|
@@ -534,11 +548,24 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
534
548
|
return p
|
|
535
549
|
|
|
536
550
|
|
|
551
|
+
def _is_windows() -> bool:
|
|
552
|
+
return sys.platform == "win32"
|
|
553
|
+
|
|
554
|
+
|
|
537
555
|
def shell_main() -> int:
|
|
538
556
|
"""Entry point for `kneepad-shell`: a drop-in value for $SHELL."""
|
|
539
557
|
return main(["shell"] + sys.argv[1:])
|
|
540
558
|
|
|
541
559
|
|
|
560
|
+
def _closed_pipe_error(exc: BaseException) -> bool:
|
|
561
|
+
"""A reader that went away: EPIPE everywhere, and EINVAL on Windows (writing to a closed pipe fails with errno 22 there)."""
|
|
562
|
+
import errno
|
|
563
|
+
if isinstance(exc, BrokenPipeError):
|
|
564
|
+
return True
|
|
565
|
+
no = getattr(exc, "errno", None)
|
|
566
|
+
return no == errno.EPIPE or (no == errno.EINVAL and os.name == "nt")
|
|
567
|
+
|
|
568
|
+
|
|
542
569
|
def _flush_std(rc: int) -> int:
|
|
543
570
|
"""Flush stdout and stderr inside main() so a reader that went away (`kneepad rules list | head -1`) is handled here.
|
|
544
571
|
|
|
@@ -550,12 +577,13 @@ def _flush_std(rc: int) -> int:
|
|
|
550
577
|
continue
|
|
551
578
|
try:
|
|
552
579
|
stream.flush()
|
|
553
|
-
except BrokenPipeError:
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
580
|
+
except (BrokenPipeError, OSError) as exc:
|
|
581
|
+
if isinstance(exc, BrokenPipeError) or _closed_pipe_error(exc):
|
|
582
|
+
try:
|
|
583
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), stream.fileno())
|
|
584
|
+
except (OSError, ValueError, AttributeError):
|
|
585
|
+
pass
|
|
586
|
+
except ValueError:
|
|
559
587
|
pass
|
|
560
588
|
return rc
|
|
561
589
|
|
|
@@ -582,5 +610,7 @@ def _main(argv: Optional[List[str]] = None) -> int:
|
|
|
582
610
|
except BrokenPipeError:
|
|
583
611
|
return 0
|
|
584
612
|
except OSError as exc:
|
|
613
|
+
if _closed_pipe_error(exc):
|
|
614
|
+
return 0
|
|
585
615
|
print(f"kneepad: error: {exc}", file=sys.stderr)
|
|
586
616
|
return 1
|
|
@@ -27,9 +27,15 @@ def is_windows() -> bool:
|
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
def ensure_private_dir(path: str) -> None:
|
|
30
|
+
existed = os.path.isdir(path)
|
|
30
31
|
os.makedirs(path, mode=0o700, exist_ok=True)
|
|
31
32
|
if is_windows():
|
|
32
|
-
|
|
33
|
+
# POSIX mode bits mean nothing on NTFS. Under the user profile the inherited ACL is already private; elsewhere it may
|
|
34
|
+
# grant Users or Everyone access, so check once, when the directory is created (icacls is too slow for every hook call).
|
|
35
|
+
if not existed:
|
|
36
|
+
from . import winacl
|
|
37
|
+
winacl.tighten_if_exposed(path, True)
|
|
38
|
+
return
|
|
33
39
|
try: # a directory we did not create may be too open; tighten it if we own it
|
|
34
40
|
st = os.stat(path)
|
|
35
41
|
if st.st_uid == os.getuid() and (st.st_mode & 0o077):
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Windows access-control checks for Kneepad's state directory and audit key.
|
|
2
|
+
|
|
3
|
+
POSIX gets 0700/0600 modes. NTFS has ACLs instead, and the default ACL of a folder under the user profile is already private
|
|
4
|
+
(the account, SYSTEM and Administrators). That default is not guaranteed: ``KNEEPAD_HOME`` may point somewhere that inherits
|
|
5
|
+
"Users" or "Everyone" read access, for example under ``C:\\ProgramData`` or the root of another drive.
|
|
6
|
+
|
|
7
|
+
This module reads a path's ACL through ``icacls /save`` (the output is an SDDL string made of SIDs, so it does not depend on the
|
|
8
|
+
Windows display language), decides whether anybody besides the current user, SYSTEM and Administrators can reach it, and can
|
|
9
|
+
remove the extra access. It uses only ``icacls`` and ``whoami``, which ship with every supported Windows.
|
|
10
|
+
|
|
11
|
+
Nothing here runs on the hook path. It is used when the state directory or key is created, by ``kneepad init`` and by
|
|
12
|
+
``kneepad doctor``. Every function returns "unknown" or ``False`` on failure instead of raising.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import tempfile
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import List, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
# SDDL two-letter aliases for the security identifiers that appear in ordinary ACLs.
|
|
26
|
+
_ALIASES = {
|
|
27
|
+
"SY": "S-1-5-18", "BA": "S-1-5-32-544", "CO": "S-1-3-0", "OW": "S-1-3-4", "WD": "S-1-1-0", "BU": "S-1-5-32-545",
|
|
28
|
+
"AU": "S-1-5-11", "IU": "S-1-5-4", "NU": "S-1-5-2", "AN": "S-1-5-7", "BG": "S-1-5-32-546", "LG": "S-1-5-32-546",
|
|
29
|
+
"PU": "S-1-5-32-547", "SU": "S-1-5-6", "LS": "S-1-5-19", "NS": "S-1-5-20", "BO": "S-1-5-32-551", "SO": "S-1-5-32-549",
|
|
30
|
+
"RC": "S-1-5-12", "CG": "S-1-3-1", "LU": "S-1-5-32-559", "WR": "S-1-5-33", "AC": "S-1-15-2-1",
|
|
31
|
+
}
|
|
32
|
+
_NAMES = {
|
|
33
|
+
"S-1-1-0": "Everyone", "S-1-5-32-545": "BUILTIN\\Users", "S-1-5-11": "Authenticated Users", "S-1-5-4": "INTERACTIVE",
|
|
34
|
+
"S-1-5-2": "NETWORK", "S-1-5-7": "ANONYMOUS LOGON", "S-1-5-32-546": "BUILTIN\\Guests", "S-1-5-32-547": "BUILTIN\\Power Users",
|
|
35
|
+
"S-1-15-2-1": "ALL APPLICATION PACKAGES",
|
|
36
|
+
}
|
|
37
|
+
# Principals that may always have access: SYSTEM, Administrators, CREATOR OWNER, OWNER RIGHTS.
|
|
38
|
+
_ALWAYS_OK = frozenset({"S-1-5-18", "S-1-5-32-544", "S-1-3-0", "S-1-3-4"})
|
|
39
|
+
# SDDL aliases with no fixed SID because they depend on the machine or domain. They are all administrator-level (the local
|
|
40
|
+
# Administrator account, which is also the account GitHub's runners log in as, and the domain/enterprise/schema/cert admins),
|
|
41
|
+
# so they are no wider than the Administrators group that is always allowed.
|
|
42
|
+
_ADMIN_ALIASES = frozenset({"LA", "DA", "EA", "SA", "CA"})
|
|
43
|
+
_ACE = re.compile(r"\(([^;()]*);([^;()]*);([^;()]*);([^;()]*);([^;()]*);([^;()]*)\)")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class AclReport:
|
|
48
|
+
status: str # "private" | "exposed" | "unknown"
|
|
49
|
+
exposed: List[str] = field(default_factory=list) # who else can reach the path
|
|
50
|
+
detail: str = ""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
trace: List[str] = [] # the last helper calls and their exit codes, so a failed check can be explained in a test or bug report
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _run(args: List[str]) -> Tuple[int, str]:
|
|
57
|
+
"""Run a helper program and return (exit code, stdout). Isolated so tests can replace it."""
|
|
58
|
+
try:
|
|
59
|
+
p = subprocess.run(args, capture_output=True, text=True, timeout=30, encoding="utf-8", errors="replace")
|
|
60
|
+
rc, out = p.returncode, p.stdout
|
|
61
|
+
note = (p.stdout + p.stderr).strip().replace("\n", " ")[:90]
|
|
62
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
63
|
+
rc, out, note = 127, "", type(exc).__name__
|
|
64
|
+
trace.append(f"{' '.join(args[1:3])[:60]} {' '.join(a for a in args[3:])[:70]} -> {rc} {note}")
|
|
65
|
+
del trace[:-12]
|
|
66
|
+
return rc, out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_me_cache: List[Optional[str]] = []
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def current_user_sid() -> Optional[str]:
|
|
73
|
+
"""SID of the account running this process, or None when it cannot be determined."""
|
|
74
|
+
if _me_cache:
|
|
75
|
+
return _me_cache[0]
|
|
76
|
+
sid: Optional[str] = None
|
|
77
|
+
rc, out = _run(["whoami", "/user", "/fo", "csv", "/nh"])
|
|
78
|
+
if rc == 0:
|
|
79
|
+
m = re.search(r'"(S-1-[0-9-]+)"\s*$', out.strip())
|
|
80
|
+
sid = m.group(1) if m else None
|
|
81
|
+
_me_cache.append(sid)
|
|
82
|
+
return sid
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def parse_dacl(sddl: str) -> List[Tuple[str, str, str, str]]:
|
|
86
|
+
"""Return (type, flags, rights, sid) for each ACE in the DACL part of an SDDL string; aliases are expanded to SIDs."""
|
|
87
|
+
text = sddl.strip()
|
|
88
|
+
if "D:" in text:
|
|
89
|
+
text = text.split("D:", 1)[1]
|
|
90
|
+
text = text.split("S:", 1)[0]
|
|
91
|
+
out = []
|
|
92
|
+
for m in _ACE.finditer(text):
|
|
93
|
+
typ, flags, rights, _og, _ig, sid = (g.strip() for g in m.groups())
|
|
94
|
+
out.append((typ, flags, rights, _ALIASES.get(sid, sid)))
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def exposed_principals(sddl: str, me: Optional[str]) -> List[str]:
|
|
99
|
+
"""Names (or SIDs) that an allow entry grants some access to, besides the current user and the always-fine principals."""
|
|
100
|
+
seen: List[str] = []
|
|
101
|
+
for typ, _flags, rights, sid in parse_dacl(sddl):
|
|
102
|
+
if typ not in ("A", "OA") or not rights:
|
|
103
|
+
continue
|
|
104
|
+
if sid in _ALWAYS_OK or sid in _ADMIN_ALIASES or sid == me or sid.startswith("S-1-5-80-"): # S-1-5-80-*: NT SERVICE accounts such as TrustedInstaller
|
|
105
|
+
continue
|
|
106
|
+
name = _NAMES.get(sid, sid)
|
|
107
|
+
if name not in seen:
|
|
108
|
+
seen.append(name)
|
|
109
|
+
return seen
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def read_sddl(path: str) -> Optional[str]:
|
|
113
|
+
"""The DACL of ``path`` as an SDDL string, or None."""
|
|
114
|
+
d = tempfile.mkdtemp(prefix="kneepad-acl-")
|
|
115
|
+
out = os.path.join(d, "acl.txt")
|
|
116
|
+
try:
|
|
117
|
+
rc, _ = _run(["icacls", path, "/save", out, "/c"])
|
|
118
|
+
if rc != 0 or not os.path.exists(out):
|
|
119
|
+
return None
|
|
120
|
+
with open(out, "rb") as fh:
|
|
121
|
+
raw = fh.read()
|
|
122
|
+
except OSError:
|
|
123
|
+
return None
|
|
124
|
+
finally:
|
|
125
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
126
|
+
if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
|
|
127
|
+
text = raw.decode("utf-16", "replace")
|
|
128
|
+
elif b"\x00" in raw[:8]:
|
|
129
|
+
text = raw.decode("utf-16-le", "replace")
|
|
130
|
+
else:
|
|
131
|
+
text = raw.decode("utf-8", "replace")
|
|
132
|
+
for line in text.splitlines():
|
|
133
|
+
line = line.strip().lstrip("\ufeff")
|
|
134
|
+
if line.startswith("D:"):
|
|
135
|
+
return line
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def check(path: str) -> AclReport:
|
|
140
|
+
"""Who besides you, SYSTEM and Administrators can reach ``path``?"""
|
|
141
|
+
me = current_user_sid()
|
|
142
|
+
if me is None:
|
|
143
|
+
return AclReport("unknown", detail="could not determine the current user")
|
|
144
|
+
sddl = read_sddl(path)
|
|
145
|
+
if sddl is None:
|
|
146
|
+
return AclReport("unknown", detail="could not read the ACL (icacls unavailable or access denied)")
|
|
147
|
+
extra = exposed_principals(sddl, me)
|
|
148
|
+
if extra:
|
|
149
|
+
return AclReport("exposed", extra, "also accessible to " + ", ".join(extra))
|
|
150
|
+
return AclReport("private")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def tighten(path: str, is_dir: bool) -> bool:
|
|
154
|
+
"""Leave access to the current user, SYSTEM and Administrators only. True when the path ends up private."""
|
|
155
|
+
me = current_user_sid()
|
|
156
|
+
if me is None:
|
|
157
|
+
return False
|
|
158
|
+
before = check(path)
|
|
159
|
+
if before.status == "private":
|
|
160
|
+
return True
|
|
161
|
+
suffix = "(OI)(CI)F" if is_dir else "F"
|
|
162
|
+
grants = [f"*{me}:{suffix}", f"*S-1-5-18:{suffix}", f"*S-1-5-32-544:{suffix}"]
|
|
163
|
+
# Grant ourselves first so removing inherited access can never lock this account out.
|
|
164
|
+
_run(["icacls", path, "/grant:r"] + grants)
|
|
165
|
+
_run(["icacls", path, "/inheritance:r"])
|
|
166
|
+
sddl = read_sddl(path)
|
|
167
|
+
if sddl is not None:
|
|
168
|
+
for name in exposed_principals(sddl, me):
|
|
169
|
+
sid = next((s for s, n in _NAMES.items() if n == name), name)
|
|
170
|
+
if sid.startswith("S-1-"):
|
|
171
|
+
_run(["icacls", path, "/remove:g", f"*{sid}"])
|
|
172
|
+
_run(["icacls", path, "/remove:d", f"*{sid}"])
|
|
173
|
+
return check(path).status == "private"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def tighten_if_exposed(path: str, is_dir: bool) -> Optional[bool]:
|
|
177
|
+
"""None when the ACL is already private or cannot be read; otherwise whether tightening worked."""
|
|
178
|
+
rep = check(path)
|
|
179
|
+
if rep.status != "exposed":
|
|
180
|
+
return None
|
|
181
|
+
return tighten(path, is_dir)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: kneepad
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log.
|
|
5
5
|
License: MIT
|
|
6
6
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -41,7 +41,7 @@ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, an
|
|
|
41
41
|
|---|---|---|---|
|
|
42
42
|
| Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
|
|
43
43
|
| Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
|
|
44
|
-
| Continuous integration | full suite | full suite | rule examples and platform tests
|
|
44
|
+
| Continuous integration | full suite and end-to-end QA | full suite and end-to-end QA | rule examples and platform tests gate the build; the full suite and the end-to-end QA run as informational steps and passed on real Windows runners for 0.3.1 |
|
|
45
45
|
|
|
46
46
|
Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The full suite passes on real macOS runners, and the Windows-specific tests pass on real Windows runners (Windows does not run the whole suite). Neither has been used by a person on a real machine with a real agent, so treat both as lightly proven. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
|
47
47
|
|
|
@@ -99,6 +99,6 @@ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short
|
|
|
99
99
|
python3 -m unittest discover -s tests
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
|
|
102
|
+
441 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
|
|
103
103
|
|
|
104
104
|
Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
|
|
@@ -19,6 +19,7 @@ src/kneepad/shellparse.py
|
|
|
19
19
|
src/kneepad/snapshots.py
|
|
20
20
|
src/kneepad/sqlscan.py
|
|
21
21
|
src/kneepad/util.py
|
|
22
|
+
src/kneepad/winacl.py
|
|
22
23
|
src/kneepad/winshell.py
|
|
23
24
|
src/kneepad.egg-info/PKG-INFO
|
|
24
25
|
src/kneepad.egg-info/SOURCES.txt
|
|
@@ -46,4 +47,5 @@ tests/test_shellparse.py
|
|
|
46
47
|
tests/test_sqlscan.py
|
|
47
48
|
tests/test_symlink_alias.py
|
|
48
49
|
tests/test_verify_rules_fuzz.py
|
|
50
|
+
tests/test_winacl.py
|
|
49
51
|
tests/test_windows_parity.py
|
|
@@ -30,7 +30,7 @@ class TestAudit(IsolatedCase):
|
|
|
30
30
|
def test_empty_log_verifies(self):
|
|
31
31
|
self.assertTrue(AuditLog(self.sb_home).verify().ok)
|
|
32
32
|
|
|
33
|
-
@unittest.skipIf(os.name == "nt", "POSIX mode bits;
|
|
33
|
+
@unittest.skipIf(os.name == "nt", "POSIX mode bits; the Windows ACL equivalents are in tests/test_winacl.py")
|
|
34
34
|
def test_key_file_is_private(self):
|
|
35
35
|
self.fill(1)
|
|
36
36
|
mode = stat.S_IMODE(os.stat(os.path.join(self.sb_home, "key")).st_mode)
|
|
@@ -195,7 +195,7 @@ class TestSnapshots(IsolatedCase):
|
|
|
195
195
|
if not os.path.islink(fp) and f != "manifest.json":
|
|
196
196
|
self.assertNotIn("TOPSECRET", open(fp).read())
|
|
197
197
|
|
|
198
|
-
@unittest.skipIf(os.name == "nt", "POSIX mode bits;
|
|
198
|
+
@unittest.skipIf(os.name == "nt", "POSIX mode bits; the Windows ACL equivalents are in tests/test_winacl.py")
|
|
199
199
|
def test_snapshot_dir_is_private(self):
|
|
200
200
|
p = self.write("a.txt")
|
|
201
201
|
SnapshotStore(self.sb_home).create(SnapshotPlan(kind="files", cwd=self.proj, paths=[p]))
|
|
@@ -192,6 +192,32 @@ class TestCliBranches(Sandbox):
|
|
|
192
192
|
rc, out, err = self.cli("doctor")
|
|
193
193
|
self.assertNotIn("cursor hook installed", out)
|
|
194
194
|
|
|
195
|
+
def test_init_each_installable_target_roundtrip(self):
|
|
196
|
+
"""Same round trip as `--target all`, but without Cline on Windows, where it is intentionally refused."""
|
|
197
|
+
targets = [t for t in integrations.TARGETS if not (t == "cline" and sys.platform == "win32")]
|
|
198
|
+
args = ["init", "--claude-code", "--scope", "project"]
|
|
199
|
+
for t in targets:
|
|
200
|
+
args += ["--target", t]
|
|
201
|
+
rc, out, err = self.cli(*args)
|
|
202
|
+
self.assertEqual(rc, 0, err)
|
|
203
|
+
rc, out, err = self.cli("doctor")
|
|
204
|
+
for t in targets:
|
|
205
|
+
self.assertIn(f"{t} hook installed", out)
|
|
206
|
+
un = ["uninstall", "--claude-code", "--scope", "project"]
|
|
207
|
+
for t in targets:
|
|
208
|
+
un += ["--target", t]
|
|
209
|
+
rc, out, err = self.cli(*un)
|
|
210
|
+
self.assertEqual(rc, 0, err)
|
|
211
|
+
rc, out, err = self.cli("doctor")
|
|
212
|
+
for t in targets:
|
|
213
|
+
self.assertNotIn(f"{t} hook installed", out)
|
|
214
|
+
|
|
215
|
+
@unittest.skipUnless(sys.platform == "win32", "Cline is refused only on Windows")
|
|
216
|
+
def test_cline_is_refused_clearly_on_windows(self):
|
|
217
|
+
rc, out, err = self.cli("init", "--target", "cline", "--scope", "project")
|
|
218
|
+
self.assertEqual(rc, 1)
|
|
219
|
+
self.assertIn("Windows", err)
|
|
220
|
+
|
|
195
221
|
def test_uninstall_default_removes_claude_hook_only(self):
|
|
196
222
|
self.cli("init", "--claude-code")
|
|
197
223
|
rc, out, _ = self.cli("uninstall")
|
|
@@ -287,7 +313,7 @@ class TestCliBranches(Sandbox):
|
|
|
287
313
|
rc, out, _ = self.cli("badge", "--force", "--out", out_path)
|
|
288
314
|
self.assertEqual(rc, 0)
|
|
289
315
|
|
|
290
|
-
@unittest.skipIf(sys.platform == "win32", "POSIX mode bits;
|
|
316
|
+
@unittest.skipIf(sys.platform == "win32", "POSIX mode bits; the Windows ACL equivalents are in tests/test_winacl.py")
|
|
291
317
|
def test_doctor_variants(self):
|
|
292
318
|
shutil.rmtree(self.state)
|
|
293
319
|
rc, out, _ = self.cli("doctor")
|
|
@@ -370,18 +396,39 @@ class TestCliBranches(Sandbox):
|
|
|
370
396
|
self.assertTrue(os.path.exists("untracked.txt"), "the file must not be deleted when its backup failed")
|
|
371
397
|
self.assertTrue(AuditLog().read_all()[-1]["data"]["refused"])
|
|
372
398
|
|
|
373
|
-
@unittest.skipIf(sys.platform == "win32", "Windows runs the real shell as a child process instead of exec (the exit code would be lost)")
|
|
374
399
|
def test_shell_branches(self):
|
|
400
|
+
"""POSIX replaces the process with the real shell (exec); the Windows branch is covered by the next test."""
|
|
375
401
|
self.cli("init")
|
|
376
|
-
with mock.patch.object(cli
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
cli.
|
|
384
|
-
|
|
402
|
+
with mock.patch.object(cli, "_is_windows", return_value=False):
|
|
403
|
+
with mock.patch.object(cli.os, "execv") as ex:
|
|
404
|
+
rc = cli.cmd_shell(type("A", (), {"argv": ["-c", "echo hi"]})())
|
|
405
|
+
ex.assert_called_once()
|
|
406
|
+
with mock.patch.object(cli.os, "execv") as ex:
|
|
407
|
+
rc = cli.cmd_shell(type("A", (), {"argv": ["--", "-c", "echo hi"]})())
|
|
408
|
+
ex.assert_called_once()
|
|
409
|
+
with mock.patch.object(cli.os, "execv") as ex: # interactive shell or script: nothing to vet
|
|
410
|
+
cli.cmd_shell(type("A", (), {"argv": ["script.sh"]})())
|
|
411
|
+
ex.assert_called_once()
|
|
412
|
+
|
|
413
|
+
def test_shell_branches_windows_child_process(self):
|
|
414
|
+
"""Windows cannot exec (the exit code would be lost), so the shell runs as a child and its exit code is returned."""
|
|
415
|
+
self.cli("init")
|
|
416
|
+
with mock.patch.object(cli, "_is_windows", return_value=True), mock.patch.object(cli.os, "execv") as ex:
|
|
417
|
+
with mock.patch.object(cli.subprocess, "call", return_value=7) as call:
|
|
418
|
+
rc = cli.cmd_shell(type("A", (), {"argv": ["-c", "echo hi"]})())
|
|
419
|
+
self.assertEqual(rc, 7)
|
|
420
|
+
self.assertEqual(call.call_args[0][0][1:], ["-c", "echo hi"])
|
|
421
|
+
with mock.patch.object(cli.subprocess, "call", side_effect=FileNotFoundError("no bash")):
|
|
422
|
+
err = io.StringIO()
|
|
423
|
+
with redirect_stderr(err):
|
|
424
|
+
rc = cli.cmd_shell(type("A", (), {"argv": ["-c", "echo hi"]})())
|
|
425
|
+
self.assertEqual(rc, 127)
|
|
426
|
+
self.assertIn("cannot run", err.getvalue())
|
|
427
|
+
with mock.patch.object(cli.subprocess, "call", return_value=0) as call: # refused commands never reach the shell
|
|
428
|
+
rc = cli.cmd_shell(type("A", (), {"argv": ["-c", "rm -rf /"]})())
|
|
429
|
+
self.assertEqual(rc, 126)
|
|
430
|
+
call.assert_not_called()
|
|
431
|
+
ex.assert_not_called()
|
|
385
432
|
|
|
386
433
|
def test_default_real_shell(self):
|
|
387
434
|
self.assertTrue(cli._default_real_shell())
|
|
@@ -305,7 +305,7 @@ class TestWindowsWrites(unittest.TestCase):
|
|
|
305
305
|
self.assertEqual(az.analyze_write_path("c:\\USERS\\ME\\.SSH\\config").action, "ask")
|
|
306
306
|
|
|
307
307
|
|
|
308
|
-
@unittest.skipIf(os.name == "nt", "simulates macOS with POSIX paths, which Windows' own path functions cannot process")
|
|
308
|
+
@unittest.skipIf(os.name == "nt", "simulates macOS with POSIX paths, which Windows' own path functions cannot process; the macOS CI jobs run these")
|
|
309
309
|
class TestMacOS(unittest.TestCase):
|
|
310
310
|
def test_home_and_cwd_under_private_are_compared_consistently(self):
|
|
311
311
|
"""GitHub's macOS runners (and many real temp dirs) live under /private/var; the prefix must not break matching."""
|
|
@@ -187,23 +187,17 @@ if __name__ == "__main__":
|
|
|
187
187
|
class TestBrokenPipe(unittest.TestCase):
|
|
188
188
|
"""`kneepad rules list | head -1` must exit 0 and stay silent, whenever the reader leaves (CI: STB-007 on macOS)."""
|
|
189
189
|
|
|
190
|
-
@unittest.skipIf(os.name == "nt", "needs a POSIX pipe whose reader can leave early (`| head -1`); Windows cannot pass a raw os.pipe() descriptor to a child")
|
|
191
190
|
def test_reader_leaves_before_exit_flush(self):
|
|
192
|
-
import subprocess
|
|
193
|
-
import time
|
|
194
191
|
src = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")
|
|
195
192
|
code = ("import sys,time;sys.path.insert(0,%r);from kneepad.cli import main\n"
|
|
196
193
|
"rc=main(['rules','list'])\n"
|
|
197
194
|
"time.sleep(0.5)\n"
|
|
198
195
|
"sys.exit(rc)") % src
|
|
199
196
|
env = {k: v for k, v in os.environ.items() if k != "PYTHONUNBUFFERED"}
|
|
200
|
-
|
|
201
|
-
p
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
os.read(r, 100)
|
|
205
|
-
os.close(r)
|
|
206
|
-
err = p.stderr.read().decode()
|
|
197
|
+
p = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
|
|
198
|
+
p.stdout.read(100)
|
|
199
|
+
p.stdout.close() # the reader leaves, like `head -1`
|
|
200
|
+
err = p.stderr.read().decode(errors="replace")
|
|
207
201
|
rc = p.wait()
|
|
208
202
|
p.stderr.close()
|
|
209
203
|
self.assertEqual(err.strip(), "", err)
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Windows ACL checks for the state directory and audit key.
|
|
2
|
+
|
|
3
|
+
The SDDL parsing and the decision logic run everywhere with icacls replaced by a fake. The last class talks to the real icacls and
|
|
4
|
+
only runs on Windows (it replaces the POSIX-mode tests that cannot run there)."""
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import unittest
|
|
10
|
+
from unittest import mock
|
|
11
|
+
|
|
12
|
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
|
|
13
|
+
|
|
14
|
+
from kneepad import winacl # noqa: E402
|
|
15
|
+
|
|
16
|
+
ME = "S-1-5-21-111-222-333-1001"
|
|
17
|
+
PRIVATE = f"D:PAI(A;OICI;FA;;;{ME})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)"
|
|
18
|
+
USERS_INHERITED = f"D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;OICIID;FA;;;{ME})"
|
|
19
|
+
EVERYONE = f"D:PAI(A;;FA;;;{ME})(A;;FR;;;WD)"
|
|
20
|
+
OTHER_USER = f"D:PAI(A;;FA;;;{ME})(A;;FA;;;S-1-5-21-111-222-333-1002)"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Parser(unittest.TestCase):
|
|
24
|
+
def test_aliases_expand_to_sids(self):
|
|
25
|
+
self.assertEqual([a[3] for a in winacl.parse_dacl(PRIVATE)], [ME, "S-1-5-18", "S-1-5-32-544"])
|
|
26
|
+
|
|
27
|
+
def test_private_acl_has_no_exposure(self):
|
|
28
|
+
self.assertEqual(winacl.exposed_principals(PRIVATE, ME), [])
|
|
29
|
+
|
|
30
|
+
def test_users_group_is_exposure(self):
|
|
31
|
+
self.assertEqual(winacl.exposed_principals(USERS_INHERITED, ME), ["BUILTIN\\Users"])
|
|
32
|
+
|
|
33
|
+
def test_everyone_is_exposure(self):
|
|
34
|
+
self.assertEqual(winacl.exposed_principals(EVERYONE, ME), ["Everyone"])
|
|
35
|
+
|
|
36
|
+
def test_another_account_is_exposure_by_sid(self):
|
|
37
|
+
self.assertEqual(winacl.exposed_principals(OTHER_USER, ME), ["S-1-5-21-111-222-333-1002"])
|
|
38
|
+
|
|
39
|
+
def test_deny_entries_and_empty_rights_are_not_exposure(self):
|
|
40
|
+
self.assertEqual(winacl.exposed_principals(f"D:P(D;;FA;;;WD)(A;;FA;;;{ME})(A;;;;;BU)", ME), [])
|
|
41
|
+
|
|
42
|
+
def test_trusted_installer_and_creator_owner_are_fine(self):
|
|
43
|
+
self.assertEqual(winacl.exposed_principals(f"D:P(A;;FA;;;S-1-5-80-956008885-1)(A;;FA;;;CO)(A;;FA;;;{ME})", ME), [])
|
|
44
|
+
|
|
45
|
+
def test_sacl_part_is_ignored(self):
|
|
46
|
+
self.assertEqual(winacl.exposed_principals(f"D:P(A;;FA;;;{ME})S:(AU;SA;FA;;;WD)", ME), [])
|
|
47
|
+
|
|
48
|
+
def test_local_administrator_alias_is_not_exposure(self):
|
|
49
|
+
"""GitHub's Windows runners log in as the built-in Administrator, whose own ACE is written with the alias LA."""
|
|
50
|
+
self.assertEqual(winacl.exposed_principals("D:PAI(A;OICI;FA;;;LA)(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;OW)", ME), [])
|
|
51
|
+
|
|
52
|
+
def test_domain_admin_aliases_are_not_exposure(self):
|
|
53
|
+
self.assertEqual(winacl.exposed_principals(f"D:P(A;;FA;;;DA)(A;;FA;;;EA)(A;;FA;;;{ME})", ME), [])
|
|
54
|
+
|
|
55
|
+
def test_guest_account_is_still_exposure(self):
|
|
56
|
+
self.assertEqual(winacl.exposed_principals(f"D:P(A;;FA;;;{ME})(A;;FR;;;LG)", ME), ["BUILTIN\\Guests"])
|
|
57
|
+
|
|
58
|
+
def test_garbage_gives_no_entries(self):
|
|
59
|
+
self.assertEqual(winacl.parse_dacl("not sddl"), [])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FakeIcacls:
|
|
63
|
+
"""Stands in for icacls/whoami: keeps one SDDL per path and applies the few switches Kneepad uses."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, sddl_by_path, me=ME, fail=False):
|
|
66
|
+
self.acl = dict(sddl_by_path)
|
|
67
|
+
self.me, self.fail, self.calls = me, fail, []
|
|
68
|
+
|
|
69
|
+
def __call__(self, args):
|
|
70
|
+
self.calls.append(list(args))
|
|
71
|
+
if self.fail:
|
|
72
|
+
return 1, ""
|
|
73
|
+
if args[0] == "whoami":
|
|
74
|
+
return 0, f'"HOST\\\\user","{self.me}"\r\n'
|
|
75
|
+
path = args[1]
|
|
76
|
+
if "/save" in args:
|
|
77
|
+
out = args[args.index("/save") + 1]
|
|
78
|
+
with open(out, "wb") as fh:
|
|
79
|
+
fh.write(("" + path + "\r\n" + self.acl[path] + "\r\n").encode("utf-16-le"))
|
|
80
|
+
return 0, ""
|
|
81
|
+
if "/inheritance:r" in args:
|
|
82
|
+
self.acl[path] = self.acl[path].replace("ID;", ";").replace("D:AI", "D:PAI")
|
|
83
|
+
if "/grant:r" in args:
|
|
84
|
+
for g in args[args.index("/grant:r") + 1:]:
|
|
85
|
+
sid = g[1:].split(":")[0]
|
|
86
|
+
if f";;;{sid})" not in self.acl[path]:
|
|
87
|
+
self.acl[path] += f"(A;OICI;FA;;;{sid})"
|
|
88
|
+
for sw in ("/remove:g", "/remove:d"):
|
|
89
|
+
if sw in args:
|
|
90
|
+
sid = args[args.index(sw) + 1][1:]
|
|
91
|
+
import re
|
|
92
|
+
names = [sid] + [a for a, v in winacl._ALIASES.items() if v == sid] # icacls resolves aliases and SIDs alike
|
|
93
|
+
for n in names:
|
|
94
|
+
self.acl[path] = re.sub(r"\([^()]*;;;" + re.escape(n) + r"\)", "", self.acl[path])
|
|
95
|
+
return 0, ""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Decisions(unittest.TestCase):
|
|
99
|
+
def setUp(self):
|
|
100
|
+
winacl._me_cache.clear()
|
|
101
|
+
|
|
102
|
+
def tearDown(self):
|
|
103
|
+
winacl._me_cache.clear()
|
|
104
|
+
|
|
105
|
+
def test_private_path_is_reported_private(self):
|
|
106
|
+
with mock.patch.object(winacl, "_run", FakeIcacls({"p": PRIVATE})):
|
|
107
|
+
self.assertEqual(winacl.check("p").status, "private")
|
|
108
|
+
|
|
109
|
+
def test_exposed_path_names_who(self):
|
|
110
|
+
with mock.patch.object(winacl, "_run", FakeIcacls({"p": USERS_INHERITED})):
|
|
111
|
+
rep = winacl.check("p")
|
|
112
|
+
self.assertEqual((rep.status, rep.exposed), ("exposed", ["BUILTIN\\Users"]))
|
|
113
|
+
self.assertIn("BUILTIN\\Users", rep.detail)
|
|
114
|
+
|
|
115
|
+
def test_unknown_when_icacls_fails_and_never_raises(self):
|
|
116
|
+
with mock.patch.object(winacl, "_run", FakeIcacls({"p": PRIVATE}, fail=True)):
|
|
117
|
+
self.assertEqual(winacl.check("p").status, "unknown")
|
|
118
|
+
self.assertIsNone(winacl.tighten_if_exposed("p", True))
|
|
119
|
+
|
|
120
|
+
def test_tighten_removes_inherited_users_access(self):
|
|
121
|
+
fake = FakeIcacls({"p": USERS_INHERITED})
|
|
122
|
+
with mock.patch.object(winacl, "_run", fake):
|
|
123
|
+
self.assertTrue(winacl.tighten("p", True))
|
|
124
|
+
self.assertEqual(winacl.check("p").status, "private")
|
|
125
|
+
grant = [c for c in fake.calls if "/grant:r" in c][0]
|
|
126
|
+
self.assertIn(f"*{ME}:(OI)(CI)F", grant)
|
|
127
|
+
self.assertIn("*S-1-5-18:(OI)(CI)F", grant)
|
|
128
|
+
|
|
129
|
+
def test_grant_happens_before_inheritance_is_removed(self):
|
|
130
|
+
fake = FakeIcacls({"p": USERS_INHERITED})
|
|
131
|
+
with mock.patch.object(winacl, "_run", fake):
|
|
132
|
+
winacl.tighten("p", False)
|
|
133
|
+
order = [("grant" if "/grant:r" in c else "inherit" if "/inheritance:r" in c else "") for c in fake.calls]
|
|
134
|
+
self.assertLess(order.index("grant"), order.index("inherit"))
|
|
135
|
+
self.assertIn(f"*{ME}:F", [c for c in fake.calls if "/grant:r" in c][0])
|
|
136
|
+
|
|
137
|
+
def test_tighten_removes_everyone(self):
|
|
138
|
+
with mock.patch.object(winacl, "_run", FakeIcacls({"p": EVERYONE})):
|
|
139
|
+
self.assertTrue(winacl.tighten("p", False))
|
|
140
|
+
|
|
141
|
+
def test_already_private_is_left_alone(self):
|
|
142
|
+
fake = FakeIcacls({"p": PRIVATE})
|
|
143
|
+
with mock.patch.object(winacl, "_run", fake):
|
|
144
|
+
self.assertIsNone(winacl.tighten_if_exposed("p", True))
|
|
145
|
+
self.assertFalse([c for c in fake.calls if "/grant:r" in c or "/inheritance:r" in c])
|
|
146
|
+
|
|
147
|
+
def test_unknown_user_means_no_changes(self):
|
|
148
|
+
fake = FakeIcacls({"p": EVERYONE}, me="")
|
|
149
|
+
fake.me = "not-a-sid"
|
|
150
|
+
with mock.patch.object(winacl, "_run", fake):
|
|
151
|
+
self.assertFalse(winacl.tighten("p", True))
|
|
152
|
+
self.assertFalse([c for c in fake.calls if "/inheritance:r" in c])
|
|
153
|
+
|
|
154
|
+
def test_utf8_save_file_is_also_understood(self):
|
|
155
|
+
def run(args):
|
|
156
|
+
if args[0] == "whoami":
|
|
157
|
+
return 0, f'"h\\u","{ME}"'
|
|
158
|
+
out = args[args.index("/save") + 1]
|
|
159
|
+
open(out, "wb").write(("p\r\n" + PRIVATE + "\r\n").encode("utf-8"))
|
|
160
|
+
return 0, ""
|
|
161
|
+
with mock.patch.object(winacl, "_run", run):
|
|
162
|
+
self.assertEqual(winacl.check("p").status, "private")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Wiring(unittest.TestCase):
|
|
166
|
+
def test_new_state_dir_is_checked_on_windows_only_once(self):
|
|
167
|
+
from kneepad import util
|
|
168
|
+
d = os.path.join(tempfile.mkdtemp(), "state")
|
|
169
|
+
with mock.patch.object(util, "is_windows", return_value=True), mock.patch.object(winacl, "tighten_if_exposed") as t:
|
|
170
|
+
util.ensure_private_dir(d)
|
|
171
|
+
util.ensure_private_dir(d) # existing directory: no icacls on every hook call
|
|
172
|
+
self.assertEqual(t.call_count, 1)
|
|
173
|
+
|
|
174
|
+
def test_posix_never_calls_icacls(self):
|
|
175
|
+
from kneepad import util
|
|
176
|
+
d = os.path.join(tempfile.mkdtemp(), "state")
|
|
177
|
+
with mock.patch.object(winacl, "tighten_if_exposed") as t:
|
|
178
|
+
util.ensure_private_dir(d)
|
|
179
|
+
if os.name != "nt":
|
|
180
|
+
t.assert_not_called()
|
|
181
|
+
|
|
182
|
+
def test_hook_path_never_shells_out_to_icacls(self):
|
|
183
|
+
"""Creating the state costs one check on Windows; appending to an existing log (every hook call) costs none."""
|
|
184
|
+
from kneepad.audit import AuditLog
|
|
185
|
+
home = tempfile.mkdtemp()
|
|
186
|
+
log = AuditLog(os.path.join(home, "s"))
|
|
187
|
+
log.append("t", {"i": 0}) # creates the directory and the key
|
|
188
|
+
with mock.patch.object(winacl, "_run", return_value=(1, "")) as r:
|
|
189
|
+
for i in range(3):
|
|
190
|
+
log.append("t", {"i": i})
|
|
191
|
+
r.assert_not_called()
|
|
192
|
+
|
|
193
|
+
def test_doctor_reports_exposure_on_windows(self):
|
|
194
|
+
from kneepad import cli
|
|
195
|
+
home = tempfile.mkdtemp()
|
|
196
|
+
with mock.patch.object(cli.sys, "platform", "win32"), mock.patch.object(winacl, "check",
|
|
197
|
+
return_value=winacl.AclReport("exposed", ["Everyone"], "also accessible to Everyone")):
|
|
198
|
+
items = cli.run_doctor(home)
|
|
199
|
+
flat = {i[1]: i for i in items}
|
|
200
|
+
self.assertIs(flat["state directory is private"][0], False)
|
|
201
|
+
self.assertIn("Everyone", flat["state directory is private"][2])
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@unittest.skipUnless(sys.platform == "win32", "uses the real icacls")
|
|
205
|
+
class RealWindowsAcl(unittest.TestCase):
|
|
206
|
+
"""Windows replacements for the POSIX mode-bit tests (test_key_file_is_private and friends)."""
|
|
207
|
+
|
|
208
|
+
def setUp(self):
|
|
209
|
+
winacl._me_cache.clear()
|
|
210
|
+
self.root = tempfile.mkdtemp()
|
|
211
|
+
|
|
212
|
+
def why(self, path):
|
|
213
|
+
return "sddl=%s trace=%s" % (winacl.read_sddl(path), winacl.trace)
|
|
214
|
+
|
|
215
|
+
def test_a_directory_made_by_kneepad_is_private(self):
|
|
216
|
+
from kneepad import util
|
|
217
|
+
d = os.path.join(self.root, "state")
|
|
218
|
+
util.ensure_private_dir(d)
|
|
219
|
+
self.assertEqual(winacl.check(d).status, "private", winacl.check(d).detail)
|
|
220
|
+
|
|
221
|
+
def test_exposure_is_detected_then_removed(self):
|
|
222
|
+
d = os.path.join(self.root, "open")
|
|
223
|
+
os.makedirs(d)
|
|
224
|
+
subprocess.run(["icacls", d, "/grant", "*S-1-1-0:(OI)(CI)R"], capture_output=True)
|
|
225
|
+
rep = winacl.check(d)
|
|
226
|
+
self.assertEqual(rep.status, "exposed", rep.detail)
|
|
227
|
+
self.assertTrue(winacl.tighten(d, True), self.why(d))
|
|
228
|
+
self.assertEqual(winacl.check(d).status, "private", self.why(d))
|
|
229
|
+
|
|
230
|
+
def test_the_audit_key_is_private(self):
|
|
231
|
+
from kneepad.audit import AuditLog
|
|
232
|
+
log = AuditLog(os.path.join(self.root, "kh"))
|
|
233
|
+
log.ensure_key()
|
|
234
|
+
self.assertEqual(winacl.check(log.key_path).status, "private", winacl.check(log.key_path).detail)
|
|
235
|
+
|
|
236
|
+
def test_an_exposed_key_is_tightened_by_init(self):
|
|
237
|
+
from kneepad import cli
|
|
238
|
+
from kneepad.audit import AuditLog
|
|
239
|
+
home = os.path.join(self.root, "kh2")
|
|
240
|
+
with mock.patch.dict(os.environ, {"KNEEPAD_HOME": home}):
|
|
241
|
+
AuditLog(home).ensure_key()
|
|
242
|
+
subprocess.run(["icacls", os.path.join(home, "key"), "/grant", "*S-1-1-0:R"], capture_output=True)
|
|
243
|
+
self.assertEqual(winacl.check(os.path.join(home, "key")).status, "exposed")
|
|
244
|
+
self.assertEqual(cli.main(["init"]), 0)
|
|
245
|
+
self.assertEqual(winacl.check(os.path.join(home, "key")).status, "private", self.why(os.path.join(home, "key")))
|
|
246
|
+
|
|
247
|
+
def test_doctor_marks_private_state_ok(self):
|
|
248
|
+
from kneepad import cli
|
|
249
|
+
home = os.path.join(self.root, "kh3")
|
|
250
|
+
with mock.patch.dict(os.environ, {"KNEEPAD_HOME": home}):
|
|
251
|
+
self.assertEqual(cli.main(["init"]), 0)
|
|
252
|
+
flat = {i[1]: i for i in cli.run_doctor(home)}
|
|
253
|
+
self.assertIs(flat["state directory is private"][0], True)
|
|
254
|
+
self.assertIs(flat["audit key is private"][0], True)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
if __name__ == "__main__":
|
|
258
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|