spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / plugins / security-guidance / hooks / patterns.py
345 lines · 17.1 KBRaw
1"""
2Regex-based security pattern definitions for the security-guidance plugin.
3
4Pure data + one pure helper. No env-var reads, no I/O, no debug_log — kept
5side-effect-free so it can be imported in isolation.
6"""
7from enum import IntEnum
8
9
10_JS_EXTS = (".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts", ".vue", ".svelte")
11_PY_EXTS = (".py", ".pyi", ".ipynb")
12_DOC_EXTS = (".md", ".mdx", ".txt", ".rst", ".json", ".yaml", ".yml")
13
14
15_UNSAFE_DESERIALIZATION_REMINDER = """⚠️ Security Warning: Loading pickle data (or equivalents: cPickle, cloudpickle, dill, marshal, shelve, joblib, pandas.read_pickle, numpy with allow_pickle=True) from untrusted sources allows arbitrary code execution.
16
17For simple data, prefer JSON or msgspec. For typed objects, prefer a schema-validated deserializer (msgspec.Struct, pydantic, marshmallow) that constructs only declared types.
18
19If this is safe or is explicitly needed, briefly document that in a comment before continuing."""
20
21_UNSAFE_YAML_LOAD_REMINDER = """⚠️ Security Warning: yaml.load() / yaml.unsafe_load() execute arbitrary Python via !!python/object tags.
22
23Use yaml.safe_load() if the file only contains simple data structures (dicts, lists, strings, numbers). If you need typed objects, parse with safe_load and validate the result against a schema (pydantic, msgspec, marshmallow) — never use a custom Loader that constructs arbitrary types."""
24
25_UNSAFE_TORCH_LOAD_REMINDER = """⚠️ Security Warning: torch.load() defaults to weights_only=False, which unpickles arbitrary Python objects and allows arbitrary code execution.
26
27If the file only contains tensors and simple data structures, pass weights_only=True (or set TORCH_FORCE_WEIGHTS_ONLY_LOAD=1)."""
28
29# Security patterns configuration
30SECURITY_PATTERNS = [
31 {
32 "ruleName": "github_actions_workflow",
33 "path_check": lambda path: ".github/workflows/" in path
34 and (path.endswith(".yml") or path.endswith(".yaml")),
35 "reminder": """⚠️ Security Warning: You are editing a GitHub Actions workflow file. Be aware of these security risks:
36
371. **Command Injection**: Never use untrusted input (like issue titles, PR descriptions, commit messages) directly in run: commands without proper escaping
382. **Use environment variables**: Instead of ${{ github.event.issue.title }}, use env: with proper quoting
393. **Review the guide**: https://github.blog/security/vulnerability-research/how-to-catch-github-actions-workflow-injections-before-attackers-do/
40
41Example of UNSAFE pattern to avoid:
42run: echo "${{ github.event.issue.title }}"
43
44Example of SAFE pattern:
45env:
46 TITLE: ${{ github.event.issue.title }}
47run: echo "$TITLE"
48
49Other risky inputs to be careful with:
50- github.event.issue.body
51- github.event.pull_request.title
52- github.event.pull_request.body
53- github.event.comment.body
54- github.event.review.body
55- github.event.review_comment.body
56- github.event.pages.*.page_name
57- github.event.commits.*.message
58- github.event.head_commit.message
59- github.event.head_commit.author.email
60- github.event.head_commit.author.name
61- github.event.commits.*.author.email
62- github.event.commits.*.author.name
63- github.event.pull_request.head.ref
64- github.event.pull_request.head.label
65- github.event.pull_request.head.repo.default_branch
66- github.event.client_payload.* (repository_dispatch events — attacker can set any field)
67
684. **Ref injection**: Never use untrusted input in `ref:` parameters of `actions/checkout`. For `client_payload.pr_number`, validate it matches `^[0-9]+$` before using in `ref: refs/pull/${{ ... }}/head`
69- github.head_ref""",
70 },
71 {
72 "ruleName": "child_process_exec",
73 # Gate to JS/TS files — bare `exec(` otherwise fires on Python's
74 # exec() and on prose/docstrings mentioning exec.
75 "path_filter": lambda p: p.endswith(_JS_EXTS),
76 "substrings": ["child_process.exec", "execSync("],
77 "regex": r"(?<![a-zA-Z0-9_\.])exec\(",
78 "reminder": """⚠️ Security Warning: Using child_process.exec() can lead to command injection vulnerabilities.
79
80exec() runs the command string through a shell, so any user input interpolated into it can inject arbitrary commands. Prefer child_process.execFile() (or spawn()) with an argument array instead of building a shell string.
81
82Instead of:
83 exec(`command ${userInput}`)
84
85Use:
86 import { execFile } from 'node:child_process'
87 execFile('command', [userInput], callback)
88
89Why execFile/spawn with an argument array is safer:
90- No shell is involved, so shell metacharacters in arguments are not interpreted
91- Arguments are passed directly to the program rather than interpolated into a command string
92
93Only use exec() if you absolutely need shell features and the input is guaranteed to be safe.""",
94 },
95 {
96 "ruleName": "new_function_injection",
97 "substrings": ["new Function"],
98 "reminder": "\u26a0\ufe0f Security Warning: Using new Function() with string interpolation is a CODE INJECTION vulnerability. If any variable is concatenated or interpolated into the function body string, an attacker controlling that variable can execute arbitrary code. Use safe alternatives: for property access use obj[key] or array.reduce((o, k) => o[k], root); for computation use a safe expression parser. NEVER interpolate untrusted strings into new Function() bodies.",
99 },
100 {
101 "ruleName": "eval_injection",
102 # Lookbehind excludes `.` so method calls like PyTorch model.eval(),
103 # redis.eval(), spec.eval() don't match. Skip doc/prose files.
104 "path_filter": lambda p: not p.endswith(_DOC_EXTS),
105 "regex": r"(?<![a-zA-Z0-9_\.])eval\(",
106 "reminder": "⚠️ Security Warning: eval() executes arbitrary code and is a major security risk. Use JSON.parse() for data, ast.literal_eval() for Python literals, or a safe expression parser. If this is safe or is explicitly needed, briefly document that in a comment before continuing.",
107 },
108 {
109 "ruleName": "react_dangerously_set_html",
110 "substrings": ["dangerouslySetInnerHTML"],
111 "reminder": "⚠️ Security Warning: dangerouslySetInnerHTML can lead to XSS vulnerabilities if used with untrusted content. Ensure all content is properly sanitized using an HTML sanitizer library like DOMPurify, or use safe alternatives.",
112 },
113 {
114 "ruleName": "document_write_xss",
115 "substrings": ["document.write"],
116 "reminder": "⚠️ Security Warning: document.write() can be exploited for XSS attacks and has performance issues. Use DOM manipulation methods like createElement() and appendChild() instead.",
117 },
118 {
119 "ruleName": "innerHTML_xss",
120 "substrings": [".innerHTML =", ".innerHTML="],
121 "reminder": "⚠️ Security Warning: Setting innerHTML with untrusted content can lead to XSS vulnerabilities. Use textContent for plain text or safe DOM methods for HTML content. If you need HTML support, consider using an HTML sanitizer library such as DOMPurify.",
122 },
123 {
124 "ruleName": "pickle_deserialization",
125 # Match deserialization only (load/loads/Unpickler). pickle.dump is
126 # not the RCE surface. `pkl_load` needs a word boundary so similarly
127 # named safe loaders don't match.
128 "path_filter": lambda p: p.endswith(_PY_EXTS),
129 "regex": r"(?<![a-zA-Z0-9_])pickle\.(loads?|Unpickler)\b|(?<![a-zA-Z0-9_])pkl_load\(",
130 "reminder": _UNSAFE_DESERIALIZATION_REMINDER,
131 },
132 {
133 "ruleName": "os_system_injection",
134 "path_filter": lambda p: p.endswith(_PY_EXTS),
135 "regex": r"\bos\.system\s*\(",
136 "substrings": ["from os import system"],
137 "reminder": "⚠️ Security Warning: os.system() runs a shell and is a command-injection sink. Use subprocess.run([...]) with a list of arguments instead. If this is safe or is explicitly needed, briefly document that in a comment before continuing.",
138 },
139 {
140 "ruleName": "python_subprocess_shell",
141 "regex": r"subprocess\.(?:run|call|Popen|check_output|check_call)\(.*shell\s*=\s*True",
142 "reminder": """⚠️ Security Warning: Using subprocess with shell=True enables command injection.
143
144UNSAFE:
145 subprocess.run(f"ls {user_input}", shell=True)
146 subprocess.call("grep " + pattern, shell=True)
147
148SAFE - pass arguments as a list without shell:
149 subprocess.run(["ls", user_input])
150 subprocess.call(["grep", pattern])
151
152When arguments are passed as a list without shell=True, special characters cannot be interpreted as shell metacharacters.""",
153 },
154 # =====================================================================
155 # Go-specific security patterns
156 # =====================================================================
157 {
158 "ruleName": "go_exec_shell_injection",
159 # Detect exec.Command with shell invocation (sh, bash, /bin/sh, /bin/bash)
160 "regex": r'exec\.Command\(\s*"(?:sh|bash|/bin/sh|/bin/bash)"',
161 "reminder": """⚠️ Security Warning: Using exec.Command with a shell interpreter (sh/bash) enables command injection.
162
163UNSAFE:
164 exec.Command("sh", "-c", "ping -c 1 " + host)
165 exec.Command("bash", "-c", fmt.Sprintf("df -h %s", path))
166
167SAFE - pass arguments directly without a shell:
168 exec.Command("ping", "-c", "1", host)
169 exec.Command("df", "-h", path)
170
171When arguments are passed directly (not through a shell), special characters in user input cannot be interpreted as shell metacharacters. This prevents command injection entirely.
172
173Additionally, validate user inputs:
174- For hostnames/IPs: use net.ParseIP() or a hostname regex
175- For file paths: use filepath.Clean() and verify the result is within an allowed directory
176- For numeric values: parse to int/float first""",
177 },
178 {
179 "ruleName": "unsafe_yaml_load",
180 "regex": r"\byaml\.load\s*\((?![^)\n]{0,80}\bSafe)",
181 "reminder": _UNSAFE_YAML_LOAD_REMINDER,
182 },
183 {
184 "ruleName": "node_createcipher_no_iv",
185 "regex": r"\bcrypto\.(createCipher|createDecipher)\b",
186 "reminder": "⚠️ Security Warning: Use crypto.createCipheriv() / createDecipheriv(). createCipher was removed in Node 22 and derives the key insecurely (no IV, MD5-based KDF).",
187 },
188 {
189 "ruleName": "aes_ecb_mode",
190 "regex": r"\bAES\.MODE_ECB\b|\bmodes\.ECB\s*\(|[\x22\x27]aes-\d+-ecb[\x22\x27]",
191 "reminder": "⚠️ Security Warning: Use AES-GCM or AES-CBC with HMAC. ECB mode leaks plaintext structure (identical blocks encrypt to identical ciphertext).",
192 },
193 {
194 "ruleName": "tls_verification_disabled",
195 "regex": r"\bverify\s*=\s*False\b|rejectUnauthorized\s*:\s*false|InsecureSkipVerify\s*:\s*true|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*[\x22\x27]?0|ssl\._create_unverified_context|check_hostname\s*=\s*False",
196 "reminder": "⚠️ Security Warning: Don't disable TLS verification. This allows MITM attacks. For self-signed dev certs, add the CA to your trust store or use a properly-issued cert.",
197 },
198 {
199 "ruleName": "marshal_loads",
200 "regex": r"\bmarshal\.loads?\s*\(",
201 "reminder": _UNSAFE_DESERIALIZATION_REMINDER,
202 },
203 {
204 "ruleName": "shelve_open",
205 "regex": r"\bshelve\.open\s*\(",
206 "reminder": _UNSAFE_DESERIALIZATION_REMINDER,
207 },
208 {
209 "ruleName": "xml_unsafe_parse",
210 "regex": r"\b(xml\.etree\.ElementTree|ElementTree|ET)\.(parse|fromstring|XML)\s*\(|\bminidom\.(parse|parseString)\s*\(|\bxml\.sax\.(parse|make_parser)\b",
211 "reminder": "⚠️ Security Warning: Use defusedxml.ElementTree. Python's stdlib XML parsers are vulnerable to XXE (external entity) and billion-laughs attacks by default.",
212 },
213 {
214 "ruleName": "pickle_variants_load",
215 "regex": r"\b(cPickle|cloudpickle|dill)\.(load|loads)\s*\(",
216 "reminder": _UNSAFE_DESERIALIZATION_REMINDER,
217 },
218 {
219 "ruleName": "outerHTML_xss",
220 "substrings": [".outerHTML =", ".outerHTML="],
221 "reminder": "⚠️ Security Warning: Use textContent or sanitize with DOMPurify. outerHTML assignment is an XSS sink equivalent to innerHTML.",
222 },
223 {
224 "ruleName": "insertAdjacentHTML_xss",
225 "substrings": [".insertAdjacentHTML("],
226 "reminder": "⚠️ Security Warning: Use insertAdjacentText() or sanitize with DOMPurify. insertAdjacentHTML is an XSS sink.",
227 },
228 {
229 "ruleName": "script_src_without_sri",
230 # Detect remote code execution via dynamic import/eval of fetched content.
231 # Negative lookahead after src checks for integrity= anywhere in the remaining tag.
232 "regex": (
233 r"<script\s+(?![^>]{0,400}integrity\s*=)"
234 r"[^>]{0,200}src\s*=\s*[\x22\x27](?:https?:)?//"
235 r"[^\x22\x27]{1,300}[\x22\x27]"
236 r"[^>]{0,100}>"
237 ),
238 "reminder": '⚠️ Security Warning: Add integrity="sha384-..." crossorigin="anonymous" to external script tags. Loading scripts without Subresource Integrity exposes you to CDN compromise.',
239 },
240 {
241 "ruleName": "torch_unsafe_load",
242 # Suppressed by weights_only=True on the same line (within 200 chars). weights_only=False
243 # still triggers. Multi-line calls false-positive — same known limitation as unsafe_yaml_load.
244 "regex": r"(?:\btorch\.load|\.torch_load)\s*\((?![^)\n]{0,200}weights_only\s*=\s*True)",
245 "reminder": _UNSAFE_TORCH_LOAD_REMINDER,
246 },
247 {
248 "ruleName": "yaml_unsafe_load_variants",
249 # yaml.unsafe_load (stdlib alias) plus unsafe wrapper method names seen in the wild.
250 # Bare yaml.load() is unsafe_yaml_load's job (RuleId 12).
251 "regex": r"(?:\byaml\.unsafe_load|\.yaml_unsafe_load)\s*\(",
252 "reminder": _UNSAFE_YAML_LOAD_REMINDER,
253 },
254 {
255 "ruleName": "pickle_wrapper_load",
256 # Library APIs that unpickle without saying "pickle". numpy.load only triggers
257 # when allow_pickle=True is explicit (defaults to False since numpy 1.16.3).
258 "regex": r"\bjoblib\.load\s*\(|\b(?:pd|pandas)\.read_pickle\s*\(|\.cloudpickle_load\s*\(|\b(?:np|numpy)\.load\s*\([^)\n]{0,200}allow_pickle\s*=\s*True",
259 "reminder": _UNSAFE_DESERIALIZATION_REMINDER,
260 },
261]
262
263
264class RuleId(IntEnum):
265 """
266 Stable numeric IDs for SECURITY_PATTERNS rules, emitted via the PostToolUse
267 metrics field so telemetry can attribute pattern-warning events to
268 specific checks. The metrics schema only allows bool|number values (no
269 strings), so rule names can't be sent directly.
270
271 Values are frozen: do not renumber existing entries. Append new ones.
272 """
273 GITHUB_ACTIONS_WORKFLOW = 1
274 CHILD_PROCESS_EXEC = 2
275 NEW_FUNCTION_INJECTION = 3
276 EVAL_INJECTION = 4
277 REACT_DANGEROUSLY_SET_HTML = 5
278 DOCUMENT_WRITE_XSS = 6
279 INNERHTML_XSS = 7
280 PICKLE_DESERIALIZATION = 8
281 OS_SYSTEM_INJECTION = 9
282 PYTHON_SUBPROCESS_SHELL = 10
283 GO_EXEC_SHELL_INJECTION = 11
284 UNSAFE_YAML_LOAD = 12
285 NODE_CREATECIPHER_NO_IV = 13
286 AES_ECB_MODE = 14
287 TLS_VERIFICATION_DISABLED = 15
288 MARSHAL_LOADS = 16
289 SHELVE_OPEN = 17
290 XML_UNSAFE_PARSE = 18
291 PICKLE_VARIANTS_LOAD = 19
292 OUTERHTML_XSS = 20
293 INSERTADJACENTHTML_XSS = 21
294 SCRIPT_SRC_WITHOUT_SRI = 22
295 TORCH_UNSAFE_LOAD = 23
296 YAML_UNSAFE_LOAD_VARIANTS = 24
297 PICKLE_WRAPPER_LOAD = 25
298
299
300_RULE_NAME_TO_ID = {
301 "github_actions_workflow": RuleId.GITHUB_ACTIONS_WORKFLOW,
302 "child_process_exec": RuleId.CHILD_PROCESS_EXEC,
303 "new_function_injection": RuleId.NEW_FUNCTION_INJECTION,
304 "eval_injection": RuleId.EVAL_INJECTION,
305 "react_dangerously_set_html": RuleId.REACT_DANGEROUSLY_SET_HTML,
306 "document_write_xss": RuleId.DOCUMENT_WRITE_XSS,
307 "innerHTML_xss": RuleId.INNERHTML_XSS,
308 "pickle_deserialization": RuleId.PICKLE_DESERIALIZATION,
309 "os_system_injection": RuleId.OS_SYSTEM_INJECTION,
310 "python_subprocess_shell": RuleId.PYTHON_SUBPROCESS_SHELL,
311 "go_exec_shell_injection": RuleId.GO_EXEC_SHELL_INJECTION,
312 "unsafe_yaml_load": RuleId.UNSAFE_YAML_LOAD,
313 "node_createcipher_no_iv": RuleId.NODE_CREATECIPHER_NO_IV,
314 "aes_ecb_mode": RuleId.AES_ECB_MODE,
315 "tls_verification_disabled": RuleId.TLS_VERIFICATION_DISABLED,
316 "marshal_loads": RuleId.MARSHAL_LOADS,
317 "shelve_open": RuleId.SHELVE_OPEN,
318 "xml_unsafe_parse": RuleId.XML_UNSAFE_PARSE,
319 "pickle_variants_load": RuleId.PICKLE_VARIANTS_LOAD,
320 "outerHTML_xss": RuleId.OUTERHTML_XSS,
321 "insertAdjacentHTML_xss": RuleId.INSERTADJACENTHTML_XSS,
322 "script_src_without_sri": RuleId.SCRIPT_SRC_WITHOUT_SRI,
323 "torch_unsafe_load": RuleId.TORCH_UNSAFE_LOAD,
324 "yaml_unsafe_load_variants": RuleId.YAML_UNSAFE_LOAD_VARIANTS,
325 "pickle_wrapper_load": RuleId.PICKLE_WRAPPER_LOAD,
326}
327
328# Fail loudly at import time if a pattern is added without a RuleId.
329# This fires in pytest on every PR, so desync is caught before merge.
330assert set(_RULE_NAME_TO_ID) == {p["ruleName"] for p in SECURITY_PATTERNS}, (
331 f"RuleId enum out of sync with SECURITY_PATTERNS: "
332 f"missing={set(p['ruleName'] for p in SECURITY_PATTERNS) - set(_RULE_NAME_TO_ID)}, "
333 f"extra={set(_RULE_NAME_TO_ID) - set(p['ruleName'] for p in SECURITY_PATTERNS)}"
334)
335
336
337def rule_names_to_mask(rule_names):
338 """Pack a set of rule names into a bitmask. Bit N set means RuleId(N) matched.
339 User-defined patterns (rule_name starting with "user:") have no static
340 RuleId and are excluded from the mask."""
341 mask = 0
342 for name in rule_names:
343 if name in _RULE_NAME_TO_ID:
344 mask |= 1 << _RULE_NAME_TO_ID[name]
345 return mask