Spaces:
Sleeping
Sleeping
Initial Code Guardian Gradio Space
Browse filesFiles changed (3)
- README.md+23-5
- app.pyAdded+706
- requirements.txtAdded+4
12345678910111213---title: Code Guardianemoji: π»colorFrom: purplecolorTo: bluesdk: gradiosdk_version: 6.31.0python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031---title: Code Guardianemoji: π‘οΈcolorFrom: redcolorTo: graysdk: gradiosdk_version: 6.31.0app_file: app.pypinned: falselicense: mitshort_description: Static Python security scanner (YARA + AST + Bandit)---# Code GuardianStatische security-scanner voor Python-code. Upload een `.py`/`.txt`-bestand of plak code; de Space voert de code **niet** uit.## Engines- **YARA** β malware-/backdoorpatronen- **AST** β gevaarlijke calls (`eval`, `exec`, `subprocess.run`, β¦) met import/alias-resolutie- **Secret regex** β AWS `AKIAβ¦`, bearer tokens, private keys- **Bandit** β SAST met time-out## Gebruik1. Upload een script of plak code2. Klik op **Start Security Scan**3. Bekijk status, risicoscore (gauge) en bevindingenAlleen `.py` en `.txt` worden ondersteund.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706"""Code Guardian β static security scanner dashboard (Gradio + YARA + AST + Bandit)."""
from __future__ import annotations
import astimport jsonimport osimport reimport shutilimport subprocessimport tempfilefrom pathlib import Pathfrom typing import Any
import gradio as grimport plotly.graph_objects as goimport yara
# --- CONFIGURATIE & SECURITY ENGINE ---
ALLOWED_EXTENSIONS = {".py", ".txt"}MAX_FILE_SIZE_MB = 5BANDIT_TIMEOUT_SEC = 30
# Canonical dangerous call names (exact match after import/alias resolution).DANGEROUS_CALLS = { "eval", "exec", "compile", "__import__", "getattr", "setattr", "os.system", "os.popen", "subprocess.Popen", "subprocess.call", "subprocess.run", "subprocess.check_output", "subprocess.check_call", "shutil.rmtree", "pty.spawn", "pickle.loads", "pickle.load", "yaml.load",}
# Modules whose bare imported names map to dotted dangerous calls.IMPORT_ALIASES_TO_CANONICAL = { ("os", "system"): "os.system", ("os", "popen"): "os.popen", ("subprocess", "Popen"): "subprocess.Popen", ("subprocess", "call"): "subprocess.call", ("subprocess", "run"): "subprocess.run", ("subprocess", "check_output"): "subprocess.check_output", ("subprocess", "check_call"): "subprocess.check_call", ("shutil", "rmtree"): "shutil.rmtree", ("pty", "spawn"): "pty.spawn", ("pickle", "loads"): "pickle.loads", ("pickle", "load"): "pickle.load", ("yaml", "load"): "yaml.load",}
SECRET_VAR_KEYWORDS = ("api_key", "secret", "password", "token", "passwd", "apikey")
SECRET_PATTERNS = [ ( "AWSAccessKey", re.compile(r"(?<![A-Za-z0-9])AKIA[0-9A-Z]{16}(?![A-Za-z0-9])"), "HIGH", 40, ), ( "GenericBearerToken", re.compile(r"(?i)\b(bearer\s+[A-Za-z0-9\-._~+/]+=*)\b"), "MEDIUM", 25, ), ( "GenericApiToken", re.compile( r"(?i)(?:api[_-]?key|access[_-]?token|secret[_-]?key)\s*[:=]\s*['\"]([^'\"]{16,})['\"]" ), "MEDIUM", 25, ), ( "PrivateKeyBlock", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"), "HIGH", 40, ),]
class AdvancedCodeGuardian: def __init__(self, max_file_size_mb: int = MAX_FILE_SIZE_MB): self.max_file_size = max_file_size_mb * 1024 * 1024 self.yara_rules = self._compile_yara_rules()
def _compile_yara_rules(self) -> yara.Rules | None: rules_source = """ rule MaliciousPythonPatterns { strings: $web_shell1 = "wsgiref.simple_server" $reverse_shell1 = "socket.SOCK_STREAM" $reverse_shell2 = "pty.spawn" $obfuscation1 = "getattr(builtins" $obfuscation2 = "eval(base64" $crypto_miner = "stratum+tcp://" condition: any of them } """ try: return yara.compile(source=rules_source) except Exception: return None
def scan_file(self, file_path: str) -> dict[str, Any]: report: dict[str, Any] = { "file": os.path.basename(file_path), "status": "PASSED", "risk_score": 0, "findings": [], }
if not os.path.exists(file_path): report["status"] = "ERROR" report["findings"].append( { "engine": "System", "type": "IOError", "severity": "HIGH", "message": "Bestand niet gevonden.", } ) return report
if os.path.getsize(file_path) > self.max_file_size: report["status"] = "REJECTED" report["findings"].append( { "engine": "DoS_Guard", "type": "SizeViolation", "severity": "HIGH", "message": ( "Bestand overschrijdt de maximale grootte " f"({MAX_FILE_SIZE_MB} MB)." ), } ) return report
suffix = Path(file_path).suffix.lower() if suffix and suffix not in ALLOWED_EXTENSIONS: report["status"] = "REJECTED" report["findings"].append( { "engine": "DoS_Guard", "type": "UnsupportedType", "severity": "MEDIUM", "message": ( f"Bestandstype '{suffix}' wordt niet ondersteund. " "Alleen .py en .txt." ), } ) return report
try: with open(file_path, "r", encoding="utf-8", errors="ignore") as handle: content = handle.read() except Exception as exc: report["status"] = "ERROR" report["findings"].append( { "engine": "System", "type": "ReadError", "severity": "HIGH", "message": str(exc), } ) return report
self._run_yara_scan(file_path, report) self._run_secret_regex_scan(content, report) self._run_owasp_ast_scan(content, report) if suffix in {".py", ".txt", ""}: self._run_bandit_scan(file_path, report)
# Preserve ERROR/REJECTED; otherwise derive from score. if report["status"] not in {"ERROR", "REJECTED"}: report["risk_score"] = min(int(report["risk_score"]), 100) if report["risk_score"] >= 70: report["status"] = "CRITICAL_DANGER" elif report["risk_score"] > 0: report["status"] = "RISKY" else: report["status"] = "PASSED" else: report["risk_score"] = min(int(report["risk_score"]), 100)
return report
def _run_yara_scan(self, file_path: str, report: dict[str, Any]) -> None: if not self.yara_rules: return try: matches = self.yara_rules.match(file_path) for match in matches: report["findings"].append( { "engine": "YARA_Malware", "type": f"MalwarePattern: {match.rule}", "severity": "HIGH", "message": ( "Overeenkomst gevonden met bekende malware- " "of backdoortactieken." ), } ) report["risk_score"] += 60 except Exception: pass
def _run_secret_regex_scan(self, content: str, report: dict[str, Any]) -> None: seen: set[tuple[str, str]] = set() for label, pattern, severity, score in SECRET_PATTERNS: for match in pattern.finditer(content): snippet = match.group(0)[:48] key = (label, snippet) if key in seen: continue seen.add(key) report["findings"].append( { "engine": "Secret_Regex", "type": f"CredentialPattern:{label}", "severity": severity, "message": ( f"Mogelijk geheim in tekst gedetecteerd " f"({label}): '{snippet}β¦'." if len(match.group(0)) > 48 else f"Mogelijk geheim in tekst gedetecteerd ({label}): '{snippet}'." ), } ) report["risk_score"] += score
@staticmethod def _attr_chain(node: ast.AST) -> str | None: parts: list[str] = [] cur: ast.AST | None = node while isinstance(cur, ast.Attribute): parts.append(cur.attr) cur = cur.value if isinstance(cur, ast.Name): parts.append(cur.id) return ".".join(reversed(parts)) return None
def _build_alias_map(self, tree: ast.AST) -> dict[str, str]: """Map local names β canonical dotted names for dangerous APIs.""" aliases: dict[str, str] = {} for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: local = alias.asname or alias.name # e.g. import subprocess as sp β sp.run becomes subprocess.run # We store module root mapping separately via prefix. aliases[f"__mod__:{local}"] = alias.name elif isinstance(node, ast.ImportFrom): if not node.module: continue mod = node.module for alias in node.names: if alias.name == "*": continue local = alias.asname or alias.name key = (mod, alias.name) if key in IMPORT_ALIASES_TO_CANONICAL: aliases[local] = IMPORT_ALIASES_TO_CANONICAL[key] elif f"{mod}.{alias.name}" in DANGEROUS_CALLS: aliases[local] = f"{mod}.{alias.name}" elif alias.name in DANGEROUS_CALLS and mod in { "builtins", "builtins", }: aliases[local] = alias.name return aliases
def _resolve_call_name( self, node: ast.Call, aliases: dict[str, str] ) -> str | None: if isinstance(node.func, ast.Name): name = node.func.id return aliases.get(name, name)
chain = self._attr_chain(node.func) if not chain: return None
# Resolve module aliases: sp.run β subprocess.run parts = chain.split(".") root = parts[0] mod_key = f"__mod__:{root}" if mod_key in aliases: parts[0] = aliases[mod_key] chain = ".".join(parts)
# Resolve imported aliases used as attributes? rare; also map bare alias. if chain in aliases: return aliases[chain] if parts[0] in aliases and len(parts) == 1: return aliases[parts[0]] return chain
def _run_owasp_ast_scan(self, content: str, report: dict[str, Any]) -> None: try: tree = ast.parse(content) except SyntaxError as exc: report["findings"].append( { "engine": "OWASP_AST", "type": "SyntaxError", "severity": "LOW", "message": ( "Kan syntax-tree niet volledig parsen " f"(mogelijk corrupte of niet-Python code): {exc}" ), } ) return
aliases = self._build_alias_map(tree)
for node in ast.walk(tree): if isinstance(node, ast.Call): func_name = self._resolve_call_name(node, aliases) if not func_name: continue
# Exact match against known dangerous calls. # Avoid substring noise (re.compile, getattr on unrelated objects # still flagged if bare getattr β intentional for OWASP A03). matched = None if func_name in DANGEROUS_CALLS: matched = func_name else: # Also match if alias resolved to canonical. for dangerous in DANGEROUS_CALLS: if func_name == dangerous: matched = dangerous break
# Soften getattr/setattr noise: only flag if first arg looks like # builtins / __builtins__ / a string constant of a dangerous name, # OR if call is the bare builtin getattr/setattr (still report once # at MEDIUM rather than HIGH when target is unknown). if matched in {"getattr", "setattr"}: severity = "MEDIUM" score = 20 msg_extra = " (dynamische attribuuttoegang)." if node.args: first = node.args[0] first_repr = "" if isinstance(first, ast.Name): first_repr = first.id elif isinstance(first, ast.Constant) and isinstance( first.value, str ): first_repr = first.value elif isinstance(first, ast.Attribute): first_repr = self._attr_chain(first) or "" if any( token in first_repr.lower() for token in ("builtin", "__dict__", "globals", "locals") ): severity = "HIGH" score = 40 msg_extra = " (obfuscatie / builtins-reflectie)." report["findings"].append( { "engine": "OWASP_AST", "type": "OWASP_A03:Injection", "severity": severity, "message": ( f"Gevaarlijke dynamische executie / RCE-risico via: " f"'{matched}'{msg_extra}" ), } ) report["risk_score"] += score continue
if matched == "compile": # Only flag builtins.compile, not re.compile (already excluded # by exact match). Still require at least 1 arg. report["findings"].append( { "engine": "OWASP_AST", "type": "OWASP_A03:Injection", "severity": "HIGH", "message": ( "Gevaarlijke dynamische executie / RCE-risico via: " "'compile'." ), } ) report["risk_score"] += 40 continue
if matched: report["findings"].append( { "engine": "OWASP_AST", "type": "OWASP_A03:Injection", "severity": "HIGH", "message": ( "Gevaarlijke dynamische executie / RCE-risico via: " f"'{matched}'." ), } ) report["risk_score"] += 40
if isinstance(node, ast.Assign): for target in node.targets: if not isinstance(target, ast.Name): continue if not any(kw in target.id.lower() for kw in SECRET_VAR_KEYWORDS): continue if isinstance(node.value, ast.Constant) and isinstance( node.value.value, str ): report["findings"].append( { "engine": "OWASP_AST", "type": "OWASP_A07:Credentials", "severity": "MEDIUM", "message": ( "Mogelijk hardcoded geheim gedetecteerd in " f"variabele: '{target.id}'." ), } ) report["risk_score"] += 30
def _run_bandit_scan(self, file_path: str, report: dict[str, Any]) -> None: bandit_exec = shutil.which("bandit") or "bandit" try: result = subprocess.run( [bandit_exec, "-f", "json", "-q", file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=BANDIT_TIMEOUT_SEC, check=False, ) if result.stdout: bandit_data = json.loads(result.stdout) for issue in bandit_data.get("results", []): sev = issue.get("issue_severity", "LOW") report["findings"].append( { "engine": "Bandit_SAST", "type": f"Bandit_{issue.get('test_id', 'unknown')}", "severity": sev, "message": ( f"Regel {issue.get('line_number', '?')}: " f"{issue.get('issue_text', '')}" ), } ) severity_map = {"LOW": 10, "MEDIUM": 20, "HIGH": 40} report["risk_score"] += severity_map.get(sev, 10) except subprocess.TimeoutExpired: report["findings"].append( { "engine": "Bandit_SAST", "type": "Timeout", "severity": "LOW", "message": ( f"Bandit-scan afgebroken na {BANDIT_TIMEOUT_SEC}s time-out." ), } ) except Exception as exc: report["findings"].append( { "engine": "Bandit_SAST", "type": "Error", "severity": "LOW", "message": f"Bandit scan kon niet volledig worden uitgevoerd: {exc}", } )
# --- UI VISUALISATIE (PLOTLY) ---
def create_gauge_chart(score: int): """Genereert een Plotly snelheidsmeter op basis van de risicoscore.""" color = "green" if score < 30 else "orange" if score < 70 else "red" fig = go.Figure( go.Indicator( mode="gauge+number", value=score, domain={"x": [0, 1], "y": [0, 1]}, title={"text": "Risico Score Index", "font": {"size": 18}}, gauge={ "axis": {"range": [0, 100], "tickwidth": 1}, "bar": {"color": color}, "steps": [ {"range": [0, 30], "color": "rgba(0, 255, 0, 0.1)"}, {"range": [30, 70], "color": "rgba(255, 165, 0, 0.1)"}, {"range": [70, 100], "color": "rgba(255, 0, 0, 0.1)"}, ], }, ) ) fig.update_layout(height=250, margin=dict(l=20, r=20, t=40, b=20)) return fig
def _status_label(status: str) -> str: mapping = { "PASSED": "β
PASSED", "RISKY": "β οΈ RISKY", "CRITICAL_DANGER": "π¨ CRITICAL DANGER", "ERROR": "β ERROR", "REJECTED": "π« REJECTED", "Geen invoer": "βΉοΈ Geen invoer", } return mapping.get(status, status)
def _resolve_upload_path(uploaded_file: Any) -> str | None: if uploaded_file is None: return None if isinstance(uploaded_file, str): return uploaded_file # Gradio FileData / tempfile-like objects for attr in ("name", "path"): value = getattr(uploaded_file, attr, None) if isinstance(value, str) and value: return value if isinstance(uploaded_file, dict): for key in ("path", "name", "orig_name"): value = uploaded_file.get(key) if isinstance(value, str) and value and ( key != "orig_name" or os.path.exists(value) ): if key == "orig_name": continue return value path = uploaded_file.get("path") or uploaded_file.get("name") if isinstance(path, str): return path return None
# --- GRADIO CONTROLLER ---
guardian = AdvancedCodeGuardian()
def dashboard_controller(uploaded_file, raw_text_code): empty_gauge = create_gauge_chart(0) raw_text = (raw_text_code or "").strip()
tmp_dir = None target_path = None try: upload_path = _resolve_upload_path(uploaded_file)
if upload_path is not None: suffix = Path(upload_path).suffix.lower() orig_name = None if hasattr(uploaded_file, "orig_name"): orig_name = uploaded_file.orig_name elif isinstance(uploaded_file, dict): orig_name = uploaded_file.get("orig_name") check_suffix = Path(orig_name).suffix.lower() if orig_name else suffix
if check_suffix and check_suffix not in ALLOWED_EXTENSIONS: status = "REJECTED" summary = ( f"### Scan Status: {_status_label(status)}\n" f"* **Reden:** bestandstype `{check_suffix}` wordt niet " "ondersteund (alleen `.py` en `.txt`)." ) details = ( "### π Gedetailleerde Audit Bevindingen\n" "JavaScript en andere talen worden niet gescand. " "Upload een Python-bestand of plak Python-code." ) return status, empty_gauge, summary, details
target_path = upload_path elif raw_text: tmp_dir = tempfile.mkdtemp(prefix="code_guardian_") target_path = os.path.join(tmp_dir, "pasted_code.py") with open(target_path, "w", encoding="utf-8") as handle: handle.write(raw_text) else: return ( "Geen invoer", empty_gauge, "### [!] Fout: Upload een bestand of plak code in het tekstveld " "om de scan te starten.", "### π Gedetailleerde Audit Bevindingen\nNog geen scan uitgevoerd.", )
report = guardian.scan_file(target_path) gauge_plot = create_gauge_chart(report["risk_score"]) status_emoji = _status_label(report["status"]) summary_markdown = f"""### Scan Status: {status_emoji}* **Geanalyseerd bestand:** `{report['file']}`* **Aantal meldingen:** {len(report['findings'])}* **Risicoscore:** {report['risk_score']}/100""" if not report["findings"]: findings_markdown = ( "### π Geen kwetsbaarheden of malware-patronen gevonden!" ) else: findings_markdown = "### π Gedetecteerde Risico's & Kwetsbaarheden:\n" for idx, finding in enumerate(report["findings"], 1): sev = finding["severity"] sev_badge = ( "π΄ HIGH" if sev == "HIGH" else "π‘ MEDIUM" if sev == "MEDIUM" else "π΅ LOW" ) findings_markdown += ( f"**{idx}. [{finding['engine']}] {finding['type']}**\n" f"* **Ernst:** {sev_badge}\n" f"* **Beschrijving:** {finding['message']}\n\n" )
return report["status"], gauge_plot, summary_markdown, findings_markdown finally: if tmp_dir and os.path.isdir(tmp_dir): shutil.rmtree(tmp_dir, ignore_errors=True)
# --- GRADIO INTERFACE DESIGN ---
theme = gr.themes.Soft( primary_hue="red", secondary_hue="slate",).set( body_background_fill="*neutral_50", block_background_fill="*white",)
with gr.Blocks(title="Code Guardian Dashboard") as demo: gr.Markdown("# π‘οΈ Code Guardian β Security & Malware Dashboard") gr.Markdown( "Analyseer direct scripts en opensource code op OWASP Top 10 risico's, " "command-injection en malware-patronen **zonder** de code uit te voeren. " "Alleen Python (`.py`) en tekst (`.txt`)." )
with gr.Row(): with gr.Column(scale=2): gr.Markdown("### π Input Bron") file_input = gr.File( label="Upload een script (.py, .txt)", file_types=[".py", ".txt"], ) text_input = gr.Textbox( label="Of plak de code direct hier:", lines=10, placeholder="import os\neval(input()) ...", ) scan_btn = gr.Button("π Start Security Scan", variant="primary")
with gr.Column(scale=3): gr.Markdown("### π Analyse Resultaten") with gr.Row(): status_box = gr.Textbox(label="Security Status", interactive=False) plot_output = gr.Plot(label="Risico Index") summary_output = gr.Markdown( "### Status\nUpload of plak code om de statistieken te laden." )
gr.Markdown("---") with gr.Row(): with gr.Column(): details_output = gr.Markdown( "### π Gedetailleerde Audit Bevindingen\n" "Hier verschijnen de specifieke code-kwetsbaarheden na de scan." )
scan_btn.click( fn=dashboard_controller, inputs=[file_input, text_input], outputs=[status_box, plot_output, summary_output, details_output], )
if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860, theme=theme)1234gradio>=5.0.0bandityara-pythonplotlyREADME.md+23-5
app.pyAdded+706
requirements.txtAdded+4