Skip to content

Commit 97612ab

Browse files
committed
feat: enhance code guard with bash language support
1 parent e244e6f commit 97612ab

1 file changed

Lines changed: 48 additions & 3 deletions

File tree

src/qwed_new/guards/code_guard.py

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,24 @@ def __init__(self):
1111
self.dangerous_functions: Set[str] = {'eval', 'exec', 'compile', 'open', 'system', 'popen'}
1212
self.dangerous_modules: Set[str] = {'os', 'subprocess', 'sys', 'shutil', 'socket', 'pickle'}
1313

14-
def verify_safety(self, code_snippet: str) -> Dict[str, Any]:
14+
def verify_safety(self, code_snippet: str, language: str = "python") -> Dict[str, Any]:
1515
"""
16-
Statically analyzes Python code for security risks using AST.
17-
Source: QWED Core Features
16+
Statically analyzes code for security risks.
17+
Supports: Python (AST), Bash (Regex/Heuristics)
1818
"""
19+
# Normalize language
20+
lang = language.lower()
21+
22+
if lang in ["bash", "sh", "shell"]:
23+
return self._verify_bash(code_snippet)
24+
25+
# Default to Python AST
1926
try:
2027
tree = ast.parse(code_snippet)
2128
except SyntaxError as e:
29+
# If it looks like bash but was passed as python, give a hint
30+
if "curl" in code_snippet or "wget" in code_snippet:
31+
return {"verified": False, "error": "Syntax Error: Code appears to be Shell/Bash but parsed as Python. Specify language='bash'."}
2232
return {"verified": False, "error": f"Syntax Error: {e}"}
2333

2434
violations: List[str] = []
@@ -53,3 +63,38 @@ def verify_safety(self, code_snippet: str) -> Dict[str, Any]:
5363
"scan_method": "AST_STATIC_ANALYSIS",
5464
"message": "Code structure verified safe (No dangerous imports/functions)."
5565
}
66+
67+
def _verify_bash(self, code: str) -> Dict[str, Any]:
68+
"""Verify Bash/Shell commands using regex patterns."""
69+
import re
70+
71+
dangerous_patterns = [
72+
(r"curl\s+.*\|\s*bash", "Pipe to Bash detected (RCE Risk)"),
73+
(r"wget\s+.*\|\s*bash", "Pipe to Bash detected (RCE Risk)"),
74+
(r"rm\s+-rf", "Destructive command (rm -rf)"),
75+
(r":\(\)\{\s*:\|:\&\s*\}\;", "Fork Bomb detected"),
76+
(r"nc\s+.*-e\s+/bin/sh", "Netcat Reverse Shell"),
77+
(r"/dev/tcp/", "Direct TCP connection (Reverse Shell Risk)"),
78+
(r"base64\s+-d", "Base64 Decoding (Obfuscation Risk)"),
79+
(r"chmod\s+777", "Insecure permissions (chmod 777)"),
80+
(r"sudo\s+", "Privilege Escalation attempt (sudo)"),
81+
]
82+
83+
violations = []
84+
for pattern, desc in dangerous_patterns:
85+
if re.search(pattern, code, re.IGNORECASE):
86+
violations.append(desc)
87+
88+
if violations:
89+
return {
90+
"verified": False,
91+
"risk": "SHELL_INJECTION_RISK",
92+
"violations": violations,
93+
"message": f"Shell Violations: {', '.join(violations)}"
94+
}
95+
96+
return {
97+
"verified": True,
98+
"scan_method": "REGEX_HEURISTICS",
99+
"message": "Shell command verified safe."
100+
}

0 commit comments

Comments
 (0)