le-sus 1.9.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,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: le-sus
3
+ Version: 1.9.0
4
+ Summary: Investigate untrusted code, packages and files without running or installing anything.
5
+ Author: Jan Tursky
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jantursky/le-sus
8
+ Project-URL: Changelog, https://github.com/jantursky/le-sus/blob/main/CHANGELOG.md
9
+ Project-URL: Demo, https://le-sus.vercel.app
10
+ Keywords: security,audit,malware,supply-chain,mcp
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Security
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: license-file
21
+
22
+ # Le Sus
23
+
24
+ Investigate a repository, folder, file, archive, published npm or PyPI package or public GitHub repository for malware and hidden behavior. Nothing in the target is run, installed or extracted. Standard library only, Python 3.9 or newer.
25
+
26
+ ```sh
27
+ uvx le-sus path/to/target
28
+ uvx le-sus npm:left-pad
29
+ ```
30
+
31
+ Or `pipx install le-sus`, then `le-sus`. Do not use `pipx run`, which can start a program planted in the folder you are in. Unset `PYTHONPATH` before looking at something untrusted: if it reaches into that folder, Python runs code from there before the scanner starts.
32
+
33
+ The exit code is 0 for no known indicators, 1 for needs review, 2 for high-risk indicators, 3 for an incomplete check and 64 for a mistake on the command line. No result means a target is safe.
34
+
35
+ The local MCP server over stdio has one read-only tool, `investigate`:
36
+
37
+ ```sh
38
+ uvx le-sus --mcp
39
+ ```
40
+
41
+ `le-sus-mcp` starts the same server after `pipx install le-sus`.
42
+
43
+ Full documentation, limits and the browser demo: <https://github.com/jantursky/le-sus>
44
+
45
+ <!-- mcp-name: io.github.jantursky/le-sus -->
@@ -0,0 +1,40 @@
1
+ le_sus-1.9.0.dist-info/licenses/LICENSE,sha256=HsD_Yf47RRvySfCRMC7_B2u2y38yD7IOAdnAcQ2aPcU,1067
2
+ lesus/__init__.py,sha256=Zit5e6LbEKOTNznko3pZ5LZH23CGaFq2SClHGCQWd2A,108
3
+ lesus/accept.py,sha256=v25gLJS5s7WvyKwnLZyEnOgCPe0Ax8cLvEs8KXAy9aY,6501
4
+ lesus/cli.py,sha256=dyi7-3Nxs1zNmxNNkQSR42X9BqUiaJoCZ0DE_Ph4LcI,22274
5
+ lesus/connections.py,sha256=EYlFMdSxo_sZ_XrZsxPEbv7CLMs2RJbSr_9SpvpkeCU,8485
6
+ lesus/entry.py,sha256=nLpY77XYGSPNCl0c7YxRlnBV0uOEblQQP9GMvfD40Z4,1184
7
+ lesus/follow.py,sha256=i7vOwxDenwXqmjsnYebOKMUDtUczFHLM0Puz8HZ3KcE,6455
8
+ lesus/github.py,sha256=VT6SS_plbIg1dlgOHNst6UM1LbVcN7j5-xo_PZ7lcz4,16140
9
+ lesus/inventory.py,sha256=uZnERXDwiFjlrPm85oPM2H7-MvbmpQvVdMeWY0720mI,23819
10
+ lesus/lockfiles.py,sha256=J1Er4te8A0xeWR7V1b4Qk1LifDJTw1fB6xaKb6kVOvk,9447
11
+ lesus/mcp.py,sha256=u6ZrH2VKda8hALZh1HgvfsK5fCSsl2ZaBsBe4JKWkEI,8722
12
+ lesus/model.py,sha256=PK56m5EZ94xDjKdiW4n67rH_j1Ll2mNyvpnCmPycxl8,5933
13
+ lesus/osv.py,sha256=YiCD7Mx1BBMdMnVsT1-k2pQcwCJy5NS5lYQ7FAsSBeQ,3513
14
+ lesus/package.py,sha256=cC5Yx0eL83WIDzUP_eRr87tWuvkCDmCnNzgfx-RG2PQ,30426
15
+ lesus/private.py,sha256=J1--F6SyHMSQUR21gM5A9f8LR_FwIj__7Saew0gBvVc,15345
16
+ lesus/progress.py,sha256=ZKHm4_cW6N-99ZhWCq5kT5RsXLUHkdu_0hM6ZGuYyGQ,1035
17
+ lesus/registry.py,sha256=_Ti-hlbY-d4tueBJxxH4xLr97P-tH9Y6FPcG89aLDDI,7333
18
+ lesus/report.py,sha256=fB8tvYNlt36qtJN7qnxbUWZYieABDxoRvM-WRQXRIBA,7653
19
+ lesus/sarif.py,sha256=5fcPQuIi51egQi0OBSbRzfk-RhYaZR-iyyXUj40Nlto,4341
20
+ lesus/walker.py,sha256=AvmEiW0q_MrQNDIdgWQvxwuVRQylMJmYCVhppAcoW-U,23678
21
+ lesus/analyzers/__init__.py,sha256=T9NI4IX22VM9YGh3b7AVnrtmyj-7gyVsDHT_UKmOZ4k,463
22
+ lesus/analyzers/agents.py,sha256=zaJu9Y0FZT8UweEjZkY_4p_EP4wMHOBJh7VCYFuJsQQ,9403
23
+ lesus/analyzers/behavior.py,sha256=I3Lz_BJ0Ya62-WE60ZCuNGVmk8HWo3O9hTjeUtQ7iiw,9399
24
+ lesus/analyzers/common.py,sha256=Iqid-YAHfLhdMRTEasFrOKVkcfFM7k5EnK-iLMVs-hM,1658
25
+ lesus/analyzers/dependencies.py,sha256=T3TKMXiNqg0IdwVEc-snRVZH18jxyOeDrTP2Fg8RwgM,11774
26
+ lesus/analyzers/secrets.py,sha256=AL-QUc1uhIoy7S089f4PGyReac8Dh0qZZ1Ti0q2ZV18,1719
27
+ lesus/analyzers/text.py,sha256=Hzecqw3OstgSR7msVL8jPocwxLpMipZe6TnvP3xdOKk,10006
28
+ lesus/analyzers/triggers.py,sha256=-FfBs4XKFki1SBpiOcHU4ipfv1vjHntK3Udbs47MVNs,27691
29
+ lesus/formats/__init__.py,sha256=nmWmxNlwD68_g2EqAL4LZ7RbqP0LjWzmYXTqFCd9MDs,2294
30
+ lesus/formats/common.py,sha256=O_2ZSC7tnqe2_wOTsDhX3grIcQCrWrJDAjUe8an2zvU,2630
31
+ lesus/formats/images.py,sha256=OjuSC-fR87Q-BgEiYHVjLRpefV8ZHseBiOLVFHBvEOg,10335
32
+ lesus/formats/office.py,sha256=8jsUcp8tfsnVJaAdB-nw6XNy1rR4dpijI_VbZ6K6dO0,20445
33
+ lesus/formats/pdf.py,sha256=27bz_DcXOnGxz0obnj8ArRyWGKnwYqaGL24LkquFBlM,22338
34
+ lesus/formats/rtf.py,sha256=hvxkhpRRCPdZc4fkNC8PSVQAl2erLTv1izoXs4WRXj8,1783
35
+ lesus/formats/vba.py,sha256=7SVlkXOm9fxum5dbvYm6pa91HKodaDENsZ45rBiBaJQ,10945
36
+ le_sus-1.9.0.dist-info/METADATA,sha256=OdnlviZxd5MqccPESEB2TQQh-INYt5MprygXUOJuUJY,1864
37
+ le_sus-1.9.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
38
+ le_sus-1.9.0.dist-info/entry_points.txt,sha256=4Qntq4lJrw5Am3vqdAsZTdlGN9BgqOyGRe1dBaj57IQ,73
39
+ le_sus-1.9.0.dist-info/top_level.txt,sha256=jrg1GXV6X_Edy8z0wmYn0mhuhH-pnn0xop_cLcH6lQ0,6
40
+ le_sus-1.9.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ le-sus = lesus.entry:scan
3
+ le-sus-mcp = lesus.entry:mcp
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jan Tursky
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ lesus
lesus/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Static investigation of untrusted files. Nothing in a target is ever executed."""
2
+
3
+ __version__ = "1.9.0"
lesus/accept.py ADDED
@@ -0,0 +1,156 @@
1
+ """Findings the caller has judged and sets aside.
2
+
3
+ Only what the caller names has any effect: nothing in a target configures a scan. A baseline entry holds for
4
+ exactly the files that were judged, so any change to a file brings its findings back.
5
+ """
6
+ import fnmatch
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import re
11
+ from typing import List, NamedTuple, Optional, Sequence, Tuple
12
+
13
+ from . import __version__
14
+ from .model import Coverage, Finding, printable
15
+
16
+ SCHEMA = 1
17
+ MAX_BYTES = 20 * 1024 * 1024
18
+ # Paths under which findings from a registry or GitHub are filed. No file stands behind them, even if one is so named.
19
+ UNFILED = ("registry metadata", "repository metadata")
20
+ IGNORE = re.compile(r"(LS\d{3})(?::(.+))?\Z", re.S)
21
+
22
+
23
+ class BadAcceptance(ValueError):
24
+ """An option or a baseline that cannot be used; the message is fit to show."""
25
+
26
+
27
+ class Accepted(NamedTuple):
28
+ finding: Finding
29
+ reason: str
30
+
31
+
32
+ def parse_ignore(value: str) -> Tuple[str, str]:
33
+ found = IGNORE.match(value)
34
+ if not found:
35
+ raise BadAcceptance("--ignore %s: write it as RULE or RULE:path-pattern, for example LS108:vendor/*" % printable(value, 200))
36
+ return found.group(1), found.group(2) or ""
37
+
38
+
39
+ def fingerprint(finding: Finding, coverage: Coverage) -> str:
40
+ """Rests on the content of the file the finding came from; empty when there is no such file."""
41
+ content = coverage.digests.get(finding.path)
42
+ if not content or finding.path.endswith(UNFILED):
43
+ return ""
44
+ parts = [finding.rule, finding.severity, finding.path, finding.evidence, content]
45
+ return hashlib.sha256("\0".join(parts).encode("utf-8", errors="surrogatepass")).hexdigest()
46
+
47
+
48
+ def _shown(path: str) -> str:
49
+ return printable(path, 400, secrets=False)
50
+
51
+
52
+ def _within(path: str, target: str) -> bool:
53
+ """Whether the path, as written or as resolved, is the target or lies below it."""
54
+ for current in (os.path.abspath(path), os.path.realpath(path)):
55
+ while True:
56
+ try:
57
+ if os.path.samefile(current, target):
58
+ return True
59
+ except OSError:
60
+ pass
61
+ parent = os.path.dirname(current)
62
+ if parent == current:
63
+ break
64
+ current = parent
65
+ return False
66
+
67
+
68
+ def outside(option: str, path: str, target: Optional[str]) -> None:
69
+ """A baseline the target could have written must never be read."""
70
+ if target is not None and _within(path, target):
71
+ raise BadAcceptance("%s %s: lies inside the target; keep it where the target cannot write it" % (option, printable(path, 400)))
72
+
73
+
74
+ def writable(option: str, path: str) -> None:
75
+ """Fails before the scan where writing a new file afterwards could only fail."""
76
+ named = "cannot write %s %s" % (option, printable(path, 400))
77
+ if os.path.lexists(path):
78
+ raise BadAcceptance("%s: already exists, it is never overwritten" % named)
79
+ folder = os.path.dirname(os.path.abspath(path))
80
+ if not os.path.isdir(folder) or not os.access(folder, os.W_OK):
81
+ raise BadAcceptance("%s: its folder is missing or cannot be written to" % named)
82
+
83
+
84
+ def same_new_file(first: str, second: str) -> bool:
85
+ """Case is ignored: on some disks two spellings are one file."""
86
+ return os.path.realpath(first).casefold() == os.path.realpath(second).casefold()
87
+
88
+
89
+ def load(path: str, target: Optional[str]) -> set:
90
+ outside("--baseline", path, target)
91
+ named = "--baseline %s" % printable(path, 400)
92
+ try:
93
+ if not os.path.isfile(path):
94
+ raise BadAcceptance("%s: not a file" % named)
95
+ with open(path, "rb") as handle:
96
+ data = handle.read(MAX_BYTES + 1)
97
+ if len(data) > MAX_BYTES:
98
+ raise BadAcceptance("%s: larger than 20 MiB" % named)
99
+ document = json.loads(data.decode("utf-8"))
100
+ if document["schema"] != SCHEMA:
101
+ raise BadAcceptance("%s: written with another schema" % named)
102
+ return {(str(e["rule"]), str(e["path"]), str(e["fingerprint"])) for e in document["findings"]}
103
+ except BadAcceptance:
104
+ raise
105
+ except OSError as error:
106
+ raise BadAcceptance("%s: %s" % (named, error.strerror))
107
+ except (ValueError, KeyError, TypeError, RecursionError):
108
+ raise BadAcceptance("%s: not a Le Sus baseline" % named)
109
+
110
+
111
+ def _matches(path: str, pattern: str) -> bool:
112
+ if path == pattern:
113
+ return True
114
+ if path.startswith("/") or ".." in path.split("/"):
115
+ # Such a name only looks as if it lay under a folder.
116
+ return False
117
+ for mark in "#!":
118
+ # Something taken out of a file answers to the file's name, not to how the part is called.
119
+ if mark not in pattern:
120
+ path = path.split(mark, 1)[0]
121
+ return fnmatch.fnmatchcase(path, pattern)
122
+
123
+
124
+ def apply(findings: List[Finding], coverage: Coverage, ignored: Sequence[Tuple[str, str]], known: set):
125
+ """Returns the findings that still count and those set aside."""
126
+ kept: List[Finding] = []
127
+ aside: List[Accepted] = []
128
+ for finding in findings:
129
+ rule = next((r for r in ignored if r[0] == finding.rule and (not r[1] or _matches(finding.path, r[1]))), None)
130
+ if rule:
131
+ aside.append(Accepted(finding, "--ignore " + ":".join(filter(None, rule))))
132
+ continue
133
+ mark = fingerprint(finding, coverage) if known else ""
134
+ if mark and (finding.rule, _shown(finding.path), mark) in known:
135
+ aside.append(Accepted(finding, "baseline"))
136
+ else:
137
+ kept.append(finding)
138
+ return kept, aside
139
+
140
+
141
+ def write(path: str, findings: List[Finding], coverage: Coverage) -> Tuple[int, int]:
142
+ """Writes a new file; returns how many findings it holds and how many cannot be held."""
143
+ entries, left = {}, 0
144
+ for finding in findings:
145
+ mark = fingerprint(finding, coverage)
146
+ if mark:
147
+ entries[finding.rule, _shown(finding.path), mark] = finding.severity
148
+ else:
149
+ left += 1
150
+ listed = [{"rule": r, "path": p, "fingerprint": m, "severity": s, "note": ""} for (r, p, m), s in sorted(entries.items())]
151
+ text = json.dumps({"schema": SCHEMA, "tool": "le-sus", "version": __version__, "findings": listed}, indent=2) + "\n"
152
+ if len(text.encode("utf-8")) > MAX_BYTES:
153
+ raise BadAcceptance("--write-baseline %s: %d findings make a file larger than the 20 MiB that can be read back" % (printable(path, 400), len(listed)))
154
+ with open(path, "x", encoding="utf-8") as handle:
155
+ handle.write(text)
156
+ return len(listed), left
@@ -0,0 +1,12 @@
1
+ from typing import Iterator
2
+
3
+ from ..model import FULL_TEXT, LOCKFILES, Finding, Source
4
+ from . import agents, behavior, dependencies, secrets, text, triggers
5
+
6
+ ANALYZERS = (text, secrets, triggers, dependencies, agents, behavior)
7
+
8
+
9
+ def analyze(source: Source) -> Iterator[Finding]:
10
+ large = source.name in LOCKFILES and len(source.text) > FULL_TEXT
11
+ for analyzer in (secrets, dependencies) if large else ANALYZERS:
12
+ yield from analyzer.analyze(source)
@@ -0,0 +1,177 @@
1
+ """Files that steer or extend coding agents."""
2
+ import re
3
+ from typing import Iterator
4
+
5
+ from ..model import MASK, Finding, Source
6
+ from .common import finding, load_json, matches
7
+
8
+ INSTRUCTIONS = re.compile(
9
+ r"(?:^|/)(?:AGENTS|CLAUDE|GEMINI|SKILL)\.md$|(?:^|/)\.(?:cursorrules|windsurfrules|clinerules)$"
10
+ r"|(?:^|/)\.github/copilot-instructions\.md$|(?:^|/)\.(?:claude|cursor|codex|gemini|agents)/.+\.(?:md|mdc|txt|toml)$",
11
+ re.I,
12
+ )
13
+ SETTINGS = re.compile(
14
+ r"(?:^|/)(?:\.(?:claude|cursor|codex|gemini)/(?:settings(?:\.local)?|hooks|mcp)\.json|\.mcp\.json|\.vscode/mcp\.json|hooks/hooks\.json)$",
15
+ re.I,
16
+ )
17
+ MANIFEST = re.compile(r"(?:^|/)\.claude-plugin/(?:plugin|marketplace)\.json$", re.I)
18
+ CODEX_MCP = re.compile(r"^[ \t]*\[mcp_servers\.[^\]\n]+\]", re.M)
19
+ SHELL_INJECTION = re.compile(r"(?<![\w`])!`[^`\n]+`")
20
+ COMMAND_FILE = re.compile(r"(?:^|/)(?:SKILL\.md|\.claude/(?:commands|skills)/.+\.md)$", re.I)
21
+ HELPERS = ("apiKeyHelper", "awsAuthRefresh", "awsCredentialExport", "statusLine")
22
+ ENDPOINTS = ("ANTHROPIC_BASE_URL", "OPENAI_BASE_URL", "GOOGLE_GEMINI_BASE_URL")
23
+ SHOWN = 20
24
+ INJECTION = re.compile(
25
+ r"\b(?:ignore|disregard|forget)\s+(?:all\s+|any\s+|the\s+)?(?:previous|prior|above|earlier|system)\s+(?:instructions|prompts?|rules)\b"
26
+ r"|\bdo\s+not\s+(?:tell|inform|alert)\s+(?:this\s+to\s+)?the\s+user\b"
27
+ r"|\bdo\s+not\s+(?:mention|show|reveal|report|disclose)\s+(?:this|these|it|that)\s+to\s+the\s+user\b"
28
+ r"|\bwithout\s+(?:telling|asking|informing)\s+the\s+user\b",
29
+ re.I,
30
+ )
31
+ NEGATIONS = r"\b(?:never|do\s+not|does\s+not|don't|must\s+not|should\s+not|will\s+not|may\s+not|cannot|can't|mustn't)"
32
+ NEGATION = re.compile(NEGATIONS + r"\b", re.I)
33
+ # The negation opens the sentence or bullet and stands right before the verb: "Never ignore ...", but not
34
+ # "If you do not ignore ..." or "do not hesitate to ignore ...".
35
+ DIRECTLY = re.compile(
36
+ r"(?:\A|[\n.!?;:])[ \t]*(?:(?:[-*+>#]+|\d{1,3}\.)[ \t]*)?(?:\*\*|__)?(?:(?:you|please|and|also|agents?)[ \t]+)?"
37
+ + NEGATIONS + r"(?:\*\*|__)?[ \t]+\Z", re.I)
38
+ OVERRIDES = ("ignore", "disregard", "forget")
39
+
40
+
41
+ def analyze(source: Source) -> Iterator[Finding]:
42
+ if INSTRUCTIONS.search(source.path):
43
+ yield finding(source, "LS501", "info", "Instructions an agent may load automatically; read them as data")
44
+ yield from injections(source)
45
+ if COMMAND_FILE.search(source.path):
46
+ yield from matches(source, SHELL_INJECTION, "LS506", "medium", "Command file runs a shell command when loaded")
47
+ if SETTINGS.search(source.path):
48
+ yield from _settings(source)
49
+ if MANIFEST.search(source.path):
50
+ yield from _manifest(source)
51
+ if source.path.lower().endswith(".codex/config.toml"):
52
+ yield from matches(source, CODEX_MCP, "LS504", "medium", "Starts or connects an MCP server")
53
+
54
+
55
+ SECRET_FLAG = re.compile(r"^--?(?:[\w]{0,30}-){0,5}[\w]{0,30}?(?:key|token|secret|pass|passwd|password|pwd|(?<=-)pat|auth|authorization|credentials?|cookie|bearer)$", re.I)
56
+ # Options whose value is an environment variable or a header.
57
+ CARRIER = re.compile(r"^(?:-e|-H|--env|--header|--headers)$")
58
+ PAIR = re.compile(r"^([A-Za-z_]\w{0,100}=|[A-Za-z][\w-]{0,100}:[ \t]+)(?=.)", re.S)
59
+ ADDRESS = re.compile(r"^([A-Za-z][\w+.-]{0,30}://)(?:[^/?#\s]*@)?([^/?#\s@]*)([^\s]*)$")
60
+ SECRET_HOLDERS = ("env", "headers", "http_headers", "env_http_headers", "environment")
61
+ QUERY = re.compile(r"([?&][\w.-]{1,40}=)[^&\s'\"]+")
62
+
63
+
64
+ def masked_arguments(arguments: list) -> list:
65
+ """Arguments without the values that are likely credentials: those of telling options,
66
+ of environment and header options, and of anything written as NAME=value or Header: value."""
67
+ shown = []
68
+ for at, argument in enumerate(arguments):
69
+ text = str(argument)
70
+ before = str(arguments[at - 1]) if at else ""
71
+ flag, equals, _ = text.partition("=")
72
+ pair = PAIR.match(text)
73
+ if SECRET_FLAG.match(before) or CARRIER.match(before):
74
+ kept = PAIR.match(text)
75
+ shown.append(kept.group(1) + MASK if kept else MASK)
76
+ elif equals and (SECRET_FLAG.match(flag) or CARRIER.match(flag)):
77
+ shown.append(flag + "=" + MASK)
78
+ elif pair:
79
+ shown.append(pair.group(1) + MASK)
80
+ else:
81
+ shown.append(QUERY.sub(r"\1" + MASK, text))
82
+ return shown
83
+
84
+
85
+ def bare_address(url: str) -> str:
86
+ """Where an address leads, without what may be a key in its user, path or query."""
87
+ found = ADDRESS.match(url)
88
+ if not found:
89
+ return MASK
90
+ rest = "/" + MASK if found.group(3).strip("/") else found.group(3)
91
+ return found.group(1) + found.group(2) + rest
92
+
93
+
94
+ def masked(value, key: str = ""):
95
+ """A configuration with values of environments and headers hidden, in whatever shape they are."""
96
+ lower = key.lower()
97
+ if lower in SECRET_HOLDERS:
98
+ if isinstance(value, dict):
99
+ return {k: bare_address(str(v)) if k in ENDPOINTS else MASK for k, v in value.items()}
100
+ return MASK
101
+ if isinstance(value, dict):
102
+ return {k: masked(v, str(k)) for k, v in value.items()}
103
+ if isinstance(value, list):
104
+ return masked_arguments(value) if lower == "args" else [masked(v) for v in value]
105
+ if isinstance(value, str) and lower.endswith(("url", "uri", "endpoint")):
106
+ return bare_address(value)
107
+ return value
108
+
109
+
110
+ def _manifest(source: Source) -> Iterator[Finding]:
111
+ """A plugin may declare hooks and servers in its manifest, inline or by naming another file."""
112
+ data = load_json(source.text)
113
+ if not isinstance(data, dict):
114
+ yield finding(source, "LS505", "medium", "Agent configuration could not be parsed")
115
+ return
116
+ entries = [data] + [p for p in data.get("plugins", []) if isinstance(p, dict)] if isinstance(data.get("plugins"), list) else [data]
117
+ for about in entries[:SHOWN]:
118
+ if about.get("hooks"):
119
+ yield finding(source, "LS503", "high", "Agent hooks run commands automatically", max(source.text.find('"hooks"'), 0), str(about["hooks"]))
120
+ servers = about.get("mcpServers")
121
+ if isinstance(servers, dict):
122
+ for name, server in list(servers.items())[:SHOWN]:
123
+ yield finding(source, "LS504", "medium", "Starts or connects an MCP server", max(source.text.find('"%s"' % name), 0), "%s: %s" % (name, masked(server)))
124
+ elif servers:
125
+ yield finding(source, "LS504", "medium", "Starts or connects an MCP server", max(source.text.find('"mcpServers"'), 0), str(masked(servers)))
126
+
127
+
128
+ def injections(source: Source) -> Iterator[Finding]:
129
+ found = 0
130
+ for match in INJECTION.finditer(source.text):
131
+ if match.group(0).lower().startswith(OVERRIDES):
132
+ before = source.text[max(match.start() - 80, 0) : match.start()]
133
+ # A cut window must not pass for the start of the text.
134
+ if DIRECTLY.search(before if match.start() <= 80 else "x" + before):
135
+ continue
136
+ elif match.group(0).lower().startswith("without"):
137
+ # The negation has to sit in the same clause to govern what follows.
138
+ sentence = re.split(r"[.!?,;:\n]", source.text[max(match.start() - 120, 0) : match.start()])[-1]
139
+ # "Never push without asking the user" protects the user.
140
+ if NEGATION.search(sentence):
141
+ continue
142
+ yield finding(source, "LS502", "high", "Text that tries to override or hide things from the user", match.start(), match.group(0))
143
+ found += 1
144
+ if found == 3:
145
+ return
146
+
147
+
148
+ def _settings(source: Source) -> Iterator[Finding]:
149
+ data = load_json(source.text)
150
+ if not isinstance(data, dict):
151
+ yield finding(source, "LS505", "medium", "Agent configuration could not be parsed")
152
+ return
153
+ permissions = data.get("permissions")
154
+ permissions = permissions if isinstance(permissions, dict) else {}
155
+ allowed = permissions.get("allow")
156
+ open_shell = isinstance(allowed, list) and any(a in ("Bash", "Bash(*)", "Bash(*:*)", "*") for a in allowed)
157
+ for key, risky in (
158
+ ("defaultMode", permissions.get("defaultMode") == "bypassPermissions"),
159
+ ("allow", open_shell),
160
+ ("enableAllProjectMcpServers", data.get("enableAllProjectMcpServers") is True),
161
+ ):
162
+ if risky:
163
+ yield finding(source, "LS509", "high", "Agent settings remove a permission prompt (%s)" % key, max(source.text.find('"%s"' % key), 0))
164
+ if data.get("hooks"):
165
+ yield finding(source, "LS503", "high", "Agent hooks run commands automatically", max(source.text.find('"hooks"'), 0), str(data["hooks"]))
166
+ for key in HELPERS:
167
+ if data.get(key):
168
+ yield finding(source, "LS507", "high" if key != "statusLine" else "medium", "Agent setting runs a command (%s)" % key, max(source.text.find('"%s"' % key), 0), str(data[key]))
169
+ environment = data.get("env")
170
+ if isinstance(environment, dict):
171
+ for key in ENDPOINTS:
172
+ if key in environment:
173
+ yield finding(source, "LS508", "high", "Agent traffic is redirected (%s)" % key, max(source.text.find(key), 0), str(environment[key]))
174
+ servers = data.get("mcpServers") or data.get("servers")
175
+ if isinstance(servers, dict):
176
+ for name, server in list(servers.items())[:SHOWN]:
177
+ yield finding(source, "LS504", "medium", "Starts or connects an MCP server", max(source.text.find('"%s"' % name), 0), "%s: %s" % (name, masked(server)))
@@ -0,0 +1,188 @@
1
+ """What code does with the network, private data and the machine it runs on."""
2
+ import re
3
+ from typing import Dict, Iterator, List, Optional, Pattern, Tuple
4
+
5
+ from ..model import Finding, Source
6
+ from .common import CODE, finding
7
+
8
+ JS = (".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts")
9
+ PYTHON = (".py",)
10
+ # How many statements a fetched value stays under suspicion; names get reused.
11
+ REACH = 150
12
+ MAX_STATEMENT = 4000
13
+ SINK_WINDOW = 300
14
+
15
+ JS_FETCH = re.compile(
16
+ r"(?<![\w$])(?:fetch|axios|got|needle|superagent)\s*(?:\.\s*(?:get|post|put|request)\s*)?\("
17
+ r"|(?<![\w$])(?:https?|request)\s*\.\s*(?:get|post|request)\s*\(|(?<![\w$.])request\s*\(|\.responseText\b"
18
+ )
19
+ JS_SINK = re.compile(
20
+ r"(?<![\w$.])(?:eval|Function|execSync)\s*\(|\bFunction\s*\.\s*constructor\s*\)?\s*\("
21
+ r"|\bvm\s*\.\s*runIn\w*Context\s*\(|\bchild_process\s*\.\s*exec(?:Sync)?\s*\("
22
+ r"|\b(?:globalThis|window|global)\s*\.\s*(?:eval|Function)\s*\(|\(\s*0\s*,\s*eval\s*\)\s*\("
23
+ )
24
+ # Loading what was just serialized in the same expression copies an object; nothing new comes in.
25
+ ROUND_TRIP = re.compile(r"\s*(?:pickle|marshal)\s*\.\s*dumps\s*\(")
26
+ # `exec` taken out of child_process is a sink under its bare name.
27
+ JS_EXEC_IMPORT = re.compile(r"\{[^{}\n]{0,200}\bexec\b[^{}\n]{0,200}\}\s*(?:=\s*require\s*\(|from\s+)\s*[\"'](?:node:)?child_process[\"']")
28
+ JS_SINK_WITH_EXEC = re.compile(JS_SINK.pattern + r"|(?<![\w$.])exec\s*\(")
29
+ PY_FETCH = re.compile(r"\burlopen\s*\(|\b(?:requests|httpx)\s*\.\s*(?:get|post|request)\s*\(|\.recv\s*\(")
30
+ PY_SINK = re.compile(
31
+ r"(?<![\w.])(?:eval|exec)\s*\(|\bos\s*\.\s*(?:system|popen)\s*\(|\bpickle\s*\.\s*loads\s*\(|\bmarshal\s*\.\s*loads\s*\("
32
+ r"|\bsubprocess\s*\.\s*\w+\s*\((?=[^\n]{0,300}\bshell\s*=\s*True)"
33
+ )
34
+
35
+ # A line goes on after an open bracket or comma, and before a leading dot or closing bracket.
36
+ STATEMENT = re.compile(r"(?:[^\n;]|(?<=[(\[,])\n|\n(?=[ \t]*[.)\]]))+")
37
+ SPACES = re.compile(r"[ \t]{2,}")
38
+ APPEND = re.compile(r"([A-Za-z_$][\w$]{0,60})\s*\+=\s*([A-Za-z_$][\w$]{0,60})")
39
+ NAME = re.compile(r"[A-Za-z_$][\w$]*")
40
+ # The closing quote is optional, so an unterminated string is consumed once instead of retried.
41
+ STRING = re.compile(r"\"(?:\\.|[^\"\\\n])*\"?|'(?:\\.|[^'\\\n])*'?")
42
+ ASSIGN = re.compile(r"^(?:[^=(]|\((?=\s*$)){0,200}?(?<![=!<>\-*/])=(?![=>])")
43
+ ALIAS = re.compile(r"\bas\s+([A-Za-z_]\w*)")
44
+ CALLBACK = re.compile(r"\(([^()]{0,100})\)\s*=>|\bfunction\b[^()]{0,60}\(([^()]{0,100})\)|(?<![\w$])([A-Za-z_$][\w$]{0,40})\s*=>")
45
+ KEYWORDS = {"const", "let", "var", "await", "async", "return", "export", "default", "new", "with", "for", "if", "in", "of"}
46
+
47
+
48
+ def _names(text: str) -> List[str]:
49
+ """Identifiers outside string literals."""
50
+ return [n for n in NAME.findall(STRING.sub("''", text)) if n not in KEYWORDS]
51
+
52
+
53
+ def _statements(text: str) -> Iterator[Tuple[int, str]]:
54
+ """Offsets and statements. Long ones are cut into pieces rather than dropped."""
55
+ for match in STATEMENT.finditer(text.replace("\r", " ")):
56
+ whole = SPACES.sub(" ", match.group(0))
57
+ for start in range(0, len(whole), MAX_STATEMENT):
58
+ yield match.start(), whole[start : start + MAX_STATEMENT]
59
+
60
+
61
+ def loader(text: str, fetch: Pattern, sink: Pattern) -> Optional[Tuple[int, str]]:
62
+ """Follow fetched values, statement by statement, into something that executes them.
63
+
64
+ This is a lead, not a proof: no scopes, no calls between files.
65
+ """
66
+ tainted: Dict[str, int] = {}
67
+ for index, (offset, statement) in enumerate(_statements(text)):
68
+ fetched = fetch.search(statement)
69
+ live = {n for n in _names(statement) if index - tainted.get(n, -REACH - 1) <= REACH}
70
+ carries = bool(fetched or live)
71
+ if carries:
72
+ for callback in CALLBACK.finditer(statement):
73
+ if fetched or ".then" in statement or ".on(" in statement:
74
+ for name in _names(next(g for g in callback.groups() if g is not None)):
75
+ tainted[name] = index
76
+ live.add(name)
77
+ for call in list(sink.finditer(statement))[:20]:
78
+ argument = statement[call.end() : call.end() + SINK_WINDOW]
79
+ if call.group(0).endswith("(") and ".loads" in call.group(0).replace(" ", "") and ROUND_TRIP.match(argument):
80
+ continue
81
+ if fetch.search(argument) or live.intersection(_names(argument)):
82
+ return offset + call.start(), statement
83
+ for target, value in APPEND.findall(statement):
84
+ if value in live:
85
+ tainted[target] = index
86
+ live.add(target)
87
+ assign = ASSIGN.match(statement)
88
+ if assign:
89
+ targets = [n for n in _names(assign.group(0)) if n not in live or carries]
90
+ value = statement[assign.end() :]
91
+ if fetch.search(value) or live.intersection(_names(value)):
92
+ for name in targets:
93
+ tainted[name] = index
94
+ elif len(targets) == 1 and not assign.group(0).endswith("+="):
95
+ tainted.pop(targets[0], None)
96
+ if fetched:
97
+ for name in ALIAS.findall(statement):
98
+ tainted[name] = index
99
+ return None
100
+
101
+
102
+ PRIVATE_DATA = re.compile(
103
+ r"\.ssh[/\\]|\bid_(?:rsa|ed25519)\b|\.aws[/\\]credentials|\.git-credentials|\.kube[/\\]config"
104
+ r"|\bLogin Data\b|\bLocal Extension Settings\b|\blogins\.json\b|\bkey4\.db\b|\blogin\.keychain\b"
105
+ r"|\bwallet\.dat\b|\bnkbihfbeogaeaoehlefnkodbefgpgknn\b|\.config[/\\]solana"
106
+ r"|JSON\.stringify\(\s*process\.env\s*\)|json\.dumps\(\s*(?:dict\(\s*)?os\.environ\b"
107
+ )
108
+ SENDS = re.compile(
109
+ r"(?<![\w$])(?:fetch|axios)\s*(?:\.\s*(?:post|put|get)\s*)?\(|\b(?:requests|httpx)\s*\.\s*(?:post|put|get)\s*\(|\burlopen\s*\("
110
+ r"|\bhttps?\s*\.\s*request\s*\(|\bXMLHttpRequest\b|\bcurl\b|\bwget\b|\bInvoke-(?:WebRequest|RestMethod)\b"
111
+ r"|\bsocket\s*\.\s*socket\s*\(|\bnet\s*\.\s*connect\s*\(|discord(?:app)?\.com/api/webhooks|api\.telegram\.org/bot",
112
+ re.I,
113
+ )
114
+ # Commands that install persistence by themselves.
115
+ PERSIST_COMMAND = re.compile(
116
+ r"\bschtasks(?:\.exe)?\b[^\n]{0,80}/create\b|\bcrontab\s+-(?![lr]\b)|\|\s*crontab\b"
117
+ r"|\bsystemctl\s+(?:--user\s+)?enable\b|\blaunchctl\s+(?:load|bootstrap)\b"
118
+ r"|>>\s*[\"']?(?:(?:~|\$HOME|\$\{HOME\})/)?(?:[^\s\"'|;&]{0,80}/)?(?:\.(?:bashrc|zshrc|bash_profile|zprofile|profile)|authorized_keys)\b",
119
+ re.I,
120
+ )
121
+ # Places that persist only when something is written to them.
122
+ PERSIST_PLACE = re.compile(
123
+ r"\bLaunch(?:Agents|Daemons)\b|/etc/cron|\.config/systemd/user|CurrentVersion\\{1,4}Run\b|Start Menu\\{1,4}Programs\\{1,4}Startup"
124
+ r"|\.bashrc\b|\.zshrc\b|\.bash_profile\b|\bauthorized_keys\b",
125
+ re.I,
126
+ )
127
+ WRITES = re.compile(
128
+ r"\b(?:writeFile|appendFile|copyFile|createWriteStream)(?:Sync)?\s*\(|(?<!stdout)(?<!stderr)\.write(?:_text|_bytes|lines)?\s*\(|\bshutil\.(?:copy\w*|move)\s*\("
129
+ r"|\bopen\s*\([^\n]{0,120}[\"'][aw]b?\+?[\"']|\bSetValueEx\b|\breg(?:\.exe)?\s+add\b|\b(?:cp|mv|tee)\s+|\b(?:Set|Add)-Content\b|\bNew-ItemProperty\b"
130
+ )
131
+
132
+
133
+ # Passing a key to ssh uses it; it does not read it.
134
+ SSH_USE = re.compile(
135
+ r"(?:^|[;&|]|\$\()[ \t]*(?:sudo[ \t]+)?(?:(?:ssh|sftp)[ \t](?:[^\n;&|]{0,150}[ \t])?-i[ \t]*|ssh-add[ \t]+|ssh-keygen[ \t][^\n;&|]{0,100}-f[ \t]*)"
136
+ r"[\"']?[^\s\"';&|]{0,80}\Z",
137
+ re.M,
138
+ )
139
+ # How close a write has to be to a place for the place to be what is written.
140
+ NEAR = 400
141
+ MAX_PLACES = 50
142
+
143
+
144
+ def _private(text: str):
145
+ for count, match in enumerate(PRIVATE_DATA.finditer(text)):
146
+ if count == MAX_PLACES:
147
+ return match
148
+ line = max(text.rfind("\n", 0, match.start()) + 1, match.start() - 300)
149
+ if not SSH_USE.search(text[line : match.start()]):
150
+ return match
151
+ return None
152
+
153
+
154
+ def _written(text: str):
155
+ for count, match in enumerate(PERSIST_PLACE.finditer(text)):
156
+ if count == MAX_PLACES or WRITES.search(text, max(match.start() - NEAR, 0), match.end() + NEAR):
157
+ return match
158
+ return None
159
+
160
+
161
+ def analyze(source: Source) -> Iterator[Finding]:
162
+ name = source.code_name
163
+ if not name.endswith(CODE):
164
+ return
165
+ text = source.text
166
+ engines = []
167
+ if name.endswith(JS):
168
+ engines.append((JS_FETCH, JS_SINK_WITH_EXEC if JS_EXEC_IMPORT.search(text) else JS_SINK))
169
+ if name.endswith(PYTHON):
170
+ engines.append((PY_FETCH, PY_SINK))
171
+ for fetch, sink in engines:
172
+ hit = loader(text, fetch, sink) if fetch.search(text) else None
173
+ if hit:
174
+ yield finding(source, "LS701", "high", "Content fetched from the network reaches code execution", hit[0], hit[1].strip())
175
+ private = _private(text)
176
+ persist = PERSIST_COMMAND.search(text)
177
+ if not persist and WRITES.search(text):
178
+ persist = _written(text)
179
+ sends = SENDS.search(text) if private or persist else None
180
+ if private:
181
+ if sends:
182
+ detail = "%s ... %s" % (private.group(0), sends.group(0))
183
+ yield finding(source, "LS702", "high", "Reads private data and can send it over the network", private.start(), detail)
184
+ else:
185
+ yield finding(source, "LS703", "low", "Refers to credentials, keys, browser or wallet data", private.start(), private.group(0))
186
+ if persist:
187
+ severity = "high" if sends else "medium"
188
+ yield finding(source, "LS704", severity, "Installs something that survives a restart or new shell", persist.start(), persist.group(0))