Spaces:
Sleeping

File size: 10,171 Bytes
c256079
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"""Regex-based security vulnerability scanner for Python source.

Detects common security anti-patterns: hardcoded secrets, injection sinks,
weak cryptography, dangerous builtins, and insecure deserialization.  This is
a lightweight linter β€” not a substitute for a full SAST tool β€” but catches the
issues that most often appear in application code.
"""

from __future__ import annotations

import logging
import re
from dataclasses import dataclass, field
from typing import Any

logger = logging.getLogger(__name__)


@dataclass
class Vulnerability:
    """A single detected vulnerability."""

    type: str
    severity: str  # "CRITICAL" | "HIGH" | "MEDIUM" | "LOW"
    line: int
    description: str
    fix: str = ""

    def to_dict(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "severity": self.severity,
            "line": self.line,
            "description": self.description,
            "fix": self.fix,
        }


@dataclass
class ScanResult:
    """Result of a security scan."""

    success: bool
    vulnerabilities: list[Vulnerability] = field(default_factory=list)
    risk_level: str = "LOW"
    error: str = ""

    @property
    def total_issues(self) -> int:
        return len(self.vulnerabilities)

    def to_dict(self) -> dict[str, Any]:
        return {
            "success": self.success,
            "vulnerabilities": [v.to_dict() for v in self.vulnerabilities],
            "risk_level": self.risk_level,
            "total_issues": self.total_issues,
            "error": self.error,
        }


class SecurityScanner:
    """Scan Python source for security vulnerabilities using regex patterns."""

    # Hardcoded-secret patterns β†’ label
    _SECRET_PATTERNS: dict[str, str] = {
        r'password\s*=\s*["\'][^"\']+["\']': "Hardcoded password",
        r'api[_-]?key\s*=\s*["\'][^"\']+["\']': "Hardcoded API key",
        r'secret[_-]?key\s*=\s*["\'][^"\']+["\']': "Hardcoded secret key",
        r'token\s*=\s*["\'][^"\']+["\']': "Hardcoded token",
        r'aws_access_key_id\s*=\s*["\'][^"\']+["\']': "Hardcoded AWS key",
    }

    _SQL_INJECTION_PATTERNS: list[str] = [
        r'execute\s*\(\s*["\'].*%s.*["\']\s*%',
        r'execute\s*\(\s*f["\'].*\{.*\}.*["\']',
        r'execute\s*\(\s*["\'].*["\']\s*\+',
    ]

    _WEAK_HASHES: list[str] = ["md5", "sha1"]

    _DANGEROUS_FUNCS: dict[str, tuple[str, str]] = {
        "eval(": ("Code Injection", "Arbitrary code execution via eval()"),
        "exec(": ("Code Injection", "Arbitrary code execution via exec()"),
        "os.system(": ("Command Injection", "Shell command injection via os.system()"),
    }

    _IP_PATTERN = re.compile(r'["\'](?:\d{1,3}\.){3}\d{1,3}["\']')

    # ── Public API ───────────────────────────────────────────────────────

    def scan(self, code: str) -> ScanResult:
        """Scan *code* and return a :class:`ScanResult`.

        Args:
            code: Python source to scan.

        Returns:
            The scan result with any vulnerabilities and an overall risk level.
        """
        vulns: list[Vulnerability] = []
        lines = code.splitlines()

        vulns.extend(self._scan_secrets(lines))
        vulns.extend(self._scan_sql_injection(lines))
        vulns.extend(self._scan_weak_crypto(lines))
        vulns.extend(self._scan_dangerous_functions(lines))
        vulns.extend(self._scan_deserialization(lines))
        vulns.extend(self._scan_shell_true(lines))
        vulns.extend(self._scan_yaml_load(lines))
        vulns.extend(self._scan_hardcoded_ip(lines))

        return ScanResult(
            success=True,
            vulnerabilities=vulns,
            risk_level=self._risk_level(vulns),
        )

    # ── Individual scans ─────────────────────────────────────────────────

    def _scan_secrets(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            for pattern, label in self._SECRET_PATTERNS.items():
                if re.search(pattern, line, re.IGNORECASE):
                    out.append(
                        Vulnerability(
                            type=label,
                            severity="CRITICAL",
                            line=n,
                            description=f"Hardcoded credential: {line.strip()[:50]}…",
                            fix="Load secrets from environment variables or a secrets manager",
                        )
                    )
        return out

    def _scan_sql_injection(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            for pattern in self._SQL_INJECTION_PATTERNS:
                if re.search(pattern, line):
                    out.append(
                        Vulnerability(
                            type="SQL Injection",
                            severity="CRITICAL",
                            line=n,
                            description="String-formatted SQL is vulnerable to injection",
                            fix="Use parameterised queries or an ORM",
                        )
                    )
                    break
        return out

    def _scan_weak_crypto(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            for algo in self._WEAK_HASHES:
                if f"hashlib.{algo}" in line:
                    out.append(
                        Vulnerability(
                            type="Weak Cryptography",
                            severity="HIGH",
                            line=n,
                            description=f"Weak hash algorithm: {algo.upper()}",
                            fix="Use SHA-256+ for integrity or bcrypt/argon2 for passwords",
                        )
                    )
        return out

    def _scan_dangerous_functions(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            for func, (vuln_type, desc) in self._DANGEROUS_FUNCS.items():
                if func in line:
                    out.append(
                        Vulnerability(
                            type=vuln_type,
                            severity="CRITICAL",
                            line=n,
                            description=desc,
                            fix=f"Avoid {func.rstrip('(')} with untrusted input",
                        )
                    )
        return out

    def _scan_deserialization(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            if "pickle.load" in line:
                out.append(
                    Vulnerability(
                        type="Insecure Deserialization",
                        severity="HIGH",
                        line=n,
                        description="pickle can execute arbitrary code during load",
                        fix="Use JSON or another safe serialisation format",
                    )
                )
        return out

    def _scan_shell_true(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            if re.search(r"subprocess\.(run|call|Popen|check_output)", line) and "shell=True" in line:
                out.append(
                    Vulnerability(
                        type="Command Injection",
                        severity="HIGH",
                        line=n,
                        description="subprocess with shell=True enables shell injection",
                        fix="Pass args as a list and use shell=False (the default)",
                    )
                )
        return out

    def _scan_yaml_load(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            if "yaml.load(" in line and "Loader=" not in line and "SafeLoader" not in line:
                out.append(
                    Vulnerability(
                        type="Insecure Deserialization",
                        severity="HIGH",
                        line=n,
                        description="yaml.load without SafeLoader can execute arbitrary code",
                        fix="Use yaml.safe_load() or Loader=yaml.SafeLoader",
                    )
                )
        return out

    def _scan_hardcoded_ip(self, lines: list[str]) -> list[Vulnerability]:
        out: list[Vulnerability] = []
        for n, line in enumerate(lines, 1):
            stripped = line.strip()
            if stripped.startswith("#"):
                continue
            match = self._IP_PATTERN.search(line)
            if match and "127.0.0.1" not in match.group() and "0.0.0.0" not in match.group():
                out.append(
                    Vulnerability(
                        type="Hardcoded IP address",
                        severity="LOW",
                        line=n,
                        description=f"Hardcoded IP {match.group()} reduces portability and can leak infra details",
                        fix="Move host addresses to configuration",
                    )
                )
        return out

    # ── Risk aggregation ─────────────────────────────────────────────────

    @staticmethod
    def _risk_level(vulns: list[Vulnerability]) -> str:
        """Roll individual severities up into an overall risk level."""
        if any(v.severity == "CRITICAL" for v in vulns):
            return "CRITICAL"
        if any(v.severity == "HIGH" for v in vulns):
            return "HIGH"
        if vulns:
            return "MEDIUM"
        return "LOW"