#!/usr/bin/env python3 """ Comprehensive security scanning script for MediGuard AI. Runs multiple security tools and generates consolidated reports. """ import os import sys import json import subprocess import argparse from datetime import datetime from pathlib import Path import logging # Setup logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) class SecurityScanner: """Comprehensive security scanner for the application.""" def __init__(self, output_dir: str = "security-reports"): self.output_dir = Path(output_dir) self.output_dir.mkdir(exist_ok=True) self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") self.results = {} def run_bandit(self) -> dict: """Run Bandit security linter.""" logger.info("Running Bandit security scan...") cmd = [ "bandit", "-r", "src/", "-f", "json", "-o", str(self.output_dir / f"bandit_{self.timestamp}.json"), "--quiet" ] try: subprocess.run(cmd, check=True) # Load results with open(self.output_dir / f"bandit_{self.timestamp}.json") as f: results = json.load(f) # Extract summary summary = { "high": 0, "medium": 0, "low": 0, "issues": results.get("results", []) } for issue in results.get("results", []): severity = issue.get("issue_severity", "LOW") if severity in summary: summary[severity] += 1 logger.info(f"Bandit completed: {summary['high']} high, {summary['medium']} medium, {summary['low']} low") return summary except subprocess.CalledProcessError as e: logger.error(f"Bandit scan failed: {e}") return {"error": str(e)} def run_safety(self) -> dict: """Run Safety to check for vulnerable dependencies.""" logger.info("Running Safety dependency scan...") cmd = [ "safety", "check", "--json", "--output", str(self.output_dir / f"safety_{self.timestamp}.json") ] try: result = subprocess.run(cmd, capture_output=True, text=True) # Parse results if result.stdout: vulnerabilities = json.loads(result.stdout) else: vulnerabilities = [] summary = { "vulnerabilities": len(vulnerabilities), "details": vulnerabilities } logger.info(f"Safety completed: {summary['vulnerabilities']} vulnerabilities found") return summary except Exception as e: logger.error(f"Safety scan failed: {e}") return {"error": str(e)} def run_semgrep(self) -> dict: """Run Semgrep for static analysis.""" logger.info("Running Semgrep static analysis...") config = "p/security-audit,p/secrets,p/owasp-top-ten" output_file = self.output_dir / f"semgrep_{self.timestamp}.json" cmd = [ "semgrep", "--config", config, "--json", "--output", str(output_file), "src/" ] try: subprocess.run(cmd, check=True) # Load results with open(output_file) as f: results = json.load(f) # Extract summary findings = results.get("results", []) summary = { "total_findings": len(findings), "by_severity": {}, "findings": findings[:50] # Limit to first 50 } for finding in findings: severity = finding.get("metadata", {}).get("severity", "INFO") summary["by_severity"][severity] = summary["by_severity"].get(severity, 0) + 1 logger.info(f"Semgrep completed: {summary['total_findings']} findings") return summary except subprocess.CalledProcessError as e: logger.error(f"Semgrep scan failed: {e}") return {"error": str(e)} except FileNotFoundError: logger.warning("Semgrep not installed, skipping...") return {"skipped": "Semgrep not installed"} def run_trivy(self, target: str = "filesystem") -> dict: """Run Trivy vulnerability scanner.""" logger.info(f"Running Trivy scan on {target}...") output_file = self.output_dir / f"trivy_{target}_{self.timestamp}.json" if target == "filesystem": cmd = [ "trivy", "fs", "--format", "json", "--output", str(output_file), "--quiet", "src/" ] elif target == "container": # Build image first subprocess.run(["docker", "build", "-t", "mediguard:scan", "."], check=True) cmd = [ "trivy", "image", "--format", "json", "--output", str(output_file), "--quiet", "mediguard:scan" ] else: return {"error": f"Unknown target: {target}"} try: subprocess.run(cmd, check=True) # Load results with open(output_file) as f: results = json.load(f) # Extract summary vulnerabilities = results.get("Results", []) summary = { "vulnerabilities": 0, "by_severity": {}, "details": vulnerabilities } for result in vulnerabilities: for vuln in result.get("Vulnerabilities", []): severity = vuln.get("Severity", "UNKNOWN") summary["by_severity"][severity] = summary["by_severity"].get(severity, 0) + 1 summary["vulnerabilities"] += 1 logger.info(f"Trivy completed: {summary['vulnerabilities']} vulnerabilities") return summary except subprocess.CalledProcessError as e: logger.error(f"Trivy scan failed: {e}") return {"error": str(e)} except FileNotFoundError: logger.warning("Trivy not installed, skipping...") return {"skipped": "Trivy not installed"} def run_gitleaks(self) -> dict: """Run Gitleaks to detect secrets in repository.""" logger.info("Running Gitleaks secret detection...") output_file = self.output_dir / f"gitleaks_{self.timestamp}.json" cmd = [ "gitleaks", "detect", "--source", ".", "--report-format", "json", "--report-path", str(output_file), "--verbose" ] try: subprocess.run(cmd, check=True) # Load results with open(output_file) as f: results = json.load(f) findings = results.get("findings", []) summary = { "secrets_found": len(findings), "findings": findings } if summary["secrets_found"] > 0: logger.warning(f"Gitleaks found {summary['secrets_found']} potential secrets!") else: logger.info("Gitleaks: No secrets found") return summary except subprocess.CalledProcessError as e: # Gitleaks returns non-zero if secrets are found if e.returncode == 1: # Load results anyway try: with open(output_file) as f: results = json.load(f) findings = results.get("findings", []) return { "secrets_found": len(findings), "findings": findings } except: pass logger.error(f"Gitleaks scan failed: {e}") return {"error": str(e)} except FileNotFoundError: logger.warning("Gitleaks not installed, skipping...") return {"skipped": "Gitleaks not installed"} def run_hipaa_compliance_check(self) -> dict: """Run custom HIPAA compliance checks.""" logger.info("Running HIPAA compliance checks...") violations = [] # Check for hardcoded credentials import re credential_pattern = re.compile( r"(password|secret|key|token|api_key|private_key)\s*[:=]\s*['\"][^'\"]{8,}['\"]", re.IGNORECASE ) # Check source files for py_file in Path("src").rglob("*.py"): try: content = py_file.read_text() matches = credential_pattern.finditer(content) for match in matches: violations.append({ "type": "hardcoded_credential", "file": str(py_file), "line": content[:match.start()].count('\n') + 1, "match": match.group() }) except: pass # Check for PHI patterns phi_patterns = [ (r"\b\d{3}-\d{2}-\d{4}\b", "ssn"), (r"\b\d{10}\b", "phone_number"), (r"\b\d{3}-\d{3}-\d{4}\b", "us_phone"), ] for pattern, phi_type in phi_patterns: regex = re.compile(pattern) for py_file in Path("src").rglob("*.py"): try: content = py_file.read_text() matches = regex.finditer(content) for match in matches: violations.append({ "type": f"potential_phi_{phi_type}", "file": str(py_file), "line": content[:match.start()].count('\n') + 1, "match": match.group() }) except: pass summary = { "violations": len(violations), "findings": violations } if summary["violations"] > 0: logger.warning(f"HIPAA check found {summary['violations']} potential violations") else: logger.info("HIPAA check passed") return summary def generate_report(self) -> str: """Generate consolidated security report.""" report_file = self.output_dir / f"security_report_{self.timestamp}.html" html_content = f"""
Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
{self.results.get('bandit', {}).get('high', 0)} High
{self.results.get('bandit', {}).get('medium', 0)} Medium
{self.results.get('bandit', {}).get('low', 0)} Low
{self.results.get('safety', {}).get('vulnerabilities', 0)} Vulnerabilities
{self.results.get('semgrep', {}).get('total_findings', 0)} Findings
{self.results.get('trivy', {}).get('vulnerabilities', 0)} Vulnerabilities
{self.results.get('gitleaks', {}).get('secrets_found', 0)} Secrets
{self.results.get('hipaa', {}).get('violations', 0)} Violations
{self._get_overall_status()}