contextlock 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ """ABOM-007: settings, servers and commands that grant an agent more than it needs."""
2
+
3
+ import re
4
+ import shlex
5
+ from collections.abc import Iterator, Sequence
6
+
7
+ from agentbom.models import (
8
+ Artifact,
9
+ Finding,
10
+ Location,
11
+ McpServer,
12
+ RuleId,
13
+ Settings,
14
+ Severity,
15
+ StdioLaunch,
16
+ )
17
+ from agentbom.rules._surfaces import SeverityTable, line_of, surfaces
18
+
19
+ _RULE: RuleId = "ABOM-007"
20
+
21
+ # Entries that allow every command, every MCP tool or every web domain.
22
+ _BROAD_ALLOW = frozenset(
23
+ {
24
+ "*",
25
+ "Bash",
26
+ "Bash(*)",
27
+ "Bash(**)",
28
+ "Bash(:*)",
29
+ "Bash(*:*)",
30
+ "Bash(* *)",
31
+ "mcp__*",
32
+ "WebFetch",
33
+ "WebFetch(*)",
34
+ "WebFetch(domain:*)",
35
+ }
36
+ )
37
+ # Compared after lowercasing, turning backslashes into slashes and dropping trailing slashes,
38
+ # so "/" becomes "" and C:\ becomes "c:".
39
+ _BROAD_ROOTS = frozenset(
40
+ {
41
+ "",
42
+ "~",
43
+ "$home",
44
+ "${home}",
45
+ "%userprofile%",
46
+ "$env:userprofile",
47
+ "${env:userprofile}",
48
+ "${userhome}",
49
+ "/home",
50
+ "/users",
51
+ "/root",
52
+ }
53
+ )
54
+ _DRIVE_ROOT = re.compile(r"[a-z]:(/users)?")
55
+ _FILESYSTEM_PACKAGE = re.compile(
56
+ r"(?:^|/)(?:@modelcontextprotocol/server-filesystem|mcp-server-filesystem)(?:[@=].*)?",
57
+ re.IGNORECASE,
58
+ )
59
+
60
+ _BYPASS_SEVERITY: SeverityTable = {"executable": "high"}
61
+ _BYPASS_FLAG = re.compile(
62
+ r"(?<![\w-])(?:--dangerously-skip-permissions|--dangerously-bypass-approvals-and-sandbox"
63
+ r"|--permission-mode[= ]+[\"']?bypassPermissions|--yolo|--allow-all-tools)(?![\w-])",
64
+ re.IGNORECASE,
65
+ )
66
+ # A bypass flag counts only on a command line that runs an agent CLI, so a guard script
67
+ # that greps for the flag is not a finding.
68
+ _AGENT_CLI = re.compile(
69
+ r"(?<![\w-])(?:claude|codex|gemini|copilot|cursor-agent|qwen)", re.IGNORECASE
70
+ )
71
+ _CONTINUATION = re.compile(r"[\\`]\n")
72
+ _COMMENT = re.compile(r"\s*(?:#|//|::|rem\s)", re.IGNORECASE)
73
+
74
+ _SETTINGS_FIX = "allow only the specific commands and tools the project needs"
75
+
76
+
77
+ def _is_broad_root(path: str) -> bool:
78
+ stripped = path.strip().strip("\"'")
79
+ if not stripped:
80
+ return False
81
+ normalized = stripped.replace("\\", "/").rstrip("/").lower()
82
+ return normalized in _BROAD_ROOTS or _DRIVE_ROOT.fullmatch(normalized) is not None
83
+
84
+
85
+ def _finding(
86
+ artifact: Artifact, severity: Severity, message: str, fix: str, line: int | None = None
87
+ ) -> Finding:
88
+ return Finding(
89
+ rule_id=_RULE,
90
+ severity=severity,
91
+ confidence="high",
92
+ message=message,
93
+ location=Location(path=artifact.source.path, line=line),
94
+ artifact_id=artifact.id,
95
+ fix=fix,
96
+ )
97
+
98
+
99
+ def _settings_findings(settings: Settings) -> Iterator[Finding]:
100
+ if settings.default_mode == "bypassPermissions":
101
+ yield _finding(
102
+ settings,
103
+ "high",
104
+ "defaultMode is bypassPermissions",
105
+ 'set defaultMode to "default" or "acceptEdits"; Claude Code ignores '
106
+ "bypassPermissions in project settings since v2.1.257, but older clients honor it",
107
+ )
108
+ for entry in settings.allow:
109
+ if entry.strip() in _BROAD_ALLOW:
110
+ yield _finding(
111
+ settings, "medium", f"permissions.allow grants {entry.strip()}", _SETTINGS_FIX
112
+ )
113
+ if settings.enable_all_project_mcp_servers is True:
114
+ yield _finding(
115
+ settings,
116
+ "medium",
117
+ "enableAllProjectMcpServers auto-approves every server in .mcp.json",
118
+ "remove enableAllProjectMcpServers and list approved servers in enabledMcpjsonServers",
119
+ )
120
+ for directory in settings.additional_directories:
121
+ if _is_broad_root(directory):
122
+ yield _finding(
123
+ settings,
124
+ "medium",
125
+ f"permissions.additionalDirectories grants access to {directory.strip()}",
126
+ "limit additionalDirectories to the directories the project needs",
127
+ )
128
+
129
+
130
+ def _argv(launch: StdioLaunch) -> list[str]:
131
+ command = launch.command.strip()
132
+ try:
133
+ words = shlex.split(command) if any(c.isspace() for c in command) else [command]
134
+ except ValueError:
135
+ words = command.split()
136
+ return [*words, *launch.args]
137
+
138
+
139
+ def _filesystem_root(server: McpServer, launch: StdioLaunch) -> Finding | None:
140
+ argv = _argv(launch)
141
+ package = next(
142
+ (i for i, word in enumerate(argv) if _FILESYSTEM_PACKAGE.search(word.replace("\\", "/"))),
143
+ None,
144
+ )
145
+ if package is None:
146
+ return None
147
+ for root in argv[package + 1 :]:
148
+ if not root.startswith("-") and _is_broad_root(root):
149
+ return _finding(
150
+ server,
151
+ "medium",
152
+ f'filesystem server "{server.name}" is rooted at {root.strip()}',
153
+ 'root the filesystem server at the project directory, such as "."',
154
+ )
155
+ return None
156
+
157
+
158
+ def _bypass_findings(artifact: Artifact) -> Iterator[Finding]:
159
+ for surface in surfaces(artifact):
160
+ severity = _BYPASS_SEVERITY.get(surface.context)
161
+ if severity is None:
162
+ continue
163
+ # Same length, so offsets still point into surface.text.
164
+ text = _CONTINUATION.sub(" ", surface.text)
165
+ start = 0
166
+ for line in text.split("\n"):
167
+ flag = _BYPASS_FLAG.search(line)
168
+ if flag and not _COMMENT.match(line) and _AGENT_CLI.search(line):
169
+ offset = start + flag.start()
170
+ yield _finding(
171
+ artifact,
172
+ severity,
173
+ f"{surface.field} runs an agent with permission checks disabled",
174
+ "drop the flag and allow only the tools the automation needs",
175
+ line=line_of(surface, offset),
176
+ )
177
+ break
178
+ start += len(line) + 1
179
+
180
+
181
+ class OverBroadPermissions:
182
+ rule_id: RuleId = _RULE
183
+
184
+ def run(self, artifacts: Sequence[Artifact]) -> Iterator[Finding]:
185
+ for artifact in artifacts:
186
+ if isinstance(artifact, Settings):
187
+ yield from _settings_findings(artifact)
188
+ if isinstance(artifact, McpServer) and isinstance(artifact.launch, StdioLaunch):
189
+ root = _filesystem_root(artifact, artifact.launch)
190
+ if root is not None:
191
+ yield root
192
+ yield from _bypass_findings(artifact)
@@ -0,0 +1,160 @@
1
+ """ABOM-008: hooks that run a shell command on their own, when a session starts or a
2
+ prompt is submitted, from files the repository controls."""
3
+
4
+ import re
5
+ from collections.abc import Iterator, Sequence
6
+
7
+ from agentbom.models import Artifact, Finding, Hook, HookShell, Location, RuleId, Script
8
+
9
+ # Event names are case-sensitive and differ per agent.
10
+ _AUTO_RUN_EVENTS: frozenset[str] = frozenset(
11
+ {
12
+ # Claude Code and Codex. Setup runs on `claude --init` and `--maintenance`.
13
+ "SessionStart",
14
+ "Setup",
15
+ "UserPromptSubmit",
16
+ # Cursor
17
+ "sessionStart",
18
+ "beforeSubmitPrompt",
19
+ "workspaceOpen",
20
+ # Copilot (sessionStart is shared with Cursor)
21
+ "userPromptSubmitted",
22
+ }
23
+ )
24
+
25
+ # Command names are case-sensitive except PowerShell's. Short names need an
26
+ # argument after them, so "GH Token" or `const nc = 1` is not a command. `nc -U`
27
+ # talks to a local Unix socket, and `conn.fetch(` is a method, not the network fetch.
28
+ _NETWORK_COMMAND = re.compile(
29
+ r"(?<![\w.$-])(?:curl|wget|(?i:Invoke-WebRequest|iwr|irm|Invoke-RestMethod)|scp"
30
+ r"|(?:ssh|gh)(?=[ \t]+[\w@.-])|(?:nc|ncat)(?=[ \t]+[\w@.-])(?![ \t]+-U\b)"
31
+ r"|git[ \t]+(?:clone|fetch|pull)|npm[ \t]+(?:i|install|ci)|pnpm[ \t]+(?:i|install)"
32
+ r"|yarn(?:[ \t]+install)?(?=[ \t]*(?:$|[;&|)\"'`]))|pip3?[ \t]+install"
33
+ r"|uv[ \t]+(?:sync|pip[ \t]+install)|npx|bunx|uvx"
34
+ r"|brew[ \t]+install|apt(?:-get)?[ \t]+install)(?![\w-])",
35
+ re.MULTILINE,
36
+ )
37
+ _NETWORK_CALL = re.compile(
38
+ r"(?:(?<![\w.$])|(?<=\bglobalThis\.)|(?<=\bwindow\.)|(?<=\bself\.))fetch\("
39
+ r"|\bhttps?\.(?:request|get)\(|\brequests\.(?:get|post|put|patch|delete|head"
40
+ r"|request|Session)\b|\burllib\b|\bhttpx\b|\baxios\b",
41
+ )
42
+ # The repository root, found the usual way, is a path and not a hidden command.
43
+ _REPO_ROOT = re.compile(
44
+ r"\$\(\s*git rev-parse --show-toplevel\s*\)|`\s*git rev-parse --show-toplevel\s*`"
45
+ )
46
+ _LOCAL_URL = re.compile(r"^https?://(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?:[:/]|$)", re.I)
47
+ _PRINT_COMMANDS = frozenset({"echo", "printf", "write-host", "write-output", "true", ":"})
48
+ _FIX = "make the hook opt-in, or keep it to a reviewed script with no network access"
49
+
50
+
51
+ def _substitutes(shell: HookShell, command: str) -> bool:
52
+ command = _REPO_ROOT.sub("", command)
53
+ # In PowerShell a backtick escapes the next character; only $( runs a command.
54
+ return "$(" in command or (shell != "powershell" and "`" in command)
55
+
56
+
57
+ def _prints_only(shell: HookShell, command: str) -> bool:
58
+ """Every command in the line prints a message and nothing runs or gets written."""
59
+ if _substitutes(shell, command):
60
+ return False
61
+ segments = [""]
62
+ quote: str | None = None
63
+ escaped = False
64
+ for char in command:
65
+ if escaped:
66
+ escaped = False
67
+ elif char == "\\" and quote != "'":
68
+ escaped = True
69
+ elif quote is not None:
70
+ if char == quote:
71
+ quote = None
72
+ elif char in "'\"":
73
+ quote = char
74
+ elif char in "<>":
75
+ return False
76
+ elif char in ";&|\n":
77
+ segments.append("")
78
+ continue
79
+ segments[-1] += char
80
+ words = [segment.split(maxsplit=1) for segment in segments]
81
+ return all(not w or w[0].lower() in _PRINT_COMMANDS for w in words)
82
+
83
+
84
+ def _scripts_run(command: str, scripts: Sequence[Script]) -> list[Script]:
85
+ text = command.replace("\\", "/")
86
+ return [
87
+ script
88
+ for script in scripts
89
+ if re.search(rf"(?:^|[\s\"'/=]){re.escape(script.source.path)}(?=$|[\s\"';|&)])", text)
90
+ ]
91
+
92
+
93
+ def _networked(script: Script) -> bool:
94
+ body = script.body
95
+ return _NETWORK_COMMAND.search(body) is not None or _NETWORK_CALL.search(body) is not None
96
+
97
+
98
+ def _command_finding(hook: Hook, scripts: Sequence[Script]) -> Finding | None:
99
+ if all(_prints_only(shell, command) for shell, command in hook.commands.items()):
100
+ return None
101
+ reasons: list[str] = []
102
+ via = sorted(
103
+ {
104
+ s.source.path
105
+ for c in hook.commands.values()
106
+ for s in _scripts_run(c, scripts)
107
+ if _networked(s)
108
+ }
109
+ )
110
+ if via or any(_NETWORK_COMMAND.search(c) for c in hook.commands.values()):
111
+ reasons.append("network access")
112
+ if any(_substitutes(shell, c) for shell, c in hook.commands.items()):
113
+ reasons.append("command substitution")
114
+ message = f"{hook.name} hook runs a shell command automatically"
115
+ if reasons:
116
+ message += " with " + " and ".join(reasons)
117
+ if via:
118
+ message += f" (via {', '.join(via)})"
119
+ return Finding(
120
+ rule_id="ABOM-008",
121
+ severity="high" if reasons else "medium",
122
+ confidence="medium",
123
+ message=message,
124
+ location=Location(path=hook.source.path),
125
+ artifact_id=hook.id,
126
+ fix=_FIX,
127
+ )
128
+
129
+
130
+ def _http_finding(hook: Hook) -> Finding | None:
131
+ if hook.url is None or _LOCAL_URL.match(hook.url):
132
+ return None
133
+ return Finding(
134
+ rule_id="ABOM-008",
135
+ severity="medium",
136
+ confidence="medium",
137
+ message=f"{hook.name} hook calls an external URL automatically",
138
+ location=Location(path=hook.source.path),
139
+ artifact_id=hook.id,
140
+ fix=_FIX,
141
+ )
142
+
143
+
144
+ class AutoRunHooks:
145
+ rule_id: RuleId = "ABOM-008"
146
+
147
+ def run(self, artifacts: Sequence[Artifact]) -> Iterator[Finding]:
148
+ scripts = [a for a in artifacts if isinstance(a, Script)]
149
+ for artifact in artifacts:
150
+ if not isinstance(artifact, Hook) or artifact.event not in _AUTO_RUN_EVENTS:
151
+ continue
152
+ match artifact.handler_type:
153
+ case "command" if artifact.commands:
154
+ finding = _command_finding(artifact, scripts)
155
+ case "http":
156
+ finding = _http_finding(artifact)
157
+ case _:
158
+ finding = None
159
+ if finding is not None:
160
+ yield finding
@@ -0,0 +1,166 @@
1
+ """ABOM-009: prose that tells the agent to drop earlier instructions or hide what it does."""
2
+
3
+ import re
4
+ from collections.abc import Callable, Iterator, Sequence
5
+ from dataclasses import dataclass
6
+
7
+ from agentbom.models import Artifact, Finding, Location, RuleId
8
+ from agentbom.rules._surfaces import SeverityTable, line_of, surfaces
9
+
10
+ _SEVERITY: SeverityTable = {"skill_prose": "medium", "rules_prose": "medium"}
11
+
12
+ # Up to three filler words between key terms, never crossing the end of a sentence.
13
+ _GAP = r"(?:[^\w.!?]+\w+){0,3}?[^\w.!?]+"
14
+ _AUDIENCE = r"(?:the\s+)?(?:user|human|developer|operator)s?\b(?!\Ws\b)"
15
+ _NEGATION_BEFORE = re.compile(r"(?:\b(?:never|not|no|cannot)|n\Wt)\s+(?:\w+\s+)?$", re.IGNORECASE)
16
+ # What may sit between the start of a clause and an imperative verb: list markers and
17
+ # emphasis, or a word that introduces an instruction.
18
+ _CLAUSE_START = re.compile(
19
+ r"(?:^[\s#>*_+\-\d.)]*|[;:,(]\s*|\b(?:and|then|also|always|you|should|must|please|to|just|now)\s+)$",
20
+ re.IGNORECASE | re.MULTILINE,
21
+ )
22
+
23
+ _SENTENCE_END = re.compile(
24
+ r"(?<!\be\.g)(?<!\bi\.e)(?<!\betc)[.!?](?=\s|$)|\n\s*\n|\n(?=\s*(?:[-*+]|\d+[.)]|#{1,6})\s)"
25
+ )
26
+ _ILLUSTRATIVE = re.compile(
27
+ r"\b(?:for example|for instance|e\.g\.|such as|attackers?|malicious|prompt injection|injected"
28
+ r"|jailbreak attempts?|watch out|be wary|beware|detect|refuse)",
29
+ re.IGNORECASE,
30
+ )
31
+ _FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
32
+ _QUOTED = re.compile(r"`[^`\n]*`|\"[^\"\n]*\"|\u201c[^\u201d\n]*\u201d")
33
+
34
+
35
+ def _not_negated(text: str, start: int) -> bool:
36
+ return _NEGATION_BEFORE.search(text, max(0, start - 40), start) is None
37
+
38
+
39
+ def _at_clause_start(text: str, start: int) -> bool:
40
+ line_start = text.rfind("\n", 0, start) + 1
41
+ return _CLAUSE_START.search(text, line_start, start) is not None
42
+
43
+
44
+ def _always(text: str, start: int) -> bool:
45
+ return True
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class _Pattern:
50
+ regex: re.Pattern[str]
51
+ # A context check on the text before the match.
52
+ applies: Callable[[str, int], bool] = _always
53
+
54
+
55
+ def _pattern(regex: str, applies: Callable[[str, int], bool] = _always) -> _Pattern:
56
+ return _Pattern(re.compile(regex, re.IGNORECASE), applies)
57
+
58
+
59
+ # Each family yields at most one finding per field, labelled "<field> tells the agent to <label>".
60
+ _FAMILIES: dict[str, tuple[_Pattern, ...]] = {
61
+ "ignore earlier instructions": (
62
+ _pattern(
63
+ rf"\b(?:ignore|disregard|forget|override|bypass){_GAP}"
64
+ rf"(?:previous|prior|earlier|above|preceding|original|system|developer){_GAP}"
65
+ r"(?:instructions?|rules?|guidelines?|prompts?|directives?|messages?)\b",
66
+ _not_negated,
67
+ ),
68
+ ),
69
+ "take on an unrestricted persona": (
70
+ _pattern(
71
+ r"\byou are (?:now|no longer)(?:[^\w.!?]+\w+){0,4}?[^\w.!?]+"
72
+ r"(?:(?-i:DAN)\b|jailbroken|unrestricted|without (?:any )?restrictions)"
73
+ ),
74
+ _pattern(r"\bdeveloper mode enabled\b"),
75
+ ),
76
+ "hide its actions from the user": (
77
+ _pattern(
78
+ r"\b(?:do not|don\Wt|never|without)\s+"
79
+ r"(?:tell|telling|inform|informing|notify|notifying|mention|mentioning|alert|alerting)"
80
+ rf"\s+(?:this\s+|it\s+|anything\s+)?(?:to\s+)?{_AUDIENCE}(?!\s+to\b)"
81
+ ),
82
+ _pattern(
83
+ r"\b(?:do not|don\Wt|never|without)\s+(?:reveal|revealing|show|showing)\s+"
84
+ rf"(?:this|it|anything|these|that)\s+(?:to\s+)?{_AUDIENCE}"
85
+ ),
86
+ _pattern(
87
+ r"\b(?:hide|conceal)\s+(?:this|that|these|everything|anything"
88
+ r"|(?:the|these|those|your|any|all)\s+(?:\w+\s+)?"
89
+ r"(?:actions?|steps?|changes?|commands?|edits?|modifications?|activity|output))\b"
90
+ rf"[^.\n]{{0,20}}?\bfrom\s+{_AUDIENCE}"
91
+ ),
92
+ _pattern(r"\b(?:hide|conceal)\s+your\s+(?:actions|activity|tracks)\b"),
93
+ _pattern(
94
+ r"\bkeep\s+(?:this|it|that|these|everything)\s+(?:a\s+)?secret\s+from\s+" + _AUDIENCE
95
+ ),
96
+ _pattern(
97
+ r"\b(?:silently|secretly|covertly)\s+"
98
+ r"(?:run|execute|send|upload|modify|delete|install)\b",
99
+ _at_clause_start,
100
+ ),
101
+ ),
102
+ }
103
+
104
+
105
+ def _mask_quoted(text: str) -> str:
106
+ """Blank out fenced blocks, inline code and double-quoted spans, keeping every offset."""
107
+ lines = text.split("\n")
108
+ fence: str | None = None
109
+ for i, line in enumerate(lines):
110
+ opening = _FENCE.match(line)
111
+ if fence is not None:
112
+ if opening and opening.group(1)[0] == fence[0] and len(opening.group(1)) >= len(fence):
113
+ fence = None
114
+ lines[i] = " " * len(line)
115
+ elif opening:
116
+ fence = opening.group(1)
117
+ lines[i] = " " * len(line)
118
+ else:
119
+ lines[i] = _QUOTED.sub(lambda quoted: " " * len(quoted.group()), line)
120
+ return "\n".join(lines)
121
+
122
+
123
+ def _sentence(text: str, start: int, end: int) -> str:
124
+ before = 0
125
+ for boundary in _SENTENCE_END.finditer(text, 0, start):
126
+ before = boundary.end()
127
+ after = _SENTENCE_END.search(text, end)
128
+ return text[before : after.start() if after else len(text)]
129
+
130
+
131
+ def _first_match(text: str, masked: str, patterns: tuple[_Pattern, ...]) -> int | None:
132
+ found: list[int] = []
133
+ for pattern in patterns:
134
+ for match in pattern.regex.finditer(masked):
135
+ if pattern.applies(masked, match.start()) and not _ILLUSTRATIVE.search(
136
+ _sentence(text, match.start(), match.end())
137
+ ):
138
+ found.append(match.start())
139
+ break
140
+ return min(found, default=None)
141
+
142
+
143
+ class InstructionOverride:
144
+ rule_id: RuleId = "ABOM-009"
145
+
146
+ def run(self, artifacts: Sequence[Artifact]) -> Iterator[Finding]:
147
+ for artifact in artifacts:
148
+ for surface in surfaces(artifact):
149
+ severity = _SEVERITY.get(surface.context)
150
+ if severity is None:
151
+ continue
152
+ masked = _mask_quoted(surface.text)
153
+ for label, patterns in _FAMILIES.items():
154
+ start = _first_match(surface.text, masked, patterns)
155
+ if start is None:
156
+ continue
157
+ yield Finding(
158
+ rule_id=self.rule_id,
159
+ severity=severity,
160
+ confidence="low",
161
+ message=f"{surface.field} tells the agent to {label}",
162
+ location=Location(path=artifact.source.path, line=line_of(surface, start)),
163
+ artifact_id=artifact.id,
164
+ fix="remove instructions that override earlier rules or hide actions "
165
+ "from the user",
166
+ )