gitbills 0.1.2__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.
gitbills/scan.py ADDED
@@ -0,0 +1,392 @@
1
+ """The 14-rule static security X-Ray over the added lines of a unified diff (src/scan.js, pattern for pattern).
2
+
3
+ Offline, linear time, deterministic. Signals name a rule, its variant, a severity, the path and the new-file line, never
4
+ the matched text, so a leaked key is never echoed.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+
10
+ from .diff import (is_doc_path, is_js_path, is_package_json_path, is_python_path, is_test_path, is_unsafe_path,
11
+ is_workflow_path)
12
+ from .slop import is_code_file
13
+ from .text import display_text
14
+
15
+ RULE_IDS = ('secret_leak', 'trojan_source_bidi', 'prompt_injection', 'reverse_shell', 'curl_pipe_shell',
16
+ 'workflow_injection', 'command_injection', 'dangerous_eval', 'sql_injection', 'ssrf', 'path_traversal',
17
+ 'unsafe_deserialization', 'insecure_config', 'symlink_or_submodule')
18
+ SEVERITY_POINTS = {'critical': 35, 'high': 25, 'medium': 10, 'low': 0, 'info': 0}
19
+ SEVERITY_RANK = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3, 'info': 4}
20
+ MAX_SCAN_LINE = 8192
21
+ # A longer line is scanned in windows of MAX_SCAN_LINE code points that overlap by SCAN_OVERLAP, so nothing hides past a cap.
22
+ SCAN_OVERLAP = 512
23
+
24
+ # (rule, variant, severity, pattern, flags, narrow, scope): the same table as src/scan.js. Within a rule the first
25
+ # variant that matches a line wins. scope: '' any file, 'workflow', 'package' (package.json) or 'python'.
26
+ TABLE = (
27
+ ('secret_leak', 'private_key', 'critical', r'-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----', '', 'secret', ''),
28
+ ('secret_leak', 'aws_access_key', 'critical', r'(?:^|[^A-Za-z0-9_])(?:AKIA|ASIA)(?!IOSFODNN7EXAMPLE)[0-9A-Z]{16}(?![0-9A-Za-z])', '', 'secret', ''),
29
+ ('secret_leak', 'github_token', 'critical', r'(?:^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{30,}', '', 'secret', ''),
30
+ ('secret_leak', 'github_pat', 'critical', r'(?:^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{30,}', '', 'secret', ''),
31
+ ('secret_leak', 'anthropic_key', 'critical', r'(?:^|[^A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{30,}', '', 'secret', ''),
32
+ ('secret_leak', 'openai_key', 'critical', r'(?:^|[^A-Za-z0-9_-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}', '', 'secret', ''),
33
+ ('secret_leak', 'stripe_live_key', 'critical', r'(?:^|[^A-Za-z0-9_])[rs]k_live_[A-Za-z0-9]{20,}', '', 'secret', ''),
34
+ ('secret_leak', 'slack_token', 'critical', r'(?:^|[^A-Za-z0-9_])xox[abposr]-[0-9]{6,}-[A-Za-z0-9-]{10,}', '', 'secret', ''),
35
+ ('secret_leak', 'slack_webhook', 'critical', r'https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]{6,}\/B[A-Z0-9]{6,}\/[A-Za-z0-9]{20,}', '', 'secret', ''),
36
+ ('secret_leak', 'google_api_key', 'critical', r'(?:^|[^A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])', '', 'secret', ''),
37
+ ('secret_leak', 'npm_token', 'critical', r'(?:^|[^A-Za-z0-9_])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])', '', 'secret', ''),
38
+ ('secret_leak', 'pypi_token', 'critical', r'pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{40,}', '', 'secret', ''),
39
+ ('secret_leak', 'jwt', 'high', r'(?:^|[^A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}', '', 'secret', ''),
40
+ ('secret_leak', 'generic_secret', 'high', r'''(?:api[_-]?key|secret[_-]?key|client[_-]?secret|auth[_-]?token|access[_-]?token|secret|password|passwd)["']?[ \t]*[:=][ \t]*["'][A-Za-z0-9_\-\/+=.]{16,}["']''', 'i', 'generic_secret', ''),
41
+ ('trojan_source_bidi', 'bidi_control', 'critical', r'[\u202a-\u202e\u2066-\u2069\u061c]', '', '', ''),
42
+ ('prompt_injection', 'instruction_override', 'critical', r'\b(?:ignore|disregard|forget|override)[ \t]+(?:all[ \t]+|any[ \t]+)?(?:of[ \t]+)?(?:the[ \t]+|your[ \t]+|my[ \t]+)?(?:previous|prior|above|earlier|preceding|system|original)[ \t]+(?:instructions|prompts?|directives|guidelines)\b', 'i', '', ''),
43
+ ('reverse_shell', 'dev_tcp', 'critical', r'\/dev\/(?:tcp|udp)\/', '', 'dev_tcp', ''),
44
+ ('reverse_shell', 'netcat_exec', 'critical', r'''\b(?:nc|ncat|netcat)(?:\.exe)?[ \t][^\n|;&]{0,120}(?:-[A-Za-z]*[ec]|--exec|--sh-exec)[ \t]+["']?(?:(?:\/usr)?\/bin\/)?(?:(?:ba|z|k|da)?sh|cmd(?:\.exe)?|powershell(?:\.exe)?)\b''', 'i', '', ''),
45
+ ('reverse_shell', 'fifo_netcat', 'critical', r'\bmkfifo\b[^\n]{0,160}\|[ \t]*(?:nc|ncat|netcat|telnet|openssl[ \t]+s_client)\b', 'i', '', ''),
46
+ ('reverse_shell', 'interactive_shell_netcat', 'critical', r'\b(?:ba|z|k|da)?sh[ \t]+-i\b[^\n]{0,80}\|[ \t]*(?:nc|ncat|netcat|telnet|openssl[ \t]+s_client)\b', 'i', '', ''),
47
+ ('reverse_shell', 'socat_exec', 'critical', r'\bsocat\b[^\n]{0,160}\b(?:exec|system):[^\n]{0,40}\b(?:(?:ba|z|k|da)?sh|cmd|powershell)\b', 'i', '', ''),
48
+ ('reverse_shell', 'python_socket_dup2', 'critical', r'\bos\.dup2[ \t]*\([^\n)]{0,60}fileno', '', 'socket_connect', ''),
49
+ ('reverse_shell', 'powershell_tcpclient', 'critical', r'\bNet\.Sockets\.TCPClient\b', 'i', 'stream_iex', ''),
50
+ ('reverse_shell', 'php_fsockopen', 'critical', r'\bfsockopen[ \t]*\(', 'i', 'php_exec', ''),
51
+ ('reverse_shell', 'perl_socket', 'critical', r'\buse[ \t]+Socket\b', '', 'perl_exec', ''),
52
+ ('curl_pipe_shell', 'download_to_shell', 'critical', r'\b(?:curl|wget)\b[^|\n]{1,200}\|[ \t]*(?:sudo[ \t]+(?:-[A-Za-z]+[ \t]+)*)?(?:ba|z|da|k)?sh\b', 'i', '', ''),
53
+ ('curl_pipe_shell', 'process_substitution', 'critical', r'\b(?:ba|z|k)?sh[ \t]+<\([ \t]*(?:curl|wget)\b', 'i', '', ''),
54
+ ('curl_pipe_shell', 'powershell_download_exec', 'critical', r'\b(?:iwr|irm|curl|wget|Invoke-WebRequest|Invoke-RestMethod)\b[^|\n]{1,200}\|[ \t]*(?:iex|Invoke-Expression)\b|\b(?:iex|Invoke-Expression)\b[^\n]{0,120}\.DownloadString[ \t]*\(', 'i', '', ''),
55
+ ('workflow_injection', 'untrusted_expression', 'critical', r'\$\{\{', '', 'untrusted_expression', 'workflow'),
56
+ ('workflow_injection', 'pr_head_checkout', 'critical', r'''\b(?:ref|repository)[ \t]*:[ \t]*["']?\$\{\{[^}\n]{0,80}?(?:github\.event\.pull_request\.head\.(?:sha|ref|repo\.full_name)|github\.head_ref|github\.event\.workflow_run\.head_(?:sha|branch|repository\.full_name))|refs\/pull\/\$\{\{[^}\n]{1,80}\}\}\/(?:head|merge)|\bgh[ \t]+pr[ \t]+checkout\b|\bgit[ \t]+fetch\b[^\n]{0,200}\bpull\/''', '', 'privileged_trigger', 'workflow'),
57
+ ('command_injection', 'template_command', 'high', r'\b(?:exec|execSync|spawn|spawnSync|execFile|execFileSync|system|popen|shell_exec|passthru)[ \t]*\([ \t]*`[^`\n]{0,200}\$\{', '', '', ''),
58
+ ('command_injection', 'concatenated_command', 'high', r'''\b(?:exec|execSync|spawn|spawnSync|system|popen|shell_exec|passthru)[ \t]*\([ \t]*["'][^"'\n]{0,200}["'][ \t]*\+[ \t]*[A-Za-z_$]''', '', '', ''),
59
+ ('command_injection', 'js_shell_true', 'high', r'\b(?:exec|execSync|spawn|spawnSync|execFile|execFileSync)[ \t]*\([^\n]{0,200}\bshell[ \t]*:[ \t]*true\b', '', 'js_dynamic', ''),
60
+ ('command_injection', 'python_shell_true', 'high', r'\bsubprocess\.[A-Za-z_]+[ \t]*\([^\n]{0,300}\bshell[ \t]*=[ \t]*True\b', '', 'py_dynamic', ''),
61
+ ('command_injection', 'os_system', 'high', r'\bos\.(?:system|popen)[ \t]*\(', '', 'py_dynamic', ''),
62
+ ('command_injection', 'dynamic_exec', 'medium', r'''\b(?:execSync|child_process\.exec)[ \t]*\((?![ \t]*(["'`])[^"'`$\n]{0,300}\1[ \t]*[,)])''', '', '', ''),
63
+ ('dangerous_eval', 'eval_call', 'high', r'(?:^|[^.A-Za-z0-9_$])(?:eval|new[ \t]+Function)[ \t]*\(', '', '', ''),
64
+ ('dangerous_eval', 'vm_run', 'high', r'\bvm\.(?:runInNewContext|runInThisContext|runInContext|compileFunction)[ \t]*\(', '', '', ''),
65
+ ('dangerous_eval', 'string_timer', 'high', r'''(?:^|[^.A-Za-z0-9_$])set(?:Timeout|Interval)[ \t]*\([ \t]*["'`]''', '', '', ''),
66
+ ('dangerous_eval', 'python_exec', 'high', r'(?:^|[^.A-Za-z0-9_])exec[ \t]*\(', '', '', 'python'),
67
+ ('sql_injection', 'interpolated_sql', 'high', r'\b(?:SELECT\b[^;\n]{0,160}\bFROM|INSERT[ \t]+INTO|UPDATE\b[^;\n]{0,80}\bSET|DELETE[ \t]+FROM)\b', 'i', 'sql_dynamic', ''),
68
+ ('ssrf', 'request_controlled_url', 'high', r'\b(?:fetch|axios(?:\.(?:get|post|put|patch|delete|head|request))?|got|needle|https?\.(?:get|request)|requests\.(?:get|post|put|patch|delete|head|request)|httpx\.(?:get|post|put|patch|delete|request)|urlopen)[ \t]*\([ \t]*`?(?:\$\{[ \t]*)?(?:req|request|ctx\.request|ctx|event)\.(?:query|params|body|args|form|values|GET|POST|json|queryStringParameters)\b', '', '', ''),
69
+ ('ssrf', 'plain_http_fetch', 'medium', r'''\bfetch[ \t]*\([ \t]*["'`]http:\/\/(?!(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?:[:\/"'`]|$))''', '', '', ''),
70
+ ('ssrf', 'open_redirect', 'medium', r'\b(?:res|response|reply)\.redirect[ \t]*\([^\n)]{0,40}\b(?:req|request)\.(?:query|params|body)\b|(?:^|[^.A-Za-z0-9_])redirect[ \t]*\([ \t]*request\.(?:args|GET|form|values)\b', '', '', ''),
71
+ ('path_traversal', 'request_controlled_path', 'high', r'\b(?:readFile|readFileSync|createReadStream|writeFile|writeFileSync|appendFile|appendFileSync|unlink|unlinkSync|rmSync|sendFile|download|send_file|send_from_directory|FileResponse|open)[ \t]*\([^\n)]{0,80}\b(?:req|request)\.(?:query|params|body|args|form|values|GET|POST|files)\b', '', '', ''),
72
+ ('path_traversal', 'request_path_join', 'high', r'\b(?:path\.(?:join|resolve)|os\.path\.join)[ \t]*\([^\n)]{0,80}\b(?:req|request)\.(?:query|params|body|args|form|values|GET|POST)\b', '', '', ''),
73
+ ('path_traversal', 'tar_extractall', 'medium', r'\.extractall[ \t]*\((?![^)\n]{0,200}\bfilter[ \t]*=)', '', 'tar_context', 'python'),
74
+ ('unsafe_deserialization', 'pickle_load', 'high', r'\b(?:c?pickle|marshal|dill)\.loads?[ \t]*\(|\bjsonpickle\.decode[ \t]*\(', '', '', ''),
75
+ ('unsafe_deserialization', 'yaml_load', 'high', r'\byaml\.(?:unsafe_)?load(?:_all)?[ \t]*\(', '', 'yaml_unsafe', ''),
76
+ ('unsafe_deserialization', 'unserialize', 'high', r'(?:^|[^.A-Za-z0-9_$])unserialize[ \t]*\(', '', '', ''),
77
+ ('unsafe_deserialization', 'java_object_stream', 'high', r'\bnew[ \t]+ObjectInputStream[ \t]*\(', '', '', ''),
78
+ ('unsafe_deserialization', 'ruby_marshal', 'high', r'\bMarshal\.load[ \t]*\(', '', '', ''),
79
+ ('insecure_config', 'tls_verification_disabled', 'high', r'''\brejectUnauthorized["']?[ \t]*[:=][ \t]*false\b|NODE_TLS_REJECT_UNAUTHORIZED["'\]]{0,2}[ \t]*[=:][ \t]*["']?0\b|\b[Ii]nsecureSkipVerify["']?[ \t]*[:=][ \t]*true\b|\binsecure-skip-tls-verify[ \t]*:[ \t]*true\b|\bverify[ \t]*=[ \t]*False\b|\bssl\._create_unverified_context\b|\bcheck_hostname[ \t]*=[ \t]*False\b|\bssl\.CERT_NONE\b''', '', '', ''),
80
+ ('insecure_config', 'cors_wildcard_credentials', 'high', r'''Access-Control-Allow-Origin[^*\n]{0,40}\*[^;\n]{0,80}Allow-Credentials|\bcredentials[ \t]*:[ \t]*true\b[^}\n]{0,80}\borigin[ \t]*:[ \t]*(?:["']\*["']|true\b)|\borigin[ \t]*:[ \t]*(?:["']\*["']|true\b)[^}\n]{0,80}\bcredentials[ \t]*:[ \t]*true\b|\ballow_origins[ \t]*=[ \t]*\[[ \t]*["']\*["'][ \t]*\][^)\n]{0,120}\ballow_credentials[ \t]*=[ \t]*True\b''', 'i', '', ''),
81
+ ('insecure_config', 'install_script', 'high', r'"(?:preinstall|install|postinstall)"[ \t]*:[ \t]*"[^"\n]{1,200}"', '', '', 'package'),
82
+ ('insecure_config', 'publish_script', 'high', r'"(?:prepack|postpack|prepublish|prepublishOnly|publish|postpublish)"[ \t]*:[ \t]*"[^"\n]{1,200}"', '', '', 'package'),
83
+ ('insecure_config', 'prepare_script', 'medium', r'"prepare"[ \t]*:[ \t]*"[^"\n]{1,200}"', '', '', 'package'),
84
+ ('insecure_config', 'unpinned_action', 'medium', r'''^[ \t]*(?:-[ \t]*)?uses:[ \t]*["']?[A-Za-z0-9_.-]+\/[A-Za-z0-9_.\/-]+@(?![0-9a-f]{40}(?![0-9A-Za-z]))[^ \t\n"'#]+''', '', '', 'workflow'),
85
+ )
86
+
87
+
88
+ def _compile(pattern: str, flags: str):
89
+ return re.compile(pattern, re.ASCII | (re.IGNORECASE if 'i' in flags else 0))
90
+
91
+
92
+ RULES = tuple({'rule': r, 'variant': v, 'severity': s, 'pattern': p, 'flags': f, 'narrow': n, 'scope': sc}
93
+ for r, v, s, p, f, n, sc in TABLE)
94
+ _COMPILED = tuple((r, v, s, _compile(p, f), n, sc) for r, v, s, p, f, n, sc in TABLE)
95
+
96
+ REMEDIATIONS = {
97
+ 'secret_leak': 'Remove the credential from the change, rotate it now, and load it from the environment or a secret store.',
98
+ 'trojan_source_bidi': 'Delete the hidden bidirectional control characters (Trojan Source): they make code read differently than it runs.',
99
+ 'prompt_injection': 'Delete the instruction-override text or invisible characters: repository text is data, never instructions.',
100
+ 'reverse_shell': 'Remove the reverse shell: nothing in a pull request should hand a shell to a remote host.',
101
+ 'curl_pipe_shell': 'Download the script, verify a pinned checksum or signature, then run it; never pipe a download into a shell.',
102
+ 'workflow_injection': 'Pass untrusted event text through env: and quote it; never interpolate it into run: or script:.',
103
+ 'command_injection': 'Pass arguments as an array to execFile or spawn (or subprocess without shell=True), never a string built from input.',
104
+ 'dangerous_eval': 'Remove dynamic code execution, and parse input with a fixed, allowlisted parser instead.',
105
+ 'sql_injection': 'Use parameterized queries or prepared statements instead of building SQL text from values.',
106
+ 'ssrf': 'Fetch only https URLs from an allowlist, and never let request input choose a URL or a redirect target.',
107
+ 'path_traversal': 'Resolve paths against a fixed root and reject .., absolute paths and links before reading or writing.',
108
+ 'unsafe_deserialization': 'Never deserialize untrusted data with pickle, marshal, unserialize or yaml.load; use JSON or yaml.safe_load.',
109
+ 'insecure_config': 'Keep certificate checks and CORS credential rules strict.',
110
+ 'symlink_or_submodule': 'Commit the file itself instead of a symbolic link, which can point outside the repository.',
111
+ 'binary_file': 'Say what each binary file is and how it was made: reviewers cannot read it.',
112
+ 'line_too_long': 'Split minified or padded lines so that every character can be scanned.',
113
+ 'malformed_diff': 'Regenerate the diff with git diff: part of it is not a valid unified diff.',
114
+ }
115
+ VARIANT_REMEDIATIONS = {
116
+ 'pr_head_checkout': 'Never check out pull request code in a pull_request_target or workflow_run job that holds secrets or a write token.',
117
+ 'unsafe_diff_path': 'Keep every path inside the repository: no absolute path, .. segment, .git folder or control character.',
118
+ 'install_script': 'Remove the install-time script, or review exactly what it runs: npm runs it on every install.',
119
+ 'publish_script': 'Remove the pack or publish script, or review exactly what it runs: npm runs prepack on every install from git.',
120
+ 'binary_code': 'Commit code, scripts, workflows and manifests as text: git shows this one as binary, so nobody can read or scan it.',
121
+ 'prepare_script': 'Review what the prepare script runs: npm runs it on local installs and installs from git.',
122
+ 'unpinned_action': 'Pin every third-party action to a full 40-character commit SHA, with the version in a comment.',
123
+ 'submodule': 'Explain the submodule pointer change in the pull request body: reviewers must check the commit it points to.',
124
+ }
125
+
126
+ _A = re.ASCII
127
+ _FAKE_HINT_RE = re.compile(r'test|fake|dummy|example|sample|placeholder|mock|xxxx|0000|not-?real|invalid|redacted|change-?me|your[-_]|[<>]', re.I | _A)
128
+ _SECRET_PREFIX_RE = re.compile(r'^(?:sk-ant-|sk-proj-|sk-svcacct-|sk-admin-|sk-|gh[pousr]_|github_pat_|[rs]k_live_|xox[abposr]-|AIza|npm_|pypi-|AKIA|ASIA)', re.I | _A)
129
+ _PLACEHOLDER_RE = re.compile(r'''["'](?:your[-_]|my[-_])|example|placeholder|change[-_]?me|dummy|fake|sample|redacted|replace[-_]?me|xxxx|<[A-Za-z_-]+>|\$\{''', re.I | _A)
130
+ _LEADING_RE = re.compile(r'^[^A-Za-z0-9]+', _A)
131
+ _WORDS_RE = re.compile(r'^[a-z]+(?:[-_][a-z]+)+$', _A)
132
+ _GENERIC_VALUE_RE = re.compile(r'''["']([A-Za-z0-9_\-/+=.]{16,})["']$''', _A)
133
+ _PY_DYNAMIC_RE = re.compile(r'''(?:^|[^A-Za-z0-9_])f["']|["'][ \t]*%[ \t]*[A-Za-z_(]|\.format[ \t]*\(|["'][ \t]*\+[ \t]*[A-Za-z_]|[A-Za-z_)\]][ \t]*\+[ \t]*["']''', _A)
134
+ _JS_DYNAMIC_RE = re.compile(r'''\$\{|["'`][ \t]*\+[ \t]*[A-Za-z_$]|[A-Za-z_$)\]][ \t]*\+[ \t]*["'`]''', _A)
135
+ _SQL_DYNAMIC_RE = re.compile(r'''\$\{|["'`][ \t]*\+[ \t]*[A-Za-z_$]|[A-Za-z_$)\]][ \t]*\+[ \t]*["'`]|["'][ \t]*%[ \t]*[A-Za-z_(]|\.format[ \t]*\(|(?:^|[^A-Za-z0-9_])f(?:"[^"\n]*|'[^'\n]*)\{[A-Za-z_]''', _A)
136
+ _DEV_TCP_SHELL_RE = re.compile(r'(?:>&|&>)[ \t]*\/dev\/(?:tcp|udp)\/|\b(?:ba|z|k|da)?sh\b[^\n|;&]{0,20}<&[ \t]*[0-9]|0<&[ \t]*[0-9]|\b(?:ba|z|k|da)?sh[ \t]+-i\b|\bdo[ \t]+\$[A-Za-z_]+[ \t]+[0-9]?>&', _A)
137
+ # A `key: ${{ ... }}` line (one whole expression as the value), an `if:` line, and each expression on a line.
138
+ _YAML_MAPPING_RE = re.compile(r'''^[ \t]*(?:-[ \t]+)?([A-Za-z_][A-Za-z0-9_.-]*)[ \t]*:[ \t]*["']?\$\{\{((?:[^}\n]|\}(?!\}))*)\}\}["']?[ \t]*(?:#[^\n]*)?$''', _A)
139
+ _YAML_IF_RE = re.compile(r'^[ \t]*(?:-[ \t]+)?if[ \t]*:', _A)
140
+ _EXPRESSION_RE = re.compile(r'\$\{\{((?:[^}\n]|\}(?!\})){0,400})\}\}', _A)
141
+ _BRACKET_RE = re.compile(r'''\[[ \t]*['"]([A-Za-z0-9_-]{1,60})['"][ \t]*\]''', _A)
142
+ _UNTRUSTED_RE = re.compile(r'\bgithub\.event\.(?:pull_request|issue|comment|review|review_comment|discussion|discussion_comment|pages|commits|head_commit|workflow_run|release)\b[A-Za-z0-9_.*\[\]-]{0,120}?\.(?:title|display_title|body|message|label|ref|head_branch|name|email|page_name|description|homepage|tag_name)\b|\bgithub\.head_ref\b|\btoJSON[ \t]*\([ \t]*github\.event\b', _A)
143
+ _ENV_REF_RE = re.compile(r'\benv\.([A-Za-z_][A-Za-z0-9_]*)', _A)
144
+
145
+
146
+ def _untrusted_expression(expr, tainted):
147
+ """Whether one expression reads text a pull request's author controls, directly or through an env var set from it."""
148
+ e = _BRACKET_RE.sub(r'.\1', expr)
149
+ if _UNTRUSTED_RE.search(e):
150
+ return True
151
+ return bool(tainted) and any(m.group(1) in tainted for m in _ENV_REF_RE.finditer(e))
152
+ _SOCKET_RE = re.compile(r'\bsocket\b', _A)
153
+ _CONNECT_RE = re.compile(r'\bconnect\b', _A)
154
+ _GETSTREAM_RE = re.compile(r'GetStream', re.I | _A)
155
+ _IEX_RE = re.compile(r'\b(?:iex|Invoke-Expression)\b', re.I | _A)
156
+ _PHP_EXEC_RE = re.compile(r'\b(?:exec|shell_exec|system|passthru|proc_open|popen)[ \t]*\(', re.I | _A)
157
+ _PERL_EXEC_RE = re.compile(r'''\bexec[ \t]*\(?[ \t]*["'][^"'\n]{0,30}\bsh\b''', _A)
158
+ _TAR_RE = re.compile(r'\btar', _A)
159
+ _YAML_UNSAFE_RE = re.compile(r'\byaml\.unsafe_load', _A)
160
+ _YAML_SAFE_RE = re.compile(r'\b(?:C?SafeLoader|BaseLoader)\b', _A)
161
+
162
+
163
+ def looks_fake_secret(token: str) -> bool:
164
+ """An obvious stand-in key: a hint word (test, fake, example, xxxx, ...) or lowercase words only."""
165
+ core = _SECRET_PREFIX_RE.sub('', _LEADING_RE.sub('', token, count=1), count=1)
166
+ return bool(_FAKE_HINT_RE.search(core) or _WORDS_RE.search(core))
167
+
168
+
169
+ def _narrow(name, line, ctx, variant, pattern):
170
+ if name == 'secret':
171
+ if variant == 'private_key':
172
+ return 'medium' if ctx['test'] else True
173
+ if variant == 'jwt':
174
+ return 'info' if ctx['test'] or ctx['doc'] else True
175
+ for m in pattern.finditer(line):
176
+ if not looks_fake_secret(m.group(0)):
177
+ return True
178
+ return 'info'
179
+ if name == 'generic_secret':
180
+ if _PLACEHOLDER_RE.search(line):
181
+ return False
182
+ real = False
183
+ for m in pattern.finditer(line):
184
+ value = _GENERIC_VALUE_RE.search(m.group(0))
185
+ if value and not looks_fake_secret(value.group(1)):
186
+ real = True
187
+ if not real:
188
+ return False
189
+ return 'info' if ctx['test'] or ctx['doc'] else True
190
+ if name == 'dev_tcp':
191
+ return bool(_DEV_TCP_SHELL_RE.search(line))
192
+ if name == 'socket_connect':
193
+ return bool(_SOCKET_RE.search(line) and _CONNECT_RE.search(line))
194
+ if name == 'stream_iex':
195
+ return bool(_GETSTREAM_RE.search(line) and _IEX_RE.search(line))
196
+ if name == 'php_exec':
197
+ return bool(_PHP_EXEC_RE.search(line))
198
+ if name == 'perl_exec':
199
+ return bool(_PERL_EXEC_RE.search(line))
200
+ if name == 'untrusted_expression':
201
+ if _YAML_IF_RE.search(line):
202
+ return False
203
+ m = _YAML_MAPPING_RE.search(line)
204
+ if m and m.group(1) != 'run' and m.group(1) != 'script':
205
+ return False
206
+ return any(_untrusted_expression(e.group(1), ctx['tainted']) for e in _EXPRESSION_RE.finditer(line))
207
+ if name == 'privileged_trigger':
208
+ return True if ctx['privileged'] else 'medium'
209
+ if name == 'js_dynamic':
210
+ return bool(_JS_DYNAMIC_RE.search(line))
211
+ if name == 'py_dynamic':
212
+ return bool(_PY_DYNAMIC_RE.search(line))
213
+ if name == 'sql_dynamic':
214
+ return bool(_SQL_DYNAMIC_RE.search(line))
215
+ if name == 'tar_context':
216
+ return bool(_TAR_RE.search(line))
217
+ if name == 'yaml_unsafe':
218
+ return not ctx['js'] and bool(_YAML_UNSAFE_RE.search(line) or not _YAML_SAFE_RE.search(line))
219
+ raise ValueError(name)
220
+
221
+
222
+ _CODE_SINK_RULES = {'command_injection', 'dangerous_eval', 'sql_injection', 'ssrf', 'path_traversal',
223
+ 'unsafe_deserialization', 'insecure_config'}
224
+ _QUOTED_IN_TESTS = {'curl_pipe_shell', 'prompt_injection', 'reverse_shell'}
225
+ _OPEN_QUOTE_RE = re.compile(r'''["'`][^"'`]*$''', _A)
226
+
227
+
228
+ def _adjust(rule, severity, line, index, ctx):
229
+ if (ctx['test'] or ctx['doc']) and rule in _CODE_SINK_RULES:
230
+ return 'info'
231
+ if ctx['test'] and rule in _QUOTED_IN_TESTS and _OPEN_QUOTE_RE.search(line[:index]):
232
+ return 'info'
233
+ if rule == 'curl_pipe_shell' and ctx['doc'] and severity == 'critical':
234
+ return 'medium'
235
+ return severity
236
+
237
+
238
+ _SCATTERED_ZW = {0x200B, 0x2060, 0x2061, 0x2062, 0x2063, 0x2064, 0xFEFF}
239
+ _UNICODE_SPACE = {0xA0, 0x1680, *range(0x2000, 0x200B), 0x202F, 0x205F, 0x3000}
240
+
241
+
242
+ def _is_zw(cp):
243
+ return 0x200B <= cp <= 0x200F or 0x2060 <= cp <= 0x2064 or cp == 0xFEFF
244
+
245
+
246
+ def _hidden_unicode(text):
247
+ scattered = tags = 0
248
+ prev_zw = run = False
249
+ for ch in text:
250
+ cp = ord(ch)
251
+ zw = _is_zw(cp)
252
+ if zw and prev_zw:
253
+ run = True
254
+ prev_zw = zw
255
+ if cp in _SCATTERED_ZW:
256
+ scattered += 1
257
+ if 0xE0000 <= cp <= 0xE007F:
258
+ tags += 1
259
+ return run or scattered >= 2 or tags >= 8
260
+
261
+
262
+ def _normalize_for_injection(text):
263
+ out = []
264
+ for ch in text:
265
+ cp = ord(ch)
266
+ if _is_zw(cp) or 0xE0000 <= cp <= 0xE007F:
267
+ continue
268
+ out.append(' ' if cp in _UNICODE_SPACE else ch)
269
+ return ''.join(out)
270
+
271
+
272
+ _PRIVILEGED_RE = re.compile(r'\b(?:pull_request_target|workflow_run)\b', _A)
273
+ # Files that run or decide what runs: code, scripts, workflows and actions, and dependency manifests.
274
+ _SCRIPT_RE = re.compile(r'\.(?:sh|bash|zsh|ksh|ps1|psm1|bat|cmd)\Z', re.I | _A)
275
+ _MANIFEST_RE = re.compile(r'(?:^|/)(?:package(?:-lock)?\.json|npm-shrinkwrap\.json|requirements[^/]*\.txt|pyproject\.toml|setup\.(?:py|cfg)|Pipfile(?:\.lock)?|Cargo\.toml|go\.mod|Gemfile|[^/]+\.gemspec|composer\.json|pom\.xml|build\.gradle(?:\.kts)?|Makefile|Dockerfile|\.npmrc)\Z', re.I | _A)
276
+
277
+
278
+ def is_executable_path(p) -> bool:
279
+ return bool(is_code_file(p) or is_workflow_path(p) or _SCRIPT_RE.search(p) or _MANIFEST_RE.search(p))
280
+
281
+
282
+ def _signal(source, rule, detail, severity, path, line, remediation):
283
+ return {'source': source, 'rule': rule, 'detail': detail, 'severity': severity,
284
+ 'path': None if path is None else display_text(path, 300), 'line': line, 'remediation': remediation}
285
+
286
+
287
+ def _remediation_for(rule, detail):
288
+ return VARIANT_REMEDIATIONS.get(detail) or REMEDIATIONS[rule]
289
+
290
+
291
+ def _line_windows(text):
292
+ """Code-point windows of a long line: [0, 8192), [7680, 15872), ... up to the one that reaches its end."""
293
+ out, start = [], 0
294
+ while True:
295
+ out.append(text[start:start + MAX_SCAN_LINE])
296
+ if start + MAX_SCAN_LINE >= len(text):
297
+ return out
298
+ start += MAX_SCAN_LINE - SCAN_OVERLAP
299
+
300
+
301
+ def _scan_line(text, line_no, ctx, out, hit):
302
+ if 'prompt_injection' not in hit and _hidden_unicode(text):
303
+ hit.add('prompt_injection')
304
+ out.append(_signal('security', 'prompt_injection', 'hidden_unicode', 'critical', ctx['path'], line_no,
305
+ REMEDIATIONS['prompt_injection']))
306
+ norm = None
307
+ for rule, variant, severity, pattern, narrow, scope in _COMPILED:
308
+ if rule in hit or (scope and not ctx[scope]):
309
+ continue
310
+ if rule == 'prompt_injection':
311
+ if norm is None:
312
+ norm = _normalize_for_injection(text)
313
+ hay = norm
314
+ else:
315
+ hay = text
316
+ m = pattern.search(hay)
317
+ if not m:
318
+ continue
319
+ sev = severity
320
+ if narrow:
321
+ r = _narrow(narrow, hay, ctx, variant, pattern)
322
+ if r is False:
323
+ continue
324
+ if isinstance(r, str):
325
+ sev = r
326
+ sev = _adjust(rule, sev, hay, m.start(), ctx)
327
+ hit.add(rule)
328
+ out.append(_signal('security', rule, variant, sev, ctx['path'], line_no, _remediation_for(rule, variant)))
329
+
330
+
331
+ def scan_diff(parsed) -> dict:
332
+ """The 14 rules over a parsed diff (parse_diff): rules_checked, signals, risk_score, risk_grade. What cannot be read
333
+ in a file that runs (binary, or lines past 8,192 code points) is high; elsewhere it is low or medium."""
334
+ out = []
335
+ for f in parsed['files']:
336
+ path = f['path']
337
+ p = path or ''
338
+ runs = is_executable_path(p)
339
+ if f['newMode'] == '120000':
340
+ out.append(_signal('security', 'symlink_or_submodule', 'symlink', 'high', path, None, REMEDIATIONS['symlink_or_submodule']))
341
+ elif f['newMode'] == '160000':
342
+ out.append(_signal('security', 'symlink_or_submodule', 'submodule', 'medium', path, None, VARIANT_REMEDIATIONS['submodule']))
343
+ unsafe = next((q for q in (f['oldPath'], f['newPath']) if isinstance(q, str) and is_unsafe_path(q)), None)
344
+ if unsafe is not None:
345
+ out.append(_signal('security', 'path_traversal', 'unsafe_diff_path', 'high', unsafe, None, VARIANT_REMEDIATIONS['unsafe_diff_path']))
346
+ if f['isBinary']:
347
+ out.append(_signal('diff', 'binary_file', 'binary_code', 'high', path, None, VARIANT_REMEDIATIONS['binary_code']) if runs
348
+ else _signal('diff', 'binary_file', 'binary_file', 'low', path, None, REMEDIATIONS['binary_file']))
349
+ ctx = {'path': path, 'test': is_test_path(p), 'doc': is_doc_path(p), 'workflow': is_workflow_path(p),
350
+ 'package': is_package_json_path(p), 'python': is_python_path(p), 'js': is_js_path(p), 'privileged': False,
351
+ 'tainted': set()}
352
+ if ctx['workflow']:
353
+ rows = f['context'] + f['added']
354
+ ctx['privileged'] = any(_PRIVILEGED_RE.search(r['text']) for r in rows)
355
+ # env names set from untrusted text anywhere in the file: `${{ env.NAME }}` in run: then interpolates that text.
356
+ for r in rows:
357
+ m = _YAML_MAPPING_RE.search(r['text'])
358
+ if m and m.group(1) not in ('run', 'script', 'if') and _untrusted_expression(m.group(2), ctx['tainted']):
359
+ ctx['tainted'].add(m.group(1))
360
+ long_noted = False
361
+ for a in f['added']:
362
+ if len(a['text']) <= MAX_SCAN_LINE:
363
+ _scan_line(a['text'], a['line'], ctx, out, set())
364
+ continue
365
+ if not long_noted:
366
+ out.append(_signal('diff', 'line_too_long', 'line_too_long', 'high' if runs else 'medium', path, a['line'],
367
+ REMEDIATIONS['line_too_long']))
368
+ long_noted = True
369
+ # Each window on its own, then one signal per rule for the line: the most severe, where the rule first showed.
370
+ found, at, merged = [], {}, []
371
+ for w in _line_windows(a['text']):
372
+ _scan_line(w, a['line'], ctx, found, set())
373
+ for s in found:
374
+ i = at.get(s['rule'])
375
+ if i is None:
376
+ at[s['rule']] = len(merged)
377
+ merged.append(s)
378
+ elif SEVERITY_RANK[s['severity']] < SEVERITY_RANK[merged[i]['severity']]:
379
+ merged[i] = s
380
+ out += merged
381
+ kinds = set()
382
+ for pr in parsed['problems']:
383
+ if pr['kind'] in kinds:
384
+ continue
385
+ kinds.add(pr['kind'])
386
+ out.append(_signal('diff', 'malformed_diff', pr['kind'], 'low', None, None, REMEDIATIONS['malformed_diff']))
387
+ score = min(100, sum(SEVERITY_POINTS[s['severity']] for s in out))
388
+ return {'rules_checked': len(RULE_IDS), 'signals': out, 'risk_score': score, 'risk_grade': risk_grade(score)}
389
+
390
+
391
+ def risk_grade(score: int) -> str:
392
+ return 'A' if score == 0 else 'B' if score <= 20 else 'C' if score <= 45 else 'D' if score <= 74 else 'F'