Review LLM app code against the OWASP Top 10 for LLM Applications 2025. Runs a static scan for 10 risky patterns, answers 10 review questions from the code and writes a report. Use when asked for an LLM security or OWASP LLM review.
94%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Medium
Suggest reviewing before use
#!/usr/bin/env python3
"""Static scan for the OWASP Top 10 for LLM Applications 2025 (pattern hints P01-P10).
Standard library only. Reads files under one directory, never executes them, never follows
symlinks and never touches the network. Findings are hints, not proof.
Usage: python3 scan.py ROOT [--format markdown|json]
Exit codes: 0 scan finished, 2 usage error or ROOT is not a directory.
A finding is silenced with a trailing comment such as: owasp-llm: ignore P01
"""
from __future__ import annotations
import argparse
import fnmatch
import json
import os
import re
import stat
import sys
DISCLAIMER = "Findings are hints, not proof."
MAX_LINE = 4096
MAX_FILE_BYTES = 1_000_000
MAX_FILES = 20_000
MAX_FINDINGS = 10_000
MAX_CALL_LINES = 20
EXCLUDE = frozenset({".git", "node_modules", ".venv", "dist", "build"})
GLOBS = ("*.py", "*.ts", "*.js")
_W = r"\w{0,60}"
_TRUE = r"(?:True|true)"
_P03_HEAD = r"^(?=[^\n]{0,4096}?(?i:prompt|messages))[^\n]{0,4096}?"
_P03_FSTR = r"(?<!\w)(?i:rf|fr|f)[\x22\x27][^\n{]{0,300}"
_P03_VAR = r"\{[^}\n]{0,100}?\b(?:request|req|query|user_input)\b"
_P09_AUTO = rf"\bauto_approve\s*[=:]\s*{_TRUE}\b"
_P09_DANGER = rf"\b(?!{_W}(?i:deserialization)){_W}(?i:dangerous){_W}\s*[=:]\s*{_TRUE}\b"
# (rule id, risk id, title, regex, hint)
RULES = (
(
"P01",
"LLM05:2025",
"Model output passed to eval or exec",
r"\b(?:eval|exec)\s*\([^)\n]{0,200}?(?i:completion|response|output|reply|content)",
"Treat model output as untrusted data and never execute it.",
),
(
"P02",
"LLM05:2025",
"Shell-enabled process call",
r"\bsubprocess\s*\.\s*\w+\s*\([^\n]{0,300}?\bshell\s*=\s*True\b",
"Pass an argument list without a shell and validate every value.",
),
(
"P03",
"LLM01:2025",
"Prompt built from raw request input",
_P03_HEAD + _P03_FSTR + _P03_VAR,
"Keep user input in its own message instead of splicing it into instructions.",
),
(
"P04",
"LLM02:2025",
"Hard-coded model API key",
r"\b(?:sk-ant-|sk-|AIza)[A-Za-z0-9_-]{20,}",
"Remove the key, rotate it and load it from a secret manager.",
),
(
"P05",
"LLM10:2025",
"Model call without a token limit",
r"(?<!def )(?<!function )\b(?:create|generate_content|complete)\s*\(",
"Set an explicit max_tokens (or equivalent) on every model call.",
),
(
"P06",
"LLM03:2025",
"Unsafe model or pickle deserialization",
r"\b(?:pickle|joblib|torch)\.load\s*\((?![^\n]*\bweights_only\s*=\s*True\b)",
"Load only trusted artifacts and pass weights_only=True or use safetensors.",
),
(
"P07",
"LLM03:2025",
"Remote model code enabled",
r"\btrust_remote_code\s*=\s*True\b",
"Do not run remote model code; pin a reviewed revision instead.",
),
(
"P08",
"LLM07:2025",
"System prompt returned to the caller",
r"\b(?:return|jsonify)\b[^\n]{0,1000}?(?i:system_?prompt)",
"Never return the system prompt to clients or logs.",
),
(
"P09",
"LLM06:2025",
"Automatic approval of agent actions",
_P09_AUTO + "|" + _P09_DANGER,
"Require human approval for tool actions and avoid flags that disable safety.",
),
(
"P10",
"LLM08:2025",
"Dangerous deserialization of vector data",
rf"\ballow_dangerous_deserialization\s*[=:]\s*{_TRUE}\b",
"Only deserialize vector store files that you created yourself.",
),
)
_COMPILED = tuple((rule, re.compile(rule[3])) for rule in RULES)
_SECRET_RUN = re.compile(r"[A-Za-z0-9_-]{20,}")
_IGNORE = re.compile(r"owasp-llm:\s*ignore\s+([^\n]{0,200})")
_RULE_ID = re.compile(r"\b[A-Z]\d{2}\b")
_TOKEN_LIMIT = re.compile(r"max_tokens|max_output_tokens|maxTokens")
_PAREN = re.compile(r"[()]")
def mask(text: str) -> str:
"""Strip, mask every run of 20+ key-like characters and cut to 120 characters."""
masked = _SECRET_RUN.sub(lambda m: m.group()[:4] + "***", text.strip())
return masked[:120]
def call_text(lines: list[str], index: int, start: int) -> str:
"""Return the argument text of a call (at most 20 lines)."""
parts: list[str] = []
depth = 1
for offset in range(MAX_CALL_LINES):
pos = index + offset
if pos >= len(lines):
break
text = lines[pos][:MAX_LINE]
begin = start if offset == 0 else 0
for match in _PAREN.finditer(text, begin):
depth += 1 if match.group() == "(" else -1
if depth == 0:
parts.append(text[begin : match.start()])
return "\n".join(parts)
parts.append(text[begin:])
return "\n".join(parts)
def missing_limit(lines: list[str], index: int, segment: str, regex: re.Pattern[str]) -> bool:
for count, match in enumerate(regex.finditer(segment)):
if count >= 16:
break
if _TOKEN_LIMIT.search(call_text(lines, index, match.end())) is None:
return True
return False
def read_text(path: str) -> str | None:
"""Read a regular, non-symlink, non-binary file up to MAX_FILE_BYTES."""
try:
info = os.lstat(path)
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_FILE_BYTES:
return None
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
flags |= getattr(os, "O_BINARY", 0)
with os.fdopen(os.open(path, flags), "rb") as handle:
data = handle.read(MAX_FILE_BYTES + 1)
except OSError:
return None
if len(data) > MAX_FILE_BYTES or b"\x00" in data[:8192]:
return None
return data.decode("utf-8", errors="replace")
def scan_lines(lines: list[str], rel: str) -> list[dict[str, object]]:
found: list[dict[str, object]] = []
for index, raw in enumerate(lines):
segment = raw[:MAX_LINE]
if not segment.strip():
continue
ignored: set[str] = set()
for match in _IGNORE.finditer(segment):
ignored.update(_RULE_ID.findall(match.group(1)))
for rule, regex in _COMPILED:
if rule[0] in ignored:
continue
if rule[0] == "P05":
hit = missing_limit(lines, index, segment, regex)
else:
hit = regex.search(segment) is not None
if hit:
found.append(
{
"rule_id": rule[0],
"risk_id": rule[1],
"title": rule[2],
"path": rel,
"line": index + 1,
"excerpt": mask(segment),
"hint": rule[4],
}
)
return found
def scan(root: str) -> tuple[dict[str, object], list[dict[str, object]]]:
findings: list[dict[str, object]] = []
skipped = 0
seen = 0
truncated = False
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
kept = []
for name in sorted(dirnames):
if name in EXCLUDE:
continue
if os.path.islink(os.path.join(dirpath, name)):
skipped += 1
continue
kept.append(name)
dirnames[:] = kept
for name in sorted(filenames):
if name in EXCLUDE or not any(fnmatch.fnmatchcase(name, g) for g in GLOBS):
continue
if seen >= MAX_FILES:
truncated = True
break
seen += 1
full = os.path.join(dirpath, name)
text = read_text(full)
if text is None:
skipped += 1
continue
rel = os.path.relpath(full, root).replace(os.sep, "/")
findings.extend(scan_lines(text.split("\n"), rel))
if truncated:
break
findings.sort(key=lambda f: (str(f["path"]), int(str(f["line"])), str(f["rule_id"])))
if len(findings) > MAX_FINDINGS:
findings = findings[:MAX_FINDINGS]
truncated = True
summary: dict[str, object] = {
"findings": len(findings),
"skipped": skipped,
"truncated": truncated,
}
return summary, findings
def render_markdown(summary: dict[str, object], findings: list[dict[str, object]]) -> str:
lines = [
DISCLAIMER,
"",
"# OWASP LLM Top 10 2025 static scan",
"",
f"Findings: {summary['findings']}. Files skipped: {summary['skipped']}. "
f"Scan truncated: {'yes' if summary['truncated'] else 'no'}.",
]
by_risk: dict[str, list[dict[str, object]]] = {}
for item in findings:
by_risk.setdefault(str(item["risk_id"]), []).append(item)
for risk in sorted(by_risk):
lines += ["", f"## {risk}"]
for item in by_risk[risk]:
excerpt = str(item["excerpt"]).replace("`", "'")
lines.append(
f"- {item['rule_id']} {item['path']}:{item['line']} {item['title']}: `{excerpt}`"
f" - {item['hint']}"
)
return "\n".join(lines)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="OWASP LLM Top 10 2025 static scan.")
parser.add_argument("root", help="directory to scan")
parser.add_argument("--format", choices=("markdown", "json"), default="markdown")
try:
args = parser.parse_args(argv)
except SystemExit as exc:
return exc.code if isinstance(exc.code, int) else 2
if not os.path.isdir(args.root):
sys.stderr.write("error: scan root is not a directory\n")
return 2
summary, findings = scan(args.root)
if args.format == "json":
payload = {"disclaimer": DISCLAIMER, "summary": summary, "findings": findings}
sys.stdout.write(json.dumps(payload, indent=2) + "\n")
else:
sys.stdout.write(render_markdown(summary, findings) + "\n")
return 0
if __name__ == "__main__":
sys.exit(main())