Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /GRID-INTELLIGENCE_GRID /src /tools /security /vulnerability_scanner.py
| """ | |
| Vulnerability scanner for GRID codebase and configurations. | |
| Provides comprehensive security vulnerability scanning for Python code, | |
| configuration files, dependencies, and infrastructure. Implements enterprise-grade | |
| security analysis with automated detection and reporting. | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import json | |
| import logging | |
| import re | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime | |
| from enum import StrEnum | |
| from pathlib import Path | |
| from typing import Any | |
| logger = logging.getLogger(__name__) | |
| class VulnerabilitySeverity(StrEnum): | |
| """Vulnerability severity levels.""" | |
| LOW = "low" | |
| MEDIUM = "medium" | |
| HIGH = "high" | |
| CRITICAL = "critical" | |
| class VulnerabilityType(StrEnum): | |
| """Types of vulnerabilities.""" | |
| HARDCODED_SECRET = "hardcoded_secret" | |
| SQL_INJECTION = "sql_injection" | |
| XSS = "xss" | |
| INSECURE_CRYPTO = "insecure_crypto" | |
| INSECURE_DESERIALIZATION = "insecure_deserialization" | |
| PATH_TRAVERSAL = "path_traversal" | |
| COMMAND_INJECTION = "command_injection" | |
| INSECURE_CONFIGURATION = "insecure_configuration" | |
| OUTDATED_DEPENDENCY = "outdated_dependency" | |
| WEAK_PASSWORD = "weak_password" | |
| DEBUG_CODE = "debug_code" | |
| INFORMATION_DISCLOSURE = "information_disclosure" | |
| class Vulnerability: | |
| """Security vulnerability found during scanning.""" | |
| vulnerability_id: str | |
| type: VulnerabilityType | |
| severity: VulnerabilitySeverity | |
| title: str | |
| description: str | |
| file_path: str | |
| line_number: int | None | |
| code_snippet: str | None | |
| cwe_id: str | None | |
| cvss_score: float | None | |
| remediation: str | |
| references: list[str] | |
| metadata: dict[str, Any] | |
| def to_dict(self) -> dict[str, Any]: | |
| """Convert to dictionary for serialization.""" | |
| return { | |
| "vulnerability_id": self.vulnerability_id, | |
| "type": self.type.value, | |
| "severity": self.severity.value, | |
| "title": self.title, | |
| "description": self.description, | |
| "file_path": self.file_path, | |
| "line_number": self.line_number, | |
| "code_snippet": self.code_snippet, | |
| "cwe_id": self.cwe_id, | |
| "cvss_score": self.cvss_score, | |
| "remediation": self.remediation, | |
| "references": self.references, | |
| "metadata": self.metadata, | |
| } | |
| class ScanResult: | |
| """Result of a vulnerability scan.""" | |
| scan_id: str | |
| timestamp: datetime | |
| scan_path: str | |
| scan_duration_seconds: float | |
| vulnerabilities: list[Vulnerability] | |
| summary: dict[str, Any] | |
| def to_dict(self) -> dict[str, Any]: | |
| """Convert to dictionary for serialization.""" | |
| return { | |
| "scan_id": self.scan_id, | |
| "timestamp": self.timestamp.isoformat(), | |
| "scan_path": self.scan_path, | |
| "scan_duration_seconds": self.scan_duration_seconds, | |
| "vulnerabilities": [vuln.to_dict() for vuln in self.vulnerabilities], | |
| "summary": self.summary, | |
| } | |
| class VulnerabilityScanner: | |
| """ | |
| Comprehensive vulnerability scanner for GRID codebase. | |
| Features: | |
| - Static code analysis for Python files | |
| - Configuration file security scanning | |
| - Dependency vulnerability checking | |
| - Secret detection across all file types | |
| - Infrastructure security analysis | |
| - Custom rule engine support | |
| """ | |
| def __init__( | |
| self, | |
| enable_dependency_checking: bool = True, | |
| enable_secret_detection: bool = True, | |
| custom_rules_path: Path | None = None, | |
| ): | |
| """ | |
| Initialize vulnerability scanner. | |
| Args: | |
| enable_dependency_checking: Enable dependency vulnerability checking | |
| enable_secret_detection: Enable secret detection | |
| custom_rules_path: Path to custom scanning rules | |
| """ | |
| self.enable_dependency_checking = enable_dependency_checking | |
| self.enable_secret_detection = enable_secret_detection | |
| self.custom_rules_path = custom_rules_path | |
| # Load detection patterns | |
| self._secret_patterns = self._load_secret_patterns() | |
| self._insecure_patterns = self._load_insecure_patterns() | |
| self._crypto_patterns = self._load_crypto_patterns() | |
| self._portfolio_patterns = self._load_portfolio_patterns() | |
| # Load custom rules if provided | |
| self._custom_rules: dict[str, Any] = {} | |
| if custom_rules_path and custom_rules_path.exists(): | |
| self._load_custom_rules() | |
| logger.info("VulnerabilityScanner initialized") | |
| def scan_path(self, scan_path: Path) -> ScanResult: | |
| """ | |
| Scan a path for vulnerabilities. | |
| Args: | |
| scan_path: Path to scan | |
| Returns: | |
| Scan result with all findings | |
| """ | |
| import time | |
| scan_id = f"scan_{int(time.time())}" | |
| start_time = time.time() | |
| vulnerabilities: list[Vulnerability] = [] | |
| logger.info(f"Starting vulnerability scan of {scan_path}") | |
| # Scan Python files | |
| python_files = list(scan_path.rglob("*.py")) | |
| for py_file in python_files: | |
| try: | |
| file_vulns = self._scan_python_file(py_file) | |
| vulnerabilities.extend(file_vulns) | |
| except Exception as e: | |
| logger.warning(f"Failed to scan Python file {py_file}: {e}") | |
| # Scan configuration files | |
| config_extensions = [".yaml", ".yml", ".json", ".toml", ".ini", ".conf"] | |
| for ext in config_extensions: | |
| config_files = list(scan_path.rglob(f"*{ext}")) | |
| for config_file in config_files: | |
| try: | |
| file_vulns = self._scan_config_file(config_file) | |
| vulnerabilities.extend(file_vulns) | |
| except Exception as e: | |
| logger.warning(f"Failed to scan config file {config_file}: {e}") | |
| # Scan for secrets across all files | |
| if self.enable_secret_detection: | |
| all_files = [f for f in scan_path.rglob("*") if f.is_file()] | |
| for file_path in all_files: | |
| if self._should_scan_file(file_path): | |
| try: | |
| file_vulns = self._scan_for_secrets(file_path) | |
| vulnerabilities.extend(file_vulns) | |
| except Exception as e: | |
| logger.warning(f"Failed to scan for secrets in {file_path}: {e}") | |
| # Check dependencies | |
| if self.enable_dependency_checking: | |
| try: | |
| dep_vulns = self._scan_dependencies(scan_path) | |
| vulnerabilities.extend(dep_vulns) | |
| except Exception as e: | |
| logger.warning(f"Failed to scan dependencies: {e}") | |
| # Apply custom rules | |
| if self._custom_rules: | |
| try: | |
| custom_vulns = self._apply_custom_rules(scan_path) | |
| vulnerabilities.extend(custom_vulns) | |
| except Exception as e: | |
| logger.warning(f"Failed to apply custom rules: {e}") | |
| # Remove duplicates | |
| vulnerabilities = self._deduplicate_vulnerabilities(vulnerabilities) | |
| # Generate summary | |
| summary = self._generate_summary(vulnerabilities) | |
| scan_duration = time.time() - start_time | |
| result = ScanResult( | |
| scan_id=scan_id, | |
| timestamp=datetime.now(UTC), | |
| scan_path=str(scan_path), | |
| scan_duration_seconds=scan_duration, | |
| vulnerabilities=vulnerabilities, | |
| summary=summary, | |
| ) | |
| logger.info(f"Scan completed: {len(vulnerabilities)} vulnerabilities found in {scan_duration:.2f}s") | |
| return result | |
| def _scan_python_file(self, file_path: Path) -> list[Vulnerability]: | |
| """Scan a Python file for security vulnerabilities.""" | |
| vulnerabilities = [] | |
| try: | |
| with open(file_path, encoding="utf-8") as f: | |
| content = f.read() | |
| # Parse AST | |
| tree = ast.parse(content) | |
| lines = content.split("\n") | |
| # Security analysis | |
| for node in ast.walk(tree): | |
| # Hardcoded secrets | |
| if isinstance(node, ast.Assign): | |
| vulns = self._check_hardcoded_secrets(node, file_path, lines) | |
| vulnerabilities.extend(vulns) | |
| # Dangerous function calls | |
| if isinstance(node, ast.Call): | |
| vulns = self._check_dangerous_functions(node, file_path, lines) | |
| vulnerabilities.extend(vulns) | |
| # SQL injection risks | |
| if isinstance(node, ast.Call): | |
| vulns = self._check_sql_injection(node, file_path, lines) | |
| vulnerabilities.extend(vulns) | |
| # Path traversal | |
| if isinstance(node, ast.Call): | |
| vulns = self._check_path_traversal(node, file_path, lines) | |
| vulnerabilities.extend(vulns) | |
| # Insecure deserialization | |
| if isinstance(node, ast.Call): | |
| vulns = self._check_insecure_deserialization(node, file_path, lines) | |
| vulnerabilities.extend(vulns) | |
| # Command injection | |
| if isinstance(node, ast.Call): | |
| vulns = self._check_command_injection(node, file_path, lines) | |
| vulnerabilities.extend(vulns) | |
| except SyntaxError as e: | |
| logger.warning(f"Syntax error in {file_path}: {e}") | |
| except Exception as e: | |
| logger.warning(f"Failed to parse {file_path}: {e}") | |
| return vulnerabilities | |
| def _scan_config_file(self, file_path: Path) -> list[Vulnerability]: | |
| """Scan a configuration file for security issues.""" | |
| vulnerabilities = [] | |
| try: | |
| with open(file_path, encoding="utf-8") as f: | |
| content = f.read() | |
| lines = content.split("\n") | |
| # Check for exposed secrets | |
| for i, line in enumerate(lines, 1): | |
| for pattern_name, pattern_data in self._secret_patterns.items(): | |
| if pattern_data["pattern"].search(line): | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"secret_{file_path.stem}_{i}_{pattern_name}", | |
| type=VulnerabilityType.HARDCODED_SECRET, | |
| severity=VulnerabilitySeverity(pattern_data["severity"]), | |
| title=f"Hardcoded secret in {file_path.name}", | |
| description=f"Potential hardcoded {pattern_name} detected in configuration file", | |
| file_path=str(file_path), | |
| line_number=i, | |
| code_snippet=line.strip(), | |
| cwe_id=pattern_data.get("cwe_id"), | |
| cvss_score=pattern_data.get("cvss_score"), | |
| remediation="Remove hardcoded secrets and use environment variables or secret management", | |
| references=pattern_data.get("references", []), | |
| metadata={"pattern_name": pattern_name}, | |
| ) | |
| ) | |
| # Check for insecure configurations | |
| for i, line in enumerate(lines, 1): | |
| for config_name, config_data in self._insecure_patterns.items(): | |
| if config_data["pattern"].search(line, re.IGNORECASE): | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"config_{file_path.stem}_{i}_{config_name}", | |
| type=VulnerabilityType.INSECURE_CONFIGURATION, | |
| severity=VulnerabilitySeverity(config_data["severity"]), | |
| title=f"Insecure configuration: {config_name}", | |
| description=config_data["description"], | |
| file_path=str(file_path), | |
| line_number=i, | |
| code_snippet=line.strip(), | |
| cwe_id=config_data.get("cwe_id"), | |
| cvss_score=config_data.get("cvss_score"), | |
| remediation=config_data.get("remediation", "Review and fix the insecure configuration"), | |
| references=config_data.get("references", []), | |
| metadata={"config_name": config_name}, | |
| ) | |
| ) | |
| except Exception as e: | |
| logger.warning(f"Failed to scan config file {file_path}: {e}") | |
| return vulnerabilities | |
| def _scan_for_secrets(self, file_path: Path) -> list[Vulnerability]: | |
| """Scan a file for hardcoded secrets.""" | |
| vulnerabilities: list[Vulnerability] = [] | |
| # Skip binary files and large files | |
| if not self._should_scan_file(file_path): | |
| return vulnerabilities | |
| try: | |
| with open(file_path, encoding="utf-8", errors="ignore") as f: | |
| content = f.read() | |
| lines = content.split("\n") | |
| for i, line in enumerate(lines, 1): | |
| for pattern_name, pattern_data in self._secret_patterns.items(): | |
| if pattern_data["pattern"].search(line): | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"secret_{file_path.stem}_{i}_{pattern_name}", | |
| type=VulnerabilityType.HARDCODED_SECRET, | |
| severity=VulnerabilitySeverity(pattern_data["severity"]), | |
| title=f"Hardcoded secret in {file_path.name}", | |
| description=f"Potential hardcoded {pattern_name} detected", | |
| file_path=str(file_path), | |
| line_number=i, | |
| code_snippet=line.strip()[:100], # Truncate for storage | |
| cwe_id=pattern_data.get("cwe_id"), | |
| cvss_score=pattern_data.get("cvss_score"), | |
| remediation="Remove hardcoded secrets and use secure secret management", | |
| references=pattern_data.get("references", []), | |
| metadata={"pattern_name": pattern_name, "file_type": file_path.suffix}, | |
| ) | |
| ) | |
| except Exception as e: | |
| logger.warning(f"Failed to scan for secrets in {file_path}: {e}") | |
| return vulnerabilities | |
| def _scan_dependencies(self, scan_path: Path) -> list[Vulnerability]: | |
| """Scan dependencies for known vulnerabilities.""" | |
| vulnerabilities = [] | |
| # Check for requirements files | |
| requirements_files = [ | |
| scan_path / "requirements.txt", | |
| scan_path / "requirements-dev.txt", | |
| scan_path / "pyproject.toml", | |
| scan_path / "Pipfile", | |
| scan_path / "poetry.lock", | |
| ] | |
| for req_file in requirements_files: | |
| if req_file.exists(): | |
| try: | |
| file_vulns = self._check_requirements_file(req_file) | |
| vulnerabilities.extend(file_vulns) | |
| except Exception as e: | |
| logger.warning(f"Failed to check requirements file {req_file}: {e}") | |
| return vulnerabilities | |
| def _check_hardcoded_secrets(self, node: ast.Assign, file_path: Path, lines: list[str]) -> list[Vulnerability]: | |
| """Check for hardcoded secrets in assignment statements.""" | |
| vulnerabilities = [] | |
| for target in node.targets: | |
| if isinstance(target, ast.Name): | |
| var_name = target.id.lower() | |
| # Check if variable name suggests it's a secret | |
| secret_keywords = ["password", "secret", "key", "token", "api", "credential"] | |
| if any(keyword in var_name for keyword in secret_keywords): | |
| if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str): | |
| line_num = node.lineno | |
| if line_num <= len(lines): | |
| code_snippet = lines[line_num - 1].strip() | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"secret_{file_path.stem}_{line_num}_{var_name}", | |
| type=VulnerabilityType.HARDCODED_SECRET, | |
| severity=VulnerabilitySeverity.HIGH, | |
| title=f"Hardcoded secret: {var_name}", | |
| description=f"Hardcoded {var_name} detected in source code", | |
| file_path=str(file_path), | |
| line_number=line_num, | |
| code_snippet=code_snippet, | |
| cwe_id="CWE-798", | |
| cvss_score=7.5, | |
| remediation="Use environment variables or secret management system", | |
| references=["https://cwe.mitre.org/data/definitions/798.html"], | |
| metadata={"variable_name": var_name}, | |
| ) | |
| ) | |
| return vulnerabilities | |
| def _check_dangerous_functions(self, node: ast.Call, file_path: Path, lines: list[str]) -> list[Vulnerability]: | |
| """Check for dangerous function calls.""" | |
| vulnerabilities = [] | |
| dangerous_funcs = { | |
| "eval": {"severity": VulnerabilitySeverity.HIGH, "cwe": "CWE-94", "cvss": 8.6}, | |
| "exec": {"severity": VulnerabilitySeverity.HIGH, "cwe": "CWE-94", "cvss": 8.6}, | |
| "compile": {"severity": VulnerabilitySeverity.MEDIUM, "cwe": "CWE-94", "cvss": 6.1}, | |
| "__import__": {"severity": VulnerabilitySeverity.MEDIUM, "cwe": "CWE-94", "cvss": 6.1}, | |
| } | |
| if isinstance(node.func, ast.Name): | |
| func_name = node.func.id.lower() | |
| if func_name in dangerous_funcs: | |
| func_info = dangerous_funcs[func_name] | |
| line_num = node.lineno | |
| if line_num <= len(lines): | |
| code_snippet = lines[line_num - 1].strip() | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"dangerous_{file_path.stem}_{line_num}_{func_name}", | |
| type=VulnerabilityType.COMMAND_INJECTION, | |
| severity=VulnerabilitySeverity(func_info["severity"]), | |
| title=f"Dangerous function usage: {func_name}", | |
| description=f"Use of dangerous function {func_name} can lead to code injection", | |
| file_path=str(file_path), | |
| line_number=line_num, | |
| code_snippet=code_snippet, | |
| cwe_id=str(func_info["cwe"]) if func_info.get("cwe") else None, | |
| cvss_score=float(func_info["cvss"]) | |
| if isinstance(func_info.get("cvss"), (int, float)) | |
| else None, # type: ignore[arg-type] | |
| remediation=f"Avoid using {func_name}. Use safer alternatives", | |
| references=["https://cwe.mitre.org/data/definitions/94.html"], | |
| metadata={"function": func_name}, | |
| ) | |
| ) | |
| return vulnerabilities | |
| def _check_sql_injection(self, node: ast.Call, file_path: Path, lines: list[str]) -> list[Vulnerability]: | |
| """Check for SQL injection vulnerabilities.""" | |
| vulnerabilities = [] | |
| if isinstance(node.func, ast.Attribute): | |
| if node.func.attr.lower() in ["execute", "executemany"]: | |
| # Check if it's a database cursor | |
| if isinstance(node.func.value, ast.Name): | |
| if "cursor" in node.func.value.id.lower() or "db" in node.func.value.id.lower(): | |
| # Check if query contains string formatting | |
| if node.args: | |
| for arg in node.args: | |
| if isinstance(arg, ast.BinOp) and isinstance(arg.op, ast.Mod): | |
| line_num = node.lineno | |
| if line_num <= len(lines): | |
| code_snippet = lines[line_num - 1].strip() | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"sqli_{file_path.stem}_{line_num}", | |
| type=VulnerabilityType.SQL_INJECTION, | |
| severity=VulnerabilitySeverity.HIGH, | |
| title="Potential SQL injection", | |
| description="SQL query with string formatting detected", | |
| file_path=str(file_path), | |
| line_number=line_num, | |
| code_snippet=code_snippet, | |
| cwe_id="CWE-89", | |
| cvss_score=8.1, | |
| remediation="Use parameterized queries or prepared statements", | |
| references=["https://cwe.mitre.org/data/definitions/89.html"], | |
| metadata={"operation": node.func.attr}, | |
| ) | |
| ) | |
| return vulnerabilities | |
| def _check_path_traversal(self, node: ast.Call, file_path: Path, lines: list[str]) -> list[Vulnerability]: | |
| """Check for path traversal vulnerabilities.""" | |
| vulnerabilities = [] | |
| if isinstance(node.func, ast.Attribute): | |
| if node.func.attr in ["open", "read", "write"]: | |
| if isinstance(node.func.value, ast.Name) and node.func.value.id == "open": | |
| # Check file path operations | |
| if node.args: | |
| for arg in node.args: | |
| if isinstance(arg, ast.BinOp) and isinstance(arg.op, ast.Add): | |
| line_num = node.lineno | |
| if line_num <= len(lines): | |
| code_snippet = lines[line_num - 1].strip() | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"path_{file_path.stem}_{line_num}", | |
| type=VulnerabilityType.PATH_TRAVERSAL, | |
| severity=VulnerabilitySeverity.MEDIUM, | |
| title="Potential path traversal", | |
| description="File path concatenation detected", | |
| file_path=str(file_path), | |
| line_number=line_num, | |
| code_snippet=code_snippet, | |
| cwe_id="CWE-22", | |
| cvss_score=5.9, | |
| remediation="Validate and sanitize file paths", | |
| references=["https://cwe.mitre.org/data/definitions/22.html"], | |
| metadata={"operation": "file_operation"}, | |
| ) | |
| ) | |
| return vulnerabilities | |
| def _check_insecure_deserialization(self, node: ast.Call, file_path: Path, lines: list[str]) -> list[Vulnerability]: | |
| """Check for insecure deserialization.""" | |
| vulnerabilities = [] | |
| insecure_funcs = { | |
| "pickle.loads": {"severity": VulnerabilitySeverity.HIGH, "cwe": "CWE-502", "cvss": 8.8}, | |
| "pickle.load": {"severity": VulnerabilitySeverity.HIGH, "cwe": "CWE-502", "cvss": 8.8}, | |
| "cPickle.loads": {"severity": VulnerabilitySeverity.HIGH, "cwe": "CWE-502", "cvss": 8.8}, | |
| "cPickle.load": {"severity": VulnerabilitySeverity.HIGH, "cwe": "CWE-502", "cvss": 8.8}, | |
| } | |
| if isinstance(node.func, ast.Attribute): | |
| func_name = f"{node.func.value.id}.{node.func.attr}" if isinstance(node.func.value, ast.Name) else "" | |
| if func_name in insecure_funcs: | |
| func_info = insecure_funcs[func_name] | |
| line_num = node.lineno | |
| if line_num <= len(lines): | |
| code_snippet = lines[line_num - 1].strip() | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"deserialize_{file_path.stem}_{line_num}", | |
| type=VulnerabilityType.INSECURE_DESERIALIZATION, | |
| severity=VulnerabilitySeverity(func_info["severity"]), | |
| title=f"Insecure deserialization: {func_name}", | |
| description=f"Use of insecure deserialization function {func_name}", | |
| file_path=str(file_path), | |
| line_number=line_num, | |
| code_snippet=code_snippet, | |
| cwe_id=str(func_info["cwe"]) if func_info.get("cwe") else None, | |
| cvss_score=float(func_info["cvss"]) | |
| if isinstance(func_info.get("cvss"), (int, float)) | |
| else None, # type: ignore[arg-type] | |
| remediation="Use safe serialization formats like JSON", | |
| references=["https://cwe.mitre.org/data/definitions/502.html"], | |
| metadata={"function": func_name}, | |
| ) | |
| ) | |
| return vulnerabilities | |
| def _check_command_injection(self, node: ast.Call, file_path: Path, lines: list[str]) -> list[Vulnerability]: | |
| """Check for command injection vulnerabilities.""" | |
| vulnerabilities = [] | |
| if isinstance(node.func, ast.Attribute): | |
| if node.func.attr in ["system", "popen", "call", "run"]: | |
| if isinstance(node.func.value, ast.Name) and node.func.value.id in ["os", "subprocess"]: | |
| line_num = node.lineno | |
| if line_num <= len(lines): | |
| code_snippet = lines[line_num - 1].strip() | |
| vulnerabilities.append( | |
| Vulnerability( | |
| vulnerability_id=f"cmd_inject_{file_path.stem}_{line_num}", | |
| type=VulnerabilityType.COMMAND_INJECTION, | |
| severity=VulnerabilitySeverity.HIGH, | |
| title=f"Command injection risk: {node.func.attr}", | |
| description=f"Potential command injection in {node.func.value.id}.{node.func.attr}", | |
| file_path=str(file_path), | |
| line_number=line_num, | |
| code_snippet=code_snippet, | |
| cwe_id="CWE-78", | |
| cvss_score=8.6, | |
| remediation="Use safe alternatives and validate input", | |
| references=["https://cwe.mitre.org/data/definitions/78.html"], | |
| metadata={"function": f"{node.func.value.id}.{node.func.attr}"}, | |
| ) | |
| ) | |
| return vulnerabilities | |
| def _check_requirements_file(self, file_path: Path) -> list[Vulnerability]: | |
| """Check requirements file for vulnerable dependencies.""" | |
| vulnerabilities = [] | |
| try: | |
| with open(file_path, encoding="utf-8") as f: | |
| content = f.read() | |
| # This is a simplified check - in production, you'd use tools like safety | |
| # or dependency-check to actually check against vulnerability databases | |
| lines = content.split("\n") | |
| for i, line in enumerate(lines, 1): | |
| line = line.strip() | |
| if line and not line.startswith("#"): | |
| # Parse package name and version | |
| if "==" in line: | |
| package, version = line.split("==", 1) | |
| package = package.strip() | |
| version = version.strip() | |
| # Check for known vulnerable versions (simplified) | |
| vulnerable_packages = { | |
| "requests": ["<2.20.0"], | |
| "urllib3": ["<1.24.2"], | |
| "pillow": ["<6.2.0"], | |
| "jinja2": ["<2.11.2"], | |
| } | |
| if package.lower() in vulnerable_packages: | |
| vuln_versions = vulnerable_packages[package.lower()] | |
| vulnerabilities.extend( | |
| Vulnerability( | |
| vulnerability_id=f"dep_{file_path.stem}_{i}_{package}", | |
| type=VulnerabilityType.OUTDATED_DEPENDENCY, | |
| severity=VulnerabilitySeverity.MEDIUM, | |
| title=f"Vulnerable dependency: {package}", | |
| description=f"Package {package} version {version} has known vulnerabilities", | |
| file_path=str(file_path), | |
| line_number=i, | |
| code_snippet=line, | |
| cwe_id="CWE-1035", | |
| cvss_score=6.5, | |
| remediation=f"Update {package} to a secure version", | |
| references=["https://nvd.nist.gov/"], | |
| metadata={"package": package, "version": version}, | |
| ) | |
| for vuln_range in vuln_versions | |
| if self._version_matches(version, vuln_range) | |
| ) | |
| except Exception as e: | |
| logger.warning(f"Failed to check requirements file {file_path}: {e}") | |
| return vulnerabilities | |
| def _version_matches(self, version: str, version_range: str) -> bool: | |
| """Simple version matching (simplified).""" | |
| if version_range.startswith("<"): | |
| max_version = version_range[1:].strip() | |
| return version < max_version | |
| return False | |
| def _should_scan_file(self, file_path: Path) -> bool: | |
| """Check if a file should be scanned for secrets.""" | |
| # Skip binary files and common non-relevant files | |
| binary_extensions = {".pyc", ".pyo", ".pyd", ".so", ".dll", ".exe", ".bin", ".jpg", ".png", ".gif", ".pdf"} | |
| skip_dirs = {".git", "__pycache__", "node_modules", ".venv", "venv"} | |
| if file_path.suffix.lower() in binary_extensions: | |
| return False | |
| if any(skip_dir in file_path.parts for skip_dir in skip_dirs): | |
| return False | |
| # Skip large files (>1MB) | |
| try: | |
| if file_path.stat().st_size > 1024 * 1024: | |
| return False | |
| except OSError: | |
| return False | |
| return True | |
| def _deduplicate_vulnerabilities(self, vulnerabilities: list[Vulnerability]) -> list[Vulnerability]: | |
| """Remove duplicate vulnerabilities.""" | |
| seen = set() | |
| deduped = [] | |
| for vuln in vulnerabilities: | |
| # Create a unique key based on file, line, and type | |
| key = (vuln.file_path, vuln.line_number, vuln.type.value) | |
| if key not in seen: | |
| seen.add(key) | |
| deduped.append(vuln) | |
| return deduped | |
| def _generate_summary(self, vulnerabilities: list[Vulnerability]) -> dict[str, Any]: | |
| """Generate summary statistics for vulnerabilities.""" | |
| summary: dict[str, Any] = { | |
| "total_vulnerabilities": len(vulnerabilities), | |
| "by_severity": {}, | |
| "by_type": {}, | |
| "by_file": {}, | |
| } | |
| # Count by severity | |
| for vuln in vulnerabilities: | |
| severity = vuln.severity.value | |
| summary["by_severity"][severity] = summary["by_severity"].get(severity, 0) + 1 | |
| # Count by type | |
| for vuln in vulnerabilities: | |
| vuln_type = vuln.type.value | |
| summary["by_type"][vuln_type] = summary["by_type"].get(vuln_type, 0) + 1 | |
| # Count by file | |
| for vuln in vulnerabilities: | |
| file_path = vuln.file_path | |
| summary["by_file"][file_path] = summary["by_file"].get(file_path, 0) + 1 | |
| return summary | |
| def _load_secret_patterns(self) -> dict[str, dict[str, Any]]: | |
| """Load patterns for secret detection.""" | |
| return { | |
| "api_key": { | |
| "pattern": re.compile(r"(?i)(api[_-]?key|apikey)[\s=:]['\"]([a-zA-Z0-9]{20,})['\"]"), | |
| "severity": "high", | |
| "cwe_id": "CWE-798", | |
| "cvss_score": 7.5, | |
| "references": ["https://cwe.mitre.org/data/definitions/798.html"], | |
| }, | |
| "password": { | |
| "pattern": re.compile(r"(?i)(password|passwd|pwd)[\s=:]['\"]([^\s'\"`]{4,})['\"]"), | |
| "severity": "high", | |
| "cwe_id": "CWE-257", | |
| "cvss_score": 7.5, | |
| "references": ["https://cwe.mitre.org/data/definitions/257.html"], | |
| }, | |
| "secret": { | |
| "pattern": re.compile(r"(?i)(secret|private[_-]?key)[\s=:]['\"]([a-zA-Z0-9+/]{20,})['\"]"), | |
| "severity": "high", | |
| "cwe_id": "CWE-798", | |
| "cvss_score": 7.5, | |
| "references": ["https://cwe.mitre.org/data/definitions/798.html"], | |
| }, | |
| "token": { | |
| "pattern": re.compile(r"(?i)(token|access[_-]?token)[\s=:]['\"]([a-zA-Z0-9]{20,})['\"]"), | |
| "severity": "medium", | |
| "cwe_id": "CWE-798", | |
| "cvss_score": 6.5, | |
| "references": ["https://cwe.mitre.org/data/definitions/798.html"], | |
| }, | |
| } | |
| def _load_insecure_patterns(self) -> dict[str, dict[str, Any]]: | |
| """Load patterns for insecure configuration detection.""" | |
| return { | |
| "debug_enabled": { | |
| "pattern": re.compile(r"debug\s*[:=]\s*true", re.IGNORECASE), | |
| "severity": "medium", | |
| "description": "Debug mode enabled in production", | |
| "cwe_id": "CWE-489", | |
| "cvss_score": 5.3, | |
| "remediation": "Disable debug mode in production", | |
| "references": ["https://cwe.mitre.org/data/definitions/489.html"], | |
| }, | |
| "ssl_verify_disabled": { | |
| "pattern": re.compile(r"ssl[_-]?verify\s*[:=]\s*false", re.IGNORECASE), | |
| "severity": "medium", | |
| "description": "SSL certificate verification disabled", | |
| "cwe_id": "CWE-295", | |
| "cvss_score": 5.9, | |
| "remediation": "Enable SSL certificate verification", | |
| "references": ["https://cwe.mitre.org/data/definitions/295.html"], | |
| }, | |
| "cors_all_origins": { | |
| "pattern": re.compile(r"allow[_-]?all[_-]?origins\s*[:=]\s*true", re.IGNORECASE), | |
| "severity": "low", | |
| "description": "CORS allows all origins", | |
| "cwe_id": "CWE-942", | |
| "cvss_score": 4.3, | |
| "remediation": "Restrict CORS to specific origins", | |
| "references": ["https://cwe.mitre.org/data/definitions/942.html"], | |
| }, | |
| } | |
| def _load_crypto_patterns(self) -> dict[str, dict[str, Any]]: | |
| """Load patterns for insecure cryptography detection.""" | |
| return { | |
| "weak_hash": { | |
| "pattern": re.compile(r"(md5|sha1)\s*\(", re.IGNORECASE), | |
| "severity": "medium", | |
| "description": "Weak cryptographic hash function", | |
| "cwe_id": "CWE-328", | |
| "cvss_score": 5.9, | |
| "remediation": "Use stronger hash functions like SHA-256 or SHA-3", | |
| "references": ["https://cwe.mitre.org/data/definitions/328.html"], | |
| }, | |
| } | |
| def _load_portfolio_patterns(self) -> dict[str, dict[str, Any]]: | |
| """Load patterns for portfolio-sensitive financial data leak prevention.""" | |
| return { | |
| "portfolio_quantity": { | |
| "pattern": re.compile(r"(?i)(quantity|shares|units)[\s=:]['\"](\d{3,})['\"]"), | |
| "severity": "high", | |
| "description": "Potential portfolio quantity leak - large position size exposed", | |
| "cwe_id": "CWE-200", | |
| "cvss_score": 7.5, | |
| "remediation": "Use aggregated or anonymized metrics instead of raw quantities", | |
| "references": ["https://cwe.mitre.org/data/definitions/200.html"], | |
| }, | |
| "portfolio_balance": { | |
| "pattern": re.compile( | |
| r"(?i)(balance|total_value|portfolio_value)[\s=:]['\"]\$\s*([\d,]+\.?\d{2})['\"]" | |
| ), | |
| "severity": "high", | |
| "description": "Potential portfolio balance leak - exact value exposed", | |
| "cwe_id": "CWE-200", | |
| "cvss_score": 7.5, | |
| "remediation": "Use rounded or percentage-based values instead of exact amounts", | |
| "references": ["https://cwe.mitre.org/data/definitions/200.html"], | |
| }, | |
| "purchase_price": { | |
| "pattern": re.compile( | |
| r"(?i)(purchase_price|average_cost|cost_basis)[\s=:]['\"]\$\s*([\d,]+\.?\d{2})['\"]" | |
| ), | |
| "severity": "high", | |
| "description": "Potential purchase price leak - exact price exposed", | |
| "cwe_id": "CWE-200", | |
| "cvss_score": 7.5, | |
| "remediation": "Use percentage-based metrics instead of exact prices", | |
| "references": ["https://cwe.mitre.org/data/definitions/200.html"], | |
| }, | |
| "user_identifier": { | |
| "pattern": re.compile(r"(?i)(user_id|account_id|customer_id)[\s=:]['\"]([a-zA-Z0-9_-]{8,})['\"]"), | |
| "severity": "critical", | |
| "description": "Potential user identifier leak - raw ID exposed", | |
| "cwe_id": "CWE-359", | |
| "cvss_score": 9.0, | |
| "remediation": "Use hashed or anonymized identifiers", | |
| "references": ["https://cwe.mitre.org/data/definitions/359.html"], | |
| }, | |
| "transaction_details": { | |
| "pattern": re.compile(r"(?i)(transaction_id|order_id|trade_id)[\s=:]['\"]([a-zA-Z0-9_-]{10,})['\"]"), | |
| "severity": "medium", | |
| "description": "Potential transaction detail leak - traceable identifier exposed", | |
| "cwe_id": "CWE-200", | |
| "cvss_score": 6.5, | |
| "remediation": "Use anonymized or aggregated transaction data", | |
| "references": ["https://cwe.mitre.org/data/definitions/200.html"], | |
| }, | |
| } | |
| def _load_custom_rules(self) -> None: | |
| """Load custom scanning rules from file.""" | |
| if not self.custom_rules_path or not self.custom_rules_path.exists(): | |
| return | |
| try: | |
| with open(self.custom_rules_path) as f: | |
| self._custom_rules = json.load(f) | |
| logger.info(f"Loaded {len(self._custom_rules)} custom rules") | |
| except Exception as e: | |
| logger.warning(f"Failed to load custom rules: {e}") | |
| def _apply_custom_rules(self, scan_path: Path) -> list[Vulnerability]: | |
| """Apply custom scanning rules.""" | |
| vulnerabilities: list[Vulnerability] = [] | |
| for rule_name in self._custom_rules.keys(): | |
| try: | |
| # Apply custom rule logic | |
| # This is a placeholder for custom rule implementation | |
| pass | |
| except Exception as e: | |
| logger.warning(f"Failed to apply custom rule {rule_name}: {e}") | |
| return vulnerabilities | |
| # Global scanner instance | |
| _global_scanner: VulnerabilityScanner | None = None | |
| def get_vulnerability_scanner() -> VulnerabilityScanner: | |
| """Get or create global vulnerability scanner instance.""" | |
| global _global_scanner | |
| if _global_scanner is None: | |
| _global_scanner = VulnerabilityScanner() | |
| return _global_scanner | |
| def set_vulnerability_scanner(scanner: VulnerabilityScanner) -> None: | |
| """Set global vulnerability scanner instance.""" | |
| global _global_scanner | |
| _global_scanner = scanner | |
Xet Storage Details
- Size:
- 42 kB
- Xet hash:
- b0b466d1ddc91e5a59f3a51e0b2d89f7049f9b93f5f7eaf3d029238924890a54
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.