aeppo 0.8.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.
- aeppo/__init__.py +1 -0
- aeppo/cli.py +139 -0
- aeppo/config.py +189 -0
- aeppo/findings.py +86 -0
- aeppo/lexer.py +218 -0
- aeppo/lockfiles.py +315 -0
- aeppo/osv.py +263 -0
- aeppo/report.py +83 -0
- aeppo/rules_actions.py +102 -0
- aeppo/rules_autoexec.py +197 -0
- aeppo/rules_code.py +460 -0
- aeppo/rules_deps.py +57 -0
- aeppo/rules_js.py +73 -0
- aeppo/rules_python.py +212 -0
- aeppo/rules_secrets.py +62 -0
- aeppo/rules_shell.py +171 -0
- aeppo/rules_vulns.py +130 -0
- aeppo/scanner.py +225 -0
- aeppo-0.8.0.dist-info/METADATA +354 -0
- aeppo-0.8.0.dist-info/RECORD +24 -0
- aeppo-0.8.0.dist-info/WHEEL +5 -0
- aeppo-0.8.0.dist-info/entry_points.txt +2 -0
- aeppo-0.8.0.dist-info/licenses/LICENSE +21 -0
- aeppo-0.8.0.dist-info/top_level.txt +1 -0
aeppo/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.8.0"
|
aeppo/cli.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import fnmatch
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from aeppo import __version__, lockfiles, osv, rules_vulns
|
|
7
|
+
from aeppo.config import CONFIG_NAME, find_config, load_config
|
|
8
|
+
from aeppo.report import format_json, format_sarif, format_text
|
|
9
|
+
from aeppo.scanner import SEVERITY_ORDER, _supported, filter_findings, load_baseline, scan_path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_DEFAULT_MAX_FILE_SIZE = 1024 * 1024
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _sarif_uri(target, finding_path):
|
|
16
|
+
"""Make SARIF locations relative to the working directory (the repository root in CI)."""
|
|
17
|
+
location = target if target.is_file() else target / finding_path
|
|
18
|
+
resolved = location.resolve()
|
|
19
|
+
try:
|
|
20
|
+
return resolved.relative_to(Path.cwd().resolve()).as_posix()
|
|
21
|
+
except ValueError:
|
|
22
|
+
return resolved.as_uri()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _settings(args):
|
|
26
|
+
"""Merge .aeppo.toml with command-line options; options given on the command line win."""
|
|
27
|
+
config = {}
|
|
28
|
+
config_path = None
|
|
29
|
+
if not args.no_config:
|
|
30
|
+
if args.config:
|
|
31
|
+
config_path = args.config
|
|
32
|
+
else:
|
|
33
|
+
# One directory target: search from it. Files or several targets (pre-commit): from cwd.
|
|
34
|
+
start = args.paths[0] if len(args.paths) == 1 and args.paths[0].is_dir() else Path.cwd()
|
|
35
|
+
config_path = find_config(start)
|
|
36
|
+
if config_path:
|
|
37
|
+
config = load_config(config_path)
|
|
38
|
+
baseline_path = args.baseline or config.get("baseline")
|
|
39
|
+
return {
|
|
40
|
+
"config_path": config_path,
|
|
41
|
+
"exclude": config.get("exclude", []) + args.exclude,
|
|
42
|
+
"disable": config.get("disable", []) + [rule_id.upper() for rule_id in args.disable],
|
|
43
|
+
"min_severity": args.min_severity or config.get("min_severity", "low"),
|
|
44
|
+
"max_file_size": args.max_file_size or config.get("max_file_size", _DEFAULT_MAX_FILE_SIZE),
|
|
45
|
+
"baseline": load_baseline(baseline_path) if baseline_path else None,
|
|
46
|
+
"osv": args.osv or config.get("osv", False),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _scan_targets(args, settings, errors):
|
|
51
|
+
"""Scan every target; return (finding, target) pairs so SARIF can resolve each location."""
|
|
52
|
+
results = []
|
|
53
|
+
for target in args.paths:
|
|
54
|
+
if target.is_file():
|
|
55
|
+
if any(fnmatch.fnmatch(target.as_posix(), pattern) for pattern in settings["exclude"]):
|
|
56
|
+
continue
|
|
57
|
+
if not _supported(target) and (args.skip_unsupported or (settings["osv"] and lockfiles.kind(target))):
|
|
58
|
+
continue
|
|
59
|
+
findings = scan_path(target, excludes=settings["exclude"], max_file_size=settings["max_file_size"], errors=errors)
|
|
60
|
+
results.extend((finding, target) for finding in findings)
|
|
61
|
+
return results
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _check_dependencies(args, settings, results, errors):
|
|
65
|
+
"""Add VULN001/MAL001 findings from OSV.dev to ``results``; return False if OSV failed."""
|
|
66
|
+
targets = [target for target in args.paths if not (target.is_file() and any(fnmatch.fnmatch(target.as_posix(), pattern) for pattern in settings["exclude"]))]
|
|
67
|
+
client = osv.Client(cache_dir=osv.default_cache_dir())
|
|
68
|
+
try:
|
|
69
|
+
findings, package_count, lockfile_count = rules_vulns.scan(targets, client, settings["exclude"], errors)
|
|
70
|
+
except osv.OSVError as error:
|
|
71
|
+
print("aeppo: error: could not check dependencies with OSV.dev: {}".format(error), file=sys.stderr)
|
|
72
|
+
return False
|
|
73
|
+
results.extend(findings)
|
|
74
|
+
print("aeppo: checked {} package version(s) from {} lockfile(s) against OSV.dev".format(package_count, lockfile_count), file=sys.stderr)
|
|
75
|
+
return True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def main(argv=None):
|
|
79
|
+
parser = argparse.ArgumentParser(prog="aeppo", description="Statically scan source code for suspicious patterns.")
|
|
80
|
+
parser.add_argument("--version", action="version", version="aeppo {}".format(__version__))
|
|
81
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
82
|
+
scan_parser = subparsers.add_parser("scan", help="scan files or directories")
|
|
83
|
+
scan_parser.add_argument("paths", nargs="+", type=Path, metavar="PATH", help="file or directory to scan; may be repeated")
|
|
84
|
+
scan_parser.add_argument("--format", choices=["text", "json", "sarif"], default="text")
|
|
85
|
+
scan_parser.add_argument("--exclude", action="append", default=[], help="exclude a relative path glob; may be repeated")
|
|
86
|
+
scan_parser.add_argument("--max-file-size", type=int, default=None, metavar="BYTES", help="skip files larger than this (default: 1048576)")
|
|
87
|
+
scan_parser.add_argument("--min-severity", choices=list(SEVERITY_ORDER), default=None, help="report only findings at or above this severity (default: low)")
|
|
88
|
+
scan_parser.add_argument("--disable", action="append", default=[], metavar="RULE", help="turn off a rule ID; may be repeated")
|
|
89
|
+
scan_parser.add_argument("--baseline", type=Path, metavar="FILE", help="ignore findings recorded in a JSON file written by --format json")
|
|
90
|
+
scan_parser.add_argument("--output", type=Path, metavar="FILE", help="write the report to FILE instead of standard output")
|
|
91
|
+
scan_parser.add_argument("--config", type=Path, metavar="FILE", help="read settings from FILE instead of searching for {}".format(CONFIG_NAME))
|
|
92
|
+
scan_parser.add_argument("--no-config", action="store_true", help="ignore {} files".format(CONFIG_NAME))
|
|
93
|
+
scan_parser.add_argument("--osv", action="store_true", help="look up lockfile dependency versions in OSV.dev for known vulnerabilities and malware (sends package names and versions)")
|
|
94
|
+
scan_parser.add_argument("--skip-unsupported", action="store_true", help="skip file targets aeppo cannot scan instead of failing (used by pre-commit)")
|
|
95
|
+
args = parser.parse_args(argv)
|
|
96
|
+
|
|
97
|
+
errors = []
|
|
98
|
+
try:
|
|
99
|
+
if args.max_file_size is not None and args.max_file_size <= 0:
|
|
100
|
+
raise ValueError("--max-file-size must be greater than zero")
|
|
101
|
+
settings = _settings(args)
|
|
102
|
+
results = _scan_targets(args, settings, errors)
|
|
103
|
+
osv_failed = settings["osv"] and not _check_dependencies(args, settings, results, errors)
|
|
104
|
+
kept = filter_findings(
|
|
105
|
+
[finding for finding, _target in results],
|
|
106
|
+
min_severity=settings["min_severity"],
|
|
107
|
+
baseline=settings["baseline"],
|
|
108
|
+
disabled=settings["disable"],
|
|
109
|
+
)
|
|
110
|
+
except (OSError, ValueError) as error:
|
|
111
|
+
print("aeppo: {}".format(error), file=sys.stderr)
|
|
112
|
+
return 2
|
|
113
|
+
for message in errors:
|
|
114
|
+
print("aeppo: warning: skipped {}".format(message), file=sys.stderr)
|
|
115
|
+
|
|
116
|
+
targets = {id(finding): target for finding, target in results}
|
|
117
|
+
if args.format == "json":
|
|
118
|
+
report = format_json(kept)
|
|
119
|
+
elif args.format == "sarif":
|
|
120
|
+
report = format_sarif(kept, uri_for=lambda finding: _sarif_uri(targets[id(finding)], finding.path))
|
|
121
|
+
else:
|
|
122
|
+
report = format_text(kept)
|
|
123
|
+
|
|
124
|
+
if args.output:
|
|
125
|
+
try:
|
|
126
|
+
args.output.write_text(report + "\n", encoding="utf-8")
|
|
127
|
+
except OSError as error:
|
|
128
|
+
print("aeppo: cannot write {}: {}".format(args.output, error.strerror or error), file=sys.stderr)
|
|
129
|
+
return 2
|
|
130
|
+
print("aeppo: wrote {} finding(s) to {}".format(len(kept), args.output), file=sys.stderr)
|
|
131
|
+
else:
|
|
132
|
+
print(report)
|
|
133
|
+
if osv_failed:
|
|
134
|
+
return 2
|
|
135
|
+
return 1 if kept else 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
if __name__ == "__main__":
|
|
139
|
+
sys.exit(main())
|
aeppo/config.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Project configuration from ``.aeppo.toml``.
|
|
2
|
+
|
|
3
|
+
Supported top-level keys::
|
|
4
|
+
|
|
5
|
+
exclude = ["tests/fixtures/**"] # relative path globs, added to --exclude
|
|
6
|
+
disable = ["GHA003"] # rule IDs to turn off
|
|
7
|
+
min-severity = "medium" # low | medium | high
|
|
8
|
+
max-file-size = 1048576 # bytes
|
|
9
|
+
baseline = "aeppo-baseline.json" # relative to the config file
|
|
10
|
+
osv = true # look up lockfile dependencies in OSV.dev (like --osv)
|
|
11
|
+
|
|
12
|
+
Python 3.11+ parses the file with ``tomllib``. Older versions use a small parser for the subset
|
|
13
|
+
above (strings, integers, booleans, arrays), so aeppo keeps no runtime dependencies. Unknown keys
|
|
14
|
+
and unknown rule IDs are errors, so a typo cannot silently turn a setting off.
|
|
15
|
+
"""
|
|
16
|
+
import re
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from aeppo.scanner import RULES, SEVERITY_ORDER
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
CONFIG_NAME = ".aeppo.toml"
|
|
23
|
+
|
|
24
|
+
_KEYS = {
|
|
25
|
+
"exclude": "a list of path globs",
|
|
26
|
+
"disable": "a list of rule IDs",
|
|
27
|
+
"min-severity": "one of low, medium, high",
|
|
28
|
+
"max-file-size": "a positive integer",
|
|
29
|
+
"baseline": "a path string",
|
|
30
|
+
"osv": "true or false",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def find_config(start):
|
|
35
|
+
"""Return the nearest ``.aeppo.toml`` from ``start`` upward, stopping at a repository root."""
|
|
36
|
+
directory = Path(start).resolve()
|
|
37
|
+
if not directory.is_dir():
|
|
38
|
+
directory = directory.parent
|
|
39
|
+
for candidate in (directory, *directory.parents):
|
|
40
|
+
config = candidate / CONFIG_NAME
|
|
41
|
+
if config.is_file():
|
|
42
|
+
return config
|
|
43
|
+
if (candidate / ".git").exists():
|
|
44
|
+
return None
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def load_config(path):
|
|
49
|
+
"""Read and validate a config file; return a dict with normalised values."""
|
|
50
|
+
path = Path(path)
|
|
51
|
+
raw = _parse(path.read_text(encoding="utf-8"))
|
|
52
|
+
unknown = sorted(set(raw) - set(_KEYS))
|
|
53
|
+
if unknown:
|
|
54
|
+
raise ValueError("{}: unknown key(s) {}; expected {}".format(path, ", ".join(unknown), ", ".join(sorted(_KEYS))))
|
|
55
|
+
config = {}
|
|
56
|
+
for key in ("exclude", "disable"):
|
|
57
|
+
if key in raw:
|
|
58
|
+
value = raw[key]
|
|
59
|
+
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
|
60
|
+
raise ValueError("{}: {} must be {}".format(path, key, _KEYS[key]))
|
|
61
|
+
config[key] = value
|
|
62
|
+
if "disable" in config:
|
|
63
|
+
config["disable"] = [rule_id.upper() for rule_id in config["disable"]]
|
|
64
|
+
unknown_rules = sorted(set(config["disable"]) - set(RULES))
|
|
65
|
+
if unknown_rules:
|
|
66
|
+
raise ValueError("{}: unknown rule ID(s) in disable: {}".format(path, ", ".join(unknown_rules)))
|
|
67
|
+
if "min-severity" in raw:
|
|
68
|
+
if raw["min-severity"] not in SEVERITY_ORDER:
|
|
69
|
+
raise ValueError("{}: min-severity must be {}".format(path, _KEYS["min-severity"]))
|
|
70
|
+
config["min_severity"] = raw["min-severity"]
|
|
71
|
+
if "max-file-size" in raw:
|
|
72
|
+
value = raw["max-file-size"]
|
|
73
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
74
|
+
raise ValueError("{}: max-file-size must be {}".format(path, _KEYS["max-file-size"]))
|
|
75
|
+
config["max_file_size"] = value
|
|
76
|
+
if "osv" in raw:
|
|
77
|
+
if not isinstance(raw["osv"], bool):
|
|
78
|
+
raise ValueError("{}: osv must be {}".format(path, _KEYS["osv"]))
|
|
79
|
+
config["osv"] = raw["osv"]
|
|
80
|
+
if "baseline" in raw:
|
|
81
|
+
if not isinstance(raw["baseline"], str) or not raw["baseline"]:
|
|
82
|
+
raise ValueError("{}: baseline must be {}".format(path, _KEYS["baseline"]))
|
|
83
|
+
config["baseline"] = (path.parent / raw["baseline"]).resolve()
|
|
84
|
+
return config
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _parse(text):
|
|
88
|
+
try:
|
|
89
|
+
import tomllib
|
|
90
|
+
except ImportError:
|
|
91
|
+
return parse_minimal_toml(text)
|
|
92
|
+
return tomllib.loads(text)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
_BARE_KEY = re.compile(r"[A-Za-z0-9_-]+")
|
|
96
|
+
_SCALAR = re.compile(r"[+-]?\d[\d_]*\b|true\b|false\b")
|
|
97
|
+
_ESCAPES = {'"': '"', "\\": "\\", "n": "\n", "t": "\t", "r": "\r", "b": "\b", "f": "\f"}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def parse_minimal_toml(text):
|
|
101
|
+
"""Parse top-level ``key = value`` pairs (strings, integers, booleans, arrays)."""
|
|
102
|
+
result = {}
|
|
103
|
+
position = _skip(text, 0)
|
|
104
|
+
while position < len(text):
|
|
105
|
+
if text[position] == "[":
|
|
106
|
+
raise ValueError("line {}: tables are not supported; use top-level keys".format(_line_of(text, position)))
|
|
107
|
+
key = _BARE_KEY.match(text, position)
|
|
108
|
+
if not key:
|
|
109
|
+
raise ValueError("line {}: expected a key".format(_line_of(text, position)))
|
|
110
|
+
position = _skip(text, key.end(), newlines=False)
|
|
111
|
+
if position >= len(text) or text[position] != "=":
|
|
112
|
+
raise ValueError("line {}: expected '=' after {}".format(_line_of(text, position), key.group()))
|
|
113
|
+
value, position = _value(text, _skip(text, position + 1, newlines=False))
|
|
114
|
+
rest = _skip(text, position, newlines=False)
|
|
115
|
+
if rest < len(text) and text[rest] not in "\r\n":
|
|
116
|
+
raise ValueError("line {}: unexpected text after the value".format(_line_of(text, rest)))
|
|
117
|
+
if key.group() in result:
|
|
118
|
+
raise ValueError("line {}: duplicate key {}".format(_line_of(text, key.start()), key.group()))
|
|
119
|
+
result[key.group()] = value
|
|
120
|
+
position = _skip(text, rest)
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _skip(text, position, newlines=True):
|
|
125
|
+
while position < len(text):
|
|
126
|
+
char = text[position]
|
|
127
|
+
if char in " \t" or (newlines and char in "\r\n"):
|
|
128
|
+
position += 1
|
|
129
|
+
elif char == "#":
|
|
130
|
+
while position < len(text) and text[position] != "\n":
|
|
131
|
+
position += 1
|
|
132
|
+
else:
|
|
133
|
+
break
|
|
134
|
+
return position
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _value(text, position):
|
|
138
|
+
if position >= len(text):
|
|
139
|
+
raise ValueError("line {}: missing value".format(_line_of(text, position)))
|
|
140
|
+
char = text[position]
|
|
141
|
+
if char == '"':
|
|
142
|
+
out = []
|
|
143
|
+
position += 1
|
|
144
|
+
while position < len(text) and text[position] != '"':
|
|
145
|
+
if text[position] in "\r\n":
|
|
146
|
+
break
|
|
147
|
+
if text[position] == "\\":
|
|
148
|
+
escape = text[position + 1 : position + 2]
|
|
149
|
+
if escape not in _ESCAPES:
|
|
150
|
+
raise ValueError("line {}: unsupported escape \\{}".format(_line_of(text, position), escape))
|
|
151
|
+
out.append(_ESCAPES[escape])
|
|
152
|
+
position += 2
|
|
153
|
+
else:
|
|
154
|
+
out.append(text[position])
|
|
155
|
+
position += 1
|
|
156
|
+
if position >= len(text) or text[position] != '"':
|
|
157
|
+
raise ValueError("line {}: unterminated string".format(_line_of(text, position)))
|
|
158
|
+
return "".join(out), position + 1
|
|
159
|
+
if char == "'":
|
|
160
|
+
end = text.find("'", position + 1)
|
|
161
|
+
if end == -1 or "\n" in text[position:end]:
|
|
162
|
+
raise ValueError("line {}: unterminated string".format(_line_of(text, position)))
|
|
163
|
+
return text[position + 1 : end], end + 1
|
|
164
|
+
if char == "[":
|
|
165
|
+
items = []
|
|
166
|
+
position = _skip(text, position + 1)
|
|
167
|
+
while True:
|
|
168
|
+
if position >= len(text):
|
|
169
|
+
raise ValueError("unterminated array")
|
|
170
|
+
if text[position] == "]":
|
|
171
|
+
return items, position + 1
|
|
172
|
+
item, position = _value(text, position)
|
|
173
|
+
items.append(item)
|
|
174
|
+
position = _skip(text, position)
|
|
175
|
+
if position < len(text) and text[position] == ",":
|
|
176
|
+
position = _skip(text, position + 1)
|
|
177
|
+
elif position < len(text) and text[position] != "]":
|
|
178
|
+
raise ValueError("line {}: expected ',' or ']' in array".format(_line_of(text, position)))
|
|
179
|
+
scalar = _SCALAR.match(text, position)
|
|
180
|
+
if not scalar:
|
|
181
|
+
raise ValueError("line {}: unsupported value".format(_line_of(text, position)))
|
|
182
|
+
token = scalar.group()
|
|
183
|
+
if token in ("true", "false"):
|
|
184
|
+
return token == "true", scalar.end()
|
|
185
|
+
return int(token.replace("_", "")), scalar.end()
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _line_of(text, position):
|
|
189
|
+
return text.count("\n", 0, position) + 1
|
aeppo/findings.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Finding objects and the rule registry shared by every rule module."""
|
|
2
|
+
from collections import namedtuple
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
SEVERITY_ORDER = {"low": 0, "medium": 1, "high": 2}
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Finding:
|
|
9
|
+
def __init__(self, path, line, rule_id, message, severity="medium", confidence="medium", category="code-risk", recommendation="Review this finding in context.", fingerprint=""):
|
|
10
|
+
self.path = path
|
|
11
|
+
self.line = line
|
|
12
|
+
self.rule_id = rule_id
|
|
13
|
+
self.message = message
|
|
14
|
+
self.severity = severity
|
|
15
|
+
self.confidence = confidence
|
|
16
|
+
self.category = category
|
|
17
|
+
self.recommendation = recommendation
|
|
18
|
+
self.fingerprint = fingerprint
|
|
19
|
+
|
|
20
|
+
def __eq__(self, other):
|
|
21
|
+
return isinstance(other, Finding) and self.__dict__ == other.__dict__
|
|
22
|
+
|
|
23
|
+
def __repr__(self):
|
|
24
|
+
return "Finding({!r}, {!r}, {!r}, {!r})".format(self.path, self.line, self.rule_id, self.message)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
Rule = namedtuple("Rule", "message severity confidence category recommendation")
|
|
28
|
+
|
|
29
|
+
_REVOKE = "Revoke and rotate it if it is real; do not commit credentials."
|
|
30
|
+
|
|
31
|
+
RULES = {
|
|
32
|
+
"PY001": Rule("Use of os.system or os.popen may execute a shell command with unsafe input.", "medium", "medium", "command-execution", "Prefer argument-list APIs such as subprocess.run([...]) and validate untrusted input."),
|
|
33
|
+
"PY002": Rule("Dynamic code execution can run attacker-controlled input.", "high", "medium", "dynamic-code", "Avoid dynamic evaluation or strictly constrain and validate the input."),
|
|
34
|
+
"PY003": Rule("subprocess call runs its command through a shell.", "high", "medium", "command-execution", "Pass an argument list without shell=True, or quote untrusted values with shlex.quote."),
|
|
35
|
+
"PY004": Rule("Unpickling can execute arbitrary code when the data is untrusted.", "high", "medium", "unsafe-deserialization", "Only unpickle trusted data; prefer JSON or another data-only format."),
|
|
36
|
+
"PY005": Rule("yaml.load without a safe loader can construct arbitrary Python objects.", "high", "medium", "unsafe-deserialization", "Use yaml.safe_load or pass Loader=yaml.SafeLoader."),
|
|
37
|
+
"PY006": Rule("Spawns an interactive shell, a common reverse-shell or backdoor pattern.", "high", "medium", "backdoor", "Confirm why the program needs an interactive shell and remove it if it is unexpected."),
|
|
38
|
+
"JS001": Rule("Use of eval may execute dynamically constructed JavaScript.", "high", "medium", "dynamic-code", "Avoid eval and use explicit parsing or dispatch."),
|
|
39
|
+
"JS002": Rule("Shell command execution may be unsafe when arguments include untrusted input.", "high", "medium", "command-execution", "Prefer execFile/spawn with an argument array and validate untrusted input."),
|
|
40
|
+
"JS003": Rule("Function constructor or string-based timer evaluates code at runtime.", "high", "medium", "dynamic-code", "Pass a function instead of a code string and avoid new Function."),
|
|
41
|
+
"SEC001": Rule("Possible AWS access key ID found.", "high", "medium", "secret", _REVOKE),
|
|
42
|
+
"SEC002": Rule("Possible GitHub token found.", "high", "medium", "secret", _REVOKE),
|
|
43
|
+
"SEC003": Rule("Private key material header found.", "high", "high", "secret", "Protect the key and rotate it if it was exposed."),
|
|
44
|
+
"SEC004": Rule("Possible Slack token found.", "high", "medium", "secret", _REVOKE),
|
|
45
|
+
"SEC005": Rule("Possible Stripe live secret or restricted key found.", "high", "high", "secret", _REVOKE),
|
|
46
|
+
"SEC006": Rule("Possible OpenAI API key found.", "high", "medium", "secret", _REVOKE),
|
|
47
|
+
"SEC007": Rule("Possible Anthropic API key found.", "high", "high", "secret", _REVOKE),
|
|
48
|
+
"SEC008": Rule("Possible Google API key found.", "high", "medium", "secret", _REVOKE),
|
|
49
|
+
"DEP001": Rule("Dependency has no version constraint.", "low", "high", "dependency-management", "Pin dependencies to reviewed versions and use a lockfile where possible."),
|
|
50
|
+
"DEP002": Rule("Dependency uses a direct URL, VCS, or local path reference.", "medium", "high", "supply-chain", "Verify the source and pin it to an immutable commit or trusted artifact."),
|
|
51
|
+
"DEP003": Rule("Package defines an install lifecycle script that runs during installation.", "medium", "high", "dependency-install-script", "Inspect the script and its transitive commands before installing dependencies."),
|
|
52
|
+
"SH001": Rule("Shell script downloads remote content and runs it.", "high", "high", "supply-chain", "Download to a file, verify its checksum or signature, and review it before running."),
|
|
53
|
+
"SH002": Rule("Shell script opens a reverse shell.", "high", "medium", "backdoor", "Remove it unless the script is an intended remote-access tool."),
|
|
54
|
+
"SH003": Rule("Shell script decodes an encoded payload and runs it.", "high", "medium", "obfuscation", "Decode the payload and review it; ship readable scripts instead of encoded ones."),
|
|
55
|
+
"SH004": Rule("Shell script installs persistence (SSH authorized key or cron entry).", "high", "medium", "backdoor", "Confirm the key or job is expected; installers should not add access or schedules silently."),
|
|
56
|
+
"SH005": Rule("Shell script modifies a shell startup file.", "low", "low", "persistence", "Review what is appended; installers commonly add PATH entries, but this can also hide persistence."),
|
|
57
|
+
"GHA001": Rule("pull_request_target workflow checks out or fetches code from the pull request.", "high", "high", "ci-security", "Do not run untrusted PR code with pull_request_target; use pull_request, or split the privileged step into a workflow_run job."),
|
|
58
|
+
"GHA002": Rule("Untrusted GitHub context is expanded directly into a script.", "high", "high", "ci-security", "Pass the value through an environment variable (env: TITLE: ${{ ... }}) and quote \"$TITLE\" in the script."),
|
|
59
|
+
"GHA003": Rule("Action is referenced by a mutable tag or branch instead of a full commit SHA.", "medium", "high", "supply-chain", "Pin the action to a full 40-character commit SHA and note the version in a comment."),
|
|
60
|
+
"AUTO001": Rule("VS Code task runs automatically when the folder is opened (runOn: folderOpen).", "medium", "high", "auto-exec", "Check the task's command before trusting the workspace; automatic tasks run as soon as the folder opens."),
|
|
61
|
+
"AUTO002": Rule("Dev container initializeCommand runs on the host machine, outside the container.", "medium", "high", "auto-exec", "Review the command before opening the folder in a dev container; it runs with your local user's access."),
|
|
62
|
+
"BLD001": Rule("Build script runs an external command.", "medium", "medium", "build-exec", "Check what the command does and when it runs; build scripts also run on IDE import or project open."),
|
|
63
|
+
"BLD002": Rule("Build script downloads content from the network.", "high", "medium", "build-exec", "Builds should not fetch and use remote content implicitly; vendor it or pin it to a checksum."),
|
|
64
|
+
"GHA004": Rule("Workflow grants write-all permissions.", "medium", "high", "ci-security", "Grant only the permissions each job needs, starting from contents: read."),
|
|
65
|
+
"DEP004": Rule("Install script downloads remote content and pipes it into an interpreter.", "high", "high", "supply-chain", "Do not install until the downloaded script is reviewed; vendor it or pin it to a verified checksum."),
|
|
66
|
+
"GO001": Rule("exec.Command runs a shell with a command built at runtime.", "high", "medium", "command-execution", "Pass the program and its arguments separately (exec.Command(\"git\", \"log\", ref)) instead of sh -c with a built string."),
|
|
67
|
+
"RS001": Rule("std::process::Command runs a shell with a command built at runtime.", "high", "medium", "command-execution", "Run the program directly with .arg() for each argument instead of sh -c with a formatted string."),
|
|
68
|
+
"JV001": Rule("Process API runs a shell with a command built at runtime.", "high", "medium", "command-execution", "Pass the program and each argument as separate strings to ProcessBuilder, without sh -c."),
|
|
69
|
+
"JV002": Rule("Runtime.exec runs a command string built at runtime.", "medium", "medium", "command-execution", "Use ProcessBuilder with a fixed program and separate, validated arguments."),
|
|
70
|
+
"JV003": Rule("ObjectInputStream.readObject deserializes data that can execute code through gadget classes.", "medium", "medium", "unsafe-deserialization", "Do not deserialize untrusted data; use a data format such as JSON, or an ObjectInputFilter allow-list."),
|
|
71
|
+
"PHP001": Rule("PHP evaluates code at runtime (eval, create_function, assert or preg_replace /e).", "high", "medium", "dynamic-code", "Remove the dynamic evaluation; web shells often hide behind eval of decoded data."),
|
|
72
|
+
"PHP002": Rule("PHP runs a shell command built at runtime.", "medium", "medium", "command-execution", "Avoid the shell; if it is required, pass every value through escapeshellarg and never use request data directly."),
|
|
73
|
+
"PHP003": Rule("unserialize on data that may be attacker controlled can instantiate arbitrary objects.", "low", "medium", "unsafe-deserialization", "Use json_decode, or pass ['allowed_classes' => false] to unserialize."),
|
|
74
|
+
"RB001": Rule("Ruby evaluates a string as code at runtime.", "high", "medium", "dynamic-code", "Avoid eval; use explicit dispatch (public_send with an allow-list) or a parser."),
|
|
75
|
+
"RB002": Rule("Ruby runs a shell command built at runtime.", "medium", "medium", "command-execution", "Use the argv form (system(\"git\", \"log\", ref)) so no shell parses the values."),
|
|
76
|
+
"RB003": Rule("Marshal.load deserializes data that can execute code.", "medium", "medium", "unsafe-deserialization", "Only load Marshal data you produced yourself; use JSON for anything that crosses a trust boundary."),
|
|
77
|
+
"NET001": Rule("Program connects to the network and hands the connection to a shell (reverse-shell pattern).", "high", "medium", "backdoor", "Remove it unless the program is an intended remote-access tool."),
|
|
78
|
+
"VULN001": Rule("Dependency version has a known vulnerability.", "medium", "high", "vulnerable-dependency", "Upgrade to a fixed version and regenerate the lockfile."),
|
|
79
|
+
"MAL001": Rule("Dependency version is listed as a malicious package.", "high", "high", "malware", "Do not install it; if it was installed, treat the machine and its credentials as compromised."),
|
|
80
|
+
"SRC001": Rule("Bidirectional Unicode control character can make code render differently from how it runs (Trojan Source).", "high", "medium", "obfuscation", "Remove the control character, or confirm it only appears inside an intended string literal."),
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def make_finding(path, line, rule_id, message=None):
|
|
85
|
+
rule = RULES[rule_id]
|
|
86
|
+
return Finding(path, line, rule_id, message or rule.message, rule.severity, rule.confidence, rule.category, rule.recommendation)
|
aeppo/lexer.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""A small lexer for Go, Rust, Java/Kotlin, PHP and Ruby source.
|
|
2
|
+
|
|
3
|
+
It does not parse anything; it only finds comments and string literals so pattern rules can tell
|
|
4
|
+
code from text. ``lex`` returns a ``Source`` with two views of the text, both the same length as
|
|
5
|
+
the input so offsets and line numbers line up:
|
|
6
|
+
|
|
7
|
+
* ``code``: comments blanked out, string literals kept;
|
|
8
|
+
* ``masked``: comments and the inside of string literals blanked out, delimiters kept.
|
|
9
|
+
|
|
10
|
+
Rules search ``masked`` for call shapes (so ``"exec.Command("`` inside a string or a comment never
|
|
11
|
+
matches) and read arguments back from ``code``. Each language's tokens are one combined regular
|
|
12
|
+
expression, so the work happens in the regex engine rather than in a per-character Python loop.
|
|
13
|
+
"""
|
|
14
|
+
import bisect
|
|
15
|
+
import re
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# Shared token shapes.
|
|
19
|
+
# Interpolation with up to two levels of nested braces: "#{x ? "#{y}" : z}".
|
|
20
|
+
_RUBY_INTERPOLATION = r"#\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}"
|
|
21
|
+
_LINE_COMMENT = r"//[^\n]*"
|
|
22
|
+
_BLOCK_COMMENT = r"/\*.*?(?:\*/|\Z)"
|
|
23
|
+
_DOUBLE = r'"(?:\\.|[^"\\\n])*"'
|
|
24
|
+
_CHAR = r"'(?:\\.|[^'\\\n])*'"
|
|
25
|
+
|
|
26
|
+
_TOKENS = {
|
|
27
|
+
"go": (
|
|
28
|
+
("comment", _LINE_COMMENT + "|" + _BLOCK_COMMENT),
|
|
29
|
+
("string", _DOUBLE + "|" + _CHAR + r"|`[^`]*`"),
|
|
30
|
+
),
|
|
31
|
+
"rust": (
|
|
32
|
+
("comment", _LINE_COMMENT + "|" + _BLOCK_COMMENT),
|
|
33
|
+
# Raw strings r#"..."#, byte strings, and char literals ('a', '\n'); a lifetime ('a) has no
|
|
34
|
+
# closing quote right after one character, so it stays code.
|
|
35
|
+
("string", r'b?r(?P<hashes>#*)".*?"(?P=hashes)|b?"(?:\\.|[^"\\])*"|b?\'(?:\\(?:x[0-9A-Fa-f]{2}|u\{[0-9A-Fa-f]+\}|.)|[^\\\'\n])\''),
|
|
36
|
+
),
|
|
37
|
+
"java": (
|
|
38
|
+
("comment", _LINE_COMMENT + "|" + _BLOCK_COMMENT),
|
|
39
|
+
# Text blocks and Kotlin raw strings, then strings with Kotlin ${...} templates.
|
|
40
|
+
("string", r'""".*?"""|"(?:\\.|\$\{(?:[^{}\n]|\{[^{}\n]*\})*\}|\$(?!\{)|[^"\\\n$])*"|' + _CHAR),
|
|
41
|
+
),
|
|
42
|
+
"php": (
|
|
43
|
+
# Everything outside <?php ... ?> is HTML; it is blanked like a comment. A '#' comment
|
|
44
|
+
# is not an attribute (#[...]).
|
|
45
|
+
("comment", r"\?>.*?(?:<\?(?:php\b|=)?|\Z)|" + _LINE_COMMENT + r"|#(?!\[)[^\n]*|" + _BLOCK_COMMENT),
|
|
46
|
+
("heredoc", r"<<<[ \t]*(?P<hq>[\"']?)(?P<hid>[A-Za-z_]\w*)(?P=hq)(?=\n(?P<body>.*?)(?P<hend>^[ \t]*(?P=hid)\b))"),
|
|
47
|
+
("string", r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\""),
|
|
48
|
+
("shell", r"`(?:\\.|[^`\\])*`"),
|
|
49
|
+
),
|
|
50
|
+
"ruby": (
|
|
51
|
+
("comment", r"^=begin\b.*?(?:^=end\b[^\n]*|\Z)|^__END__\n.*\Z|#[^\n]*"),
|
|
52
|
+
# The heredoc token is only the <<~ID marker; its body (from the next line to the
|
|
53
|
+
# terminator) is captured by the lookahead and blanked separately, so the rest of the
|
|
54
|
+
# marker's line (``run(<<~SH, x)``) is still read as code.
|
|
55
|
+
("heredoc", r"<<[~-]?(?P<hq>[\"'`]?)(?P<hid>[A-Z_][A-Z0-9_]*)(?P=hq)(?=[^\n]*\n(?P<body>.*?)(?P<hend>^[ \t]*(?P=hid)$))"),
|
|
56
|
+
# Regex literals: a '/' where an operand is expected and not followed by a space.
|
|
57
|
+
("regex", r"(?:(?<=[(,=~!&|{\[;?:])|(?<=^)|(?<=[(,=~!&|{\[;?:\s]\s)|(?<=\w\s))/(?![\s=])(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n])+/[imxounse]*"),
|
|
58
|
+
("string", r"'(?:\\.|[^'\\])*'|\"(?:\\.|" + _RUBY_INTERPOLATION + r"|#(?!\{)|[^\"\\#])*\""
|
|
59
|
+
r"|%[qQwWiI](?:\((?:\\.|[^)\\])*\)|\[(?:\\.|[^\]\\])*\]|\{(?:\\.|[^}\\])*\}|<(?:\\.|[^>\\])*>|\|(?:\\.|[^|\\])*\|)"),
|
|
60
|
+
("shell", r"`(?:\\.|" + _RUBY_INTERPOLATION + r"|#(?!\{)|[^`\\#])*`|%x(?:\((?:\\.|[^)\\])*\)|\[(?:\\.|[^\]\\])*\]|\{(?:\\.|[^}\\])*\}|\|(?:\\.|[^|\\])*\|)"),
|
|
61
|
+
),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
_KINDS = ("comment", "heredoc", "regex", "string", "shell")
|
|
65
|
+
|
|
66
|
+
_PATTERNS = {
|
|
67
|
+
language: re.compile("|".join("(?P<{}>{})".format(kind, pattern) for kind, pattern in tokens), re.DOTALL | re.MULTILINE)
|
|
68
|
+
for language, tokens in _TOKENS.items()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
_BLANK = re.compile(r"[^\n]")
|
|
72
|
+
_LITERAL_BODY = re.compile(r'^(?:[br]{0,2}#*)?("""|["\'`])(.*)\1#*$', re.DOTALL)
|
|
73
|
+
_PERCENT_BODY = re.compile(r"^%[qQwWiIx](.)(.*).$", re.DOTALL)
|
|
74
|
+
_INTERPOLATION = {
|
|
75
|
+
"ruby": re.compile(r"#\{"),
|
|
76
|
+
"java": re.compile(r"\$[{A-Za-z_]"), # Kotlin string templates
|
|
77
|
+
"php": re.compile(r"\$[{A-Za-z_]|\{\$"),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Token:
|
|
82
|
+
__slots__ = ("start", "end", "kind", "text", "body")
|
|
83
|
+
|
|
84
|
+
def __init__(self, start, end, kind, text, body=None):
|
|
85
|
+
self.start, self.end, self.kind, self.text, self.body = start, end, kind, text, body
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Source:
|
|
89
|
+
def __init__(self, language, text, code, masked, tokens):
|
|
90
|
+
self.language = language
|
|
91
|
+
self.text = text
|
|
92
|
+
self.code = code
|
|
93
|
+
self.masked = masked
|
|
94
|
+
self.strings = [token for token in tokens if token.kind != "comment"]
|
|
95
|
+
self._by_start = {token.start: token for token in self.strings}
|
|
96
|
+
self._newlines = [index for index, char in enumerate(text) if char == "\n"]
|
|
97
|
+
|
|
98
|
+
def line_of(self, offset):
|
|
99
|
+
return bisect.bisect_right(self._newlines, offset - 1) + 1
|
|
100
|
+
|
|
101
|
+
def literal(self, start, end):
|
|
102
|
+
"""The value of a plain string literal spanning exactly ``[start, end)`` (ignoring
|
|
103
|
+
surrounding whitespace), or None for anything else, including interpolated strings."""
|
|
104
|
+
while start < end and self.code[start].isspace():
|
|
105
|
+
start += 1
|
|
106
|
+
while end > start and self.code[end - 1].isspace():
|
|
107
|
+
end -= 1
|
|
108
|
+
token = self._by_start.get(start)
|
|
109
|
+
if token is None or token.end != end or token.kind not in {"string", "heredoc"}:
|
|
110
|
+
return None
|
|
111
|
+
return literal_value(self.language, token.text, token.body)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def literal_value(language, text, heredoc_body=None):
|
|
115
|
+
"""Inner text of a string token, or None when it is interpolated."""
|
|
116
|
+
if heredoc_body is not None:
|
|
117
|
+
body = heredoc_body
|
|
118
|
+
single_quoted = "'" in text
|
|
119
|
+
else:
|
|
120
|
+
match = _PERCENT_BODY.match(text) if text.startswith("%") else _LITERAL_BODY.match(text)
|
|
121
|
+
if not match:
|
|
122
|
+
return None
|
|
123
|
+
body = match.group(2)
|
|
124
|
+
single_quoted = text.lstrip("br#").startswith("'") or text[:2] in {"%q", "%w", "%i"}
|
|
125
|
+
interpolation = _INTERPOLATION.get(language)
|
|
126
|
+
if interpolation and not single_quoted and interpolation.search(body):
|
|
127
|
+
return None
|
|
128
|
+
return body
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def lex(language, text):
|
|
132
|
+
pattern = _PATTERNS[language]
|
|
133
|
+
code, masked, tokens = [], [], []
|
|
134
|
+
position = 0
|
|
135
|
+
if language == "php":
|
|
136
|
+
# Leading HTML before the first PHP tag.
|
|
137
|
+
first = text.find("<?")
|
|
138
|
+
if first < 0:
|
|
139
|
+
blank = _BLANK.sub(" ", text)
|
|
140
|
+
return Source(language, text, blank, blank, [])
|
|
141
|
+
if first:
|
|
142
|
+
blank = _BLANK.sub(" ", text[:first])
|
|
143
|
+
code.append(blank)
|
|
144
|
+
masked.append(blank)
|
|
145
|
+
position = first
|
|
146
|
+
heredoc_end = None # (line_end, body_end) while finishing a heredoc marker's line
|
|
147
|
+
while True:
|
|
148
|
+
limit = heredoc_end[0] if heredoc_end else len(text)
|
|
149
|
+
match = pattern.search(text, position, limit)
|
|
150
|
+
if match is None:
|
|
151
|
+
code.append(text[position:limit])
|
|
152
|
+
masked.append(text[position:limit])
|
|
153
|
+
if not heredoc_end:
|
|
154
|
+
break
|
|
155
|
+
body = text[limit:heredoc_end[1]]
|
|
156
|
+
code.append(body)
|
|
157
|
+
masked.append(_BLANK.sub(" ", body))
|
|
158
|
+
position, heredoc_end = heredoc_end[1], None
|
|
159
|
+
continue
|
|
160
|
+
start, end = match.span()
|
|
161
|
+
between = text[position:start]
|
|
162
|
+
code.append(between)
|
|
163
|
+
masked.append(between)
|
|
164
|
+
token_text = match.group(0)
|
|
165
|
+
kind = next(kind for kind in _KINDS if kind in match.re.groupindex and match.group(kind) is not None)
|
|
166
|
+
if kind == "heredoc":
|
|
167
|
+
tokens.append(Token(start, end, kind, token_text, match.group("body")))
|
|
168
|
+
code.append(token_text)
|
|
169
|
+
masked.append(token_text)
|
|
170
|
+
line_end = text.find("\n", end)
|
|
171
|
+
if heredoc_end is None and line_end >= 0:
|
|
172
|
+
heredoc_end = (line_end, match.end("hend"))
|
|
173
|
+
position = end
|
|
174
|
+
continue
|
|
175
|
+
tokens.append(Token(start, end, kind, token_text))
|
|
176
|
+
if kind == "comment":
|
|
177
|
+
blank = _BLANK.sub(" ", token_text)
|
|
178
|
+
code.append(blank)
|
|
179
|
+
masked.append(blank)
|
|
180
|
+
else:
|
|
181
|
+
code.append(token_text)
|
|
182
|
+
inner = _BLANK.sub(" ", token_text[1:-1]) if len(token_text) >= 2 else ""
|
|
183
|
+
masked.append(token_text[:1] + inner + token_text[-1:] if len(token_text) >= 2 else token_text)
|
|
184
|
+
position = end
|
|
185
|
+
return Source(language, text, "".join(code), "".join(masked), tokens)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
_OPEN = "([{"
|
|
189
|
+
_CLOSE = ")]}"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def call_arguments(source, open_index):
|
|
193
|
+
"""Split the call whose ``(`` (or ``[``/``{``) is at ``open_index`` into argument spans.
|
|
194
|
+
|
|
195
|
+
Returns ``(spans, close_index)``; spans are ``(start, end)`` offsets into the text. Brackets
|
|
196
|
+
inside strings and comments are already blanked in ``masked``, so they do not count.
|
|
197
|
+
"""
|
|
198
|
+
masked = source.masked
|
|
199
|
+
depth = 0
|
|
200
|
+
spans = []
|
|
201
|
+
argument_start = open_index + 1
|
|
202
|
+
index = open_index
|
|
203
|
+
limit = min(len(masked), open_index + 20000)
|
|
204
|
+
while index < limit:
|
|
205
|
+
char = masked[index]
|
|
206
|
+
if char in _OPEN:
|
|
207
|
+
depth += 1
|
|
208
|
+
elif char in _CLOSE:
|
|
209
|
+
depth -= 1
|
|
210
|
+
if depth == 0:
|
|
211
|
+
if masked[argument_start:index].strip():
|
|
212
|
+
spans.append((argument_start, index))
|
|
213
|
+
return spans, index
|
|
214
|
+
elif char == "," and depth == 1:
|
|
215
|
+
spans.append((argument_start, index))
|
|
216
|
+
argument_start = index + 1
|
|
217
|
+
index += 1
|
|
218
|
+
return spans, None
|