devsecpac 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ """Nmap Container and Service Port Readiness Scanner."""
2
+
3
+ from pathlib import Path
4
+ from .base import BaseScanner
5
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
6
+ from ..runner import ProcessRunner
7
+ from ..discovery import TargetDiscovery
8
+
9
+
10
+ class NmapScanner(BaseScanner):
11
+ def __init__(self):
12
+ super().__init__(name="Nmap (Port & Service Probe)", category="Network Security", binary_name="nmap")
13
+
14
+ def scan(self, target_dir: Path) -> ToolResult:
15
+ discovery = TargetDiscovery(target_dir)
16
+ compose = discovery.discover_compose_files()
17
+
18
+ # Only run Nmap if local container or compose configuration is present
19
+ if not compose:
20
+ return self.create_not_applicable_result("No docker-compose or containerized service detected for port inspection")
21
+
22
+ if not self.is_tool_available():
23
+ return self.create_skipped_result("nmap binary not found in PATH")
24
+
25
+ # Probe standard application service ports on localhost
26
+ ports = "80,443,3000,5000,8000,8080,8443,9000"
27
+ cmd = [
28
+ str(self.binary_path),
29
+ "-p", ports,
30
+ "-T4",
31
+ "--open",
32
+ "127.0.0.1"
33
+ ]
34
+
35
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=60)
36
+
37
+ findings = FindingCounts()
38
+ items = []
39
+ open_ports = []
40
+
41
+ for line in stdout.splitlines():
42
+ line = line.strip()
43
+ if "/tcp" in line and "open" in line:
44
+ port_part = line.split("/")[0]
45
+ open_ports.append(port_part)
46
+ items.append(
47
+ FindingDetail(
48
+ severity="LOW",
49
+ tool=self.name,
50
+ file="localhost",
51
+ line=port_part,
52
+ rule="OPEN-SERVICE-PORT",
53
+ description=f"Port {port_part}/tcp is actively open and listening"
54
+ )
55
+ )
56
+
57
+ status = StatusEnum.PASS
58
+ if open_ports:
59
+ summary = f"Detected {len(open_ports)} listening service port(s): {', '.join(open_ports)}"
60
+ else:
61
+ summary = "No exposed service ports actively listening on localhost"
62
+
63
+ return ToolResult(
64
+ tool_name=self.name,
65
+ category=self.category,
66
+ status=status,
67
+ exit_code=code,
68
+ summary=summary,
69
+ findings=findings,
70
+ duration_seconds=elapsed,
71
+ items=items
72
+ )
@@ -0,0 +1,39 @@
1
+ """Software Bill of Materials (SBOM) generation with Syft."""
2
+
3
+ from pathlib import Path
4
+ from .base import BaseScanner
5
+ from ..contracts import ToolResult, StatusEnum, FindingCounts
6
+ from ..runner import ProcessRunner
7
+
8
+
9
+ class SyftScanner(BaseScanner):
10
+ def __init__(self):
11
+ super().__init__(name="Syft", category="SBOM Generation", binary_name="syft")
12
+
13
+ def scan(self, target_dir: Path) -> ToolResult:
14
+ if not self.is_tool_available():
15
+ return self.create_skipped_result("syft binary not found in PATH")
16
+
17
+ cyclonedx_file = target_dir / "sbom-cyclonedx.json"
18
+ cmd = [
19
+ str(self.binary_path),
20
+ "scan",
21
+ f"dir:{target_dir}",
22
+ "-o", f"cyclonedx-json={cyclonedx_file}",
23
+ "-q"
24
+ ]
25
+
26
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir))
27
+
28
+ status = StatusEnum.PASS if code == 0 and cyclonedx_file.exists() else StatusEnum.ERROR
29
+ summary = f"Generated CycloneDX SBOM at {cyclonedx_file.name}" if status == StatusEnum.PASS else "Failed to generate SBOM"
30
+
31
+ return ToolResult(
32
+ tool_name=self.name,
33
+ category=self.category,
34
+ status=status,
35
+ exit_code=code,
36
+ summary=summary,
37
+ findings=FindingCounts(),
38
+ duration_seconds=elapsed
39
+ )
@@ -0,0 +1,192 @@
1
+ """Software Composition Analysis (SCA) & Filesystem Vulnerability Scanners."""
2
+
3
+ from pathlib import Path
4
+ import os
5
+ import shutil
6
+ import json
7
+ from .base import BaseScanner
8
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
9
+ from ..runner import ProcessRunner
10
+
11
+
12
+ class TrivyFSScanner(BaseScanner):
13
+ def __init__(self):
14
+ super().__init__(name="Aqua Trivy (FS)", category="SCA & Vulnerability", binary_name="trivy")
15
+
16
+ def scan(self, target_dir: Path) -> ToolResult:
17
+ if not self.is_tool_available():
18
+ return self.create_skipped_result("trivy binary not found in PATH")
19
+
20
+ cmd = [
21
+ str(self.binary_path),
22
+ "fs",
23
+ "--format", "json",
24
+ "--quiet",
25
+ str(target_dir)
26
+ ]
27
+
28
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=600)
29
+
30
+ findings = FindingCounts()
31
+ items = []
32
+ summary = "No filesystem vulnerabilities detected"
33
+
34
+ if stdout.strip():
35
+ try:
36
+ data = json.loads(stdout)
37
+ results = data.get("Results", [])
38
+ for res in results:
39
+ target_file = res.get("Target", "filesystem")
40
+ vulns = res.get("Vulnerabilities", [])
41
+ for v in vulns:
42
+ sev = v.get("Severity", "UNKNOWN").upper()
43
+ if sev == "CRITICAL":
44
+ findings.critical += 1
45
+ elif sev == "HIGH":
46
+ findings.high += 1
47
+ elif sev == "MEDIUM":
48
+ findings.medium += 1
49
+ elif sev == "LOW":
50
+ findings.low += 1
51
+ else:
52
+ findings.info += 1
53
+
54
+ cve_id = v.get("VulnerabilityID", "")
55
+ pkg_name = v.get("PkgName", "")
56
+ installed_ver = v.get("InstalledVersion", "")
57
+ fixed_ver = v.get("FixedVersion", "")
58
+ desc = f"{pkg_name} {installed_ver}"
59
+ if fixed_ver:
60
+ desc += f" -> fixed in {fixed_ver}"
61
+
62
+ items.append(
63
+ FindingDetail(
64
+ severity=sev,
65
+ tool=self.name,
66
+ file=target_file,
67
+ line="",
68
+ rule=cve_id,
69
+ description=desc
70
+ )
71
+ )
72
+
73
+ if findings.total > 0:
74
+ summary = (
75
+ f"Found {findings.total} package vulnerabilities "
76
+ f"({findings.critical} Crit, {findings.high} High, {findings.medium} Med, {findings.low} Low)"
77
+ )
78
+ except Exception:
79
+ pass
80
+
81
+ status = StatusEnum.FAIL if findings.has_blocking else StatusEnum.PASS
82
+
83
+ return ToolResult(
84
+ tool_name=self.name,
85
+ category=self.category,
86
+ status=status,
87
+ exit_code=0,
88
+ summary=summary,
89
+ findings=findings,
90
+ duration_seconds=elapsed,
91
+ items=items
92
+ )
93
+
94
+
95
+ class DependencyCheckScanner(BaseScanner):
96
+ def __init__(self):
97
+ super().__init__(name="OWASP Dependency-Check", category="SCA", binary_name="dependency-check")
98
+
99
+ def scan(self, target_dir: Path) -> ToolResult:
100
+ if not self.is_tool_available():
101
+ return self.create_skipped_result("dependency-check binary not found in PATH")
102
+
103
+ out_dir = target_dir / ".owasp_dc"
104
+ nvd_api_key = os.environ.get("NVD_API_KEY", "")
105
+
106
+ cmd = [
107
+ str(self.binary_path),
108
+ "--scan", str(target_dir),
109
+ "--format", "JSON",
110
+ "--out", str(out_dir),
111
+ "--failOnCVSS", "7",
112
+ "--disableAssembly" # avoid heavy .NET reflection overhead
113
+ ]
114
+
115
+ if nvd_api_key:
116
+ cmd.extend(["--nvdApiKey", nvd_api_key])
117
+ else:
118
+ # Without an NVD API key, NIST rate-limits download requests heavily
119
+ # Pass noupdate if local database cache exists to avoid 10-minute freezes
120
+ data_dir = Path.home() / ".local" / "opt" / "dependency-check" / "data"
121
+ if (data_dir / "odc.mv.db").exists():
122
+ cmd.append("--noupdate")
123
+
124
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=120)
125
+
126
+ findings = FindingCounts()
127
+ items = []
128
+
129
+ if code == -1:
130
+ return self.create_skipped_result("NVD feed download timed out (export NVD_API_KEY for faster updates)")
131
+
132
+ report_file = out_dir / "dependency-check-report.json"
133
+ if not report_file.exists():
134
+ if code != 0:
135
+ return self.create_skipped_result("Dependency-Check run failed (NVD database feed unavailable)")
136
+ status = StatusEnum.PASS
137
+ summary = "No CVE vulnerabilities >= CVSS 7.0 detected"
138
+ else:
139
+ status = StatusEnum.PASS
140
+ summary = "No CVE vulnerabilities >= CVSS 7.0 detected"
141
+ try:
142
+ data = json.loads(report_file.read_text(encoding="utf-8"))
143
+ dependencies = data.get("dependencies", [])
144
+ for dep in dependencies:
145
+ file_name = dep.get("fileName", "unknown")
146
+ vulns = dep.get("vulnerabilities", [])
147
+ for v in vulns:
148
+ cvss_score = float(v.get("cvssv3", {}).get("baseScore", 0.0) or v.get("cvssv2", {}).get("score", 0.0))
149
+ sev = "LOW"
150
+ if cvss_score >= 9.0:
151
+ findings.critical += 1
152
+ sev = "CRITICAL"
153
+ elif cvss_score >= 7.0:
154
+ findings.high += 1
155
+ sev = "HIGH"
156
+ elif cvss_score >= 4.0:
157
+ findings.medium += 1
158
+ sev = "MEDIUM"
159
+ else:
160
+ findings.low += 1
161
+
162
+ cve_name = v.get("name", "CVE")
163
+ desc = v.get("description", "")[:100]
164
+ items.append(
165
+ FindingDetail(
166
+ severity=sev,
167
+ tool=self.name,
168
+ file=file_name,
169
+ line="",
170
+ rule=cve_name,
171
+ description=desc
172
+ )
173
+ )
174
+
175
+ if findings.has_blocking:
176
+ status = StatusEnum.FAIL
177
+ summary = f"Detected {findings.critical} Critical and {findings.high} High CVEs"
178
+ except Exception:
179
+ pass
180
+ finally:
181
+ shutil.rmtree(out_dir, ignore_errors=True)
182
+
183
+ return ToolResult(
184
+ tool_name=self.name,
185
+ category=self.category,
186
+ status=status,
187
+ exit_code=code,
188
+ summary=summary,
189
+ findings=findings,
190
+ duration_seconds=elapsed,
191
+ items=items
192
+ )
@@ -0,0 +1,77 @@
1
+ """Schemathesis API Contract & Schema Security Scanner."""
2
+
3
+ from pathlib import Path
4
+ from typing import List
5
+ from .base import BaseScanner
6
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
7
+ from ..runner import ProcessRunner
8
+
9
+
10
+ class SchemathesisScanner(BaseScanner):
11
+ def __init__(self):
12
+ super().__init__(name="Schemathesis", category="API Security", binary_name="st")
13
+
14
+ def _discover_api_schemas(self, target_dir: Path) -> List[Path]:
15
+ """Finds OpenAPI/Swagger/GraphQL definition files."""
16
+ patterns = [
17
+ "**/openapi.json", "**/openapi.yaml", "**/openapi.yml",
18
+ "**/swagger.json", "**/swagger.yaml", "**/swagger.yml",
19
+ "**/schema.graphql"
20
+ ]
21
+ schemas = []
22
+ for pat in patterns:
23
+ for p in target_dir.glob(pat):
24
+ if p.is_file() and ".git" not in p.parts:
25
+ schemas.append(p)
26
+ return schemas
27
+
28
+ def scan(self, target_dir: Path) -> ToolResult:
29
+ schemas = self._discover_api_schemas(target_dir)
30
+
31
+ if not schemas:
32
+ return self.create_not_applicable_result("No OpenAPI/Swagger schemas detected")
33
+
34
+ if not self.is_tool_available():
35
+ return self.create_skipped_result("schemathesis ('st') binary not found in PATH")
36
+
37
+ findings = FindingCounts()
38
+ items = []
39
+
40
+ # Validate schema structure and security definitions
41
+ primary_schema = schemas[0]
42
+ cmd = [
43
+ str(self.binary_path),
44
+ "run",
45
+ str(primary_schema),
46
+ "--dry-run",
47
+ "--checks=all"
48
+ ]
49
+
50
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=120)
51
+
52
+ if code != 0:
53
+ findings.medium += 1
54
+ items.append(
55
+ FindingDetail(
56
+ severity="MEDIUM",
57
+ tool=self.name,
58
+ file=str(primary_schema.relative_to(target_dir)),
59
+ line="1",
60
+ rule="api/contract-security-violation",
61
+ description="API schema contains specification or property boundary violations"
62
+ )
63
+ )
64
+
65
+ status = StatusEnum.FAIL if (findings.critical + findings.high) > 0 else StatusEnum.PASS
66
+ summary = f"Schemathesis audited {len(schemas)} API schema(s): {findings.total} issue(s) detected"
67
+
68
+ return ToolResult(
69
+ tool_name=self.name,
70
+ category=self.category,
71
+ status=status,
72
+ exit_code=code,
73
+ summary=summary,
74
+ findings=findings,
75
+ duration_seconds=elapsed,
76
+ items=items
77
+ )
@@ -0,0 +1,170 @@
1
+ """Secret detection scanners: Gitleaks & TruffleHog."""
2
+
3
+ from pathlib import Path
4
+ import json
5
+ from .base import BaseScanner
6
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
7
+ from ..runner import ProcessRunner
8
+
9
+
10
+ class GitleaksScanner(BaseScanner):
11
+ def __init__(self):
12
+ super().__init__(name="Gitleaks", category="Secret Detection", binary_name="gitleaks")
13
+
14
+ def scan(self, target_dir: Path) -> ToolResult:
15
+ if not self.is_tool_available():
16
+ return self.create_skipped_result("gitleaks binary not found in PATH")
17
+
18
+ report_file = target_dir / ".gitleaks_report.json"
19
+ is_git = (target_dir / ".git").is_dir()
20
+
21
+ cmd = [
22
+ str(self.binary_path),
23
+ "detect",
24
+ "--source", str(target_dir),
25
+ "--report-format", "json",
26
+ "--report-path", str(report_file),
27
+ "--exit-code", "0"
28
+ ]
29
+ if not is_git:
30
+ cmd.append("--no-git")
31
+
32
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=600)
33
+
34
+ findings = FindingCounts()
35
+ items = []
36
+ summary = "No secrets detected"
37
+ status = StatusEnum.PASS
38
+
39
+ if report_file.exists():
40
+ try:
41
+ data = json.loads(report_file.read_text(encoding="utf-8"))
42
+ if isinstance(data, list) and len(data) > 0:
43
+ findings.high = len(data)
44
+ status = StatusEnum.FAIL
45
+ summary = f"Detected {len(data)} potential secret(s)"
46
+
47
+ for finding in data:
48
+ file_path = finding.get("File", "unknown")
49
+ line_no = str(finding.get("StartLine", ""))
50
+ rule_id = finding.get("RuleID", "Secret")
51
+ desc = finding.get("Description", rule_id)
52
+ commit_hash = finding.get("Commit", "")
53
+ if commit_hash:
54
+ desc += f" (commit {commit_hash[:8]})"
55
+
56
+ items.append(
57
+ FindingDetail(
58
+ severity="HIGH",
59
+ tool=self.name,
60
+ file=file_path,
61
+ line=line_no,
62
+ rule=rule_id,
63
+ description=desc
64
+ )
65
+ )
66
+ except Exception:
67
+ pass
68
+ finally:
69
+ report_file.unlink(missing_ok=True)
70
+
71
+ return ToolResult(
72
+ tool_name=self.name,
73
+ category=self.category,
74
+ status=status,
75
+ exit_code=code,
76
+ summary=summary,
77
+ findings=findings,
78
+ duration_seconds=elapsed,
79
+ items=items
80
+ )
81
+
82
+
83
+ class TruffleHogScanner(BaseScanner):
84
+ def __init__(self):
85
+ super().__init__(name="TruffleHog", category="Secret Detection", binary_name="trufflehog")
86
+
87
+ def scan(self, target_dir: Path) -> ToolResult:
88
+ if not self.is_tool_available():
89
+ return self.create_skipped_result("trufflehog binary not found in PATH")
90
+
91
+ is_git = (target_dir / ".git").is_dir()
92
+
93
+ # If git repo, scan git history right from root commit to latest
94
+ if is_git:
95
+ # TruffleHog git file://
96
+ uri = target_dir.as_uri()
97
+ cmd = [
98
+ str(self.binary_path),
99
+ "git",
100
+ uri,
101
+ "--json",
102
+ "--only-verified"
103
+ ]
104
+ else:
105
+ cmd = [
106
+ str(self.binary_path),
107
+ "filesystem",
108
+ str(target_dir),
109
+ "--json",
110
+ "--only-verified"
111
+ ]
112
+
113
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=600)
114
+
115
+ findings = FindingCounts()
116
+ items = []
117
+ verified_count = 0
118
+
119
+ for line in stdout.splitlines():
120
+ line = line.strip()
121
+ if not line:
122
+ continue
123
+ try:
124
+ item = json.loads(line)
125
+ if item.get("Verified", False):
126
+ verified_count += 1
127
+ source_meta = item.get("SourceMetadata", {}).get("Data", {})
128
+ # Handle Git source vs Filesystem source metadata
129
+ git_meta = source_meta.get("Git", {})
130
+ fs_meta = source_meta.get("Filesystem", {})
131
+
132
+ file_path = git_meta.get("file") or fs_meta.get("file") or "unknown"
133
+ line_no = str(git_meta.get("line") or fs_meta.get("line") or "")
134
+ commit_hash = git_meta.get("commit", "")
135
+ detector = item.get("DetectorName", "VerifiedSecret")
136
+ desc = f"Verified {detector} credential"
137
+ if commit_hash:
138
+ desc += f" (in commit {commit_hash[:8]})"
139
+
140
+ items.append(
141
+ FindingDetail(
142
+ severity="CRITICAL",
143
+ tool=self.name,
144
+ file=file_path,
145
+ line=line_no,
146
+ rule=detector,
147
+ description=desc
148
+ )
149
+ )
150
+ except Exception:
151
+ continue
152
+
153
+ if verified_count > 0:
154
+ findings.critical = verified_count
155
+ status = StatusEnum.FAIL
156
+ summary = f"Detected {verified_count} verified active secret(s)!"
157
+ else:
158
+ status = StatusEnum.PASS
159
+ summary = "No verified secrets detected"
160
+
161
+ return ToolResult(
162
+ tool_name=self.name,
163
+ category=self.category,
164
+ status=status,
165
+ exit_code=code,
166
+ summary=summary,
167
+ findings=findings,
168
+ duration_seconds=elapsed,
169
+ items=items
170
+ )
@@ -0,0 +1,95 @@
1
+ """Semgrep Fast SAST and Security Guardrail Scanner."""
2
+
3
+ from pathlib import Path
4
+ import json
5
+ from .base import BaseScanner
6
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
7
+ from ..runner import ProcessRunner
8
+ from ..discovery import TargetDiscovery
9
+
10
+
11
+ class SemgrepScanner(BaseScanner):
12
+ def __init__(self):
13
+ super().__init__(name="Semgrep", category="Fast SAST", binary_name="semgrep")
14
+
15
+ def scan(self, target_dir: Path) -> ToolResult:
16
+ discovery = TargetDiscovery(target_dir)
17
+ languages = discovery.detect_languages()
18
+
19
+ if not languages:
20
+ return self.create_not_applicable_result("No application source files detected")
21
+
22
+ if not self.is_tool_available():
23
+ return self.create_skipped_result("semgrep binary not found in PATH")
24
+
25
+ # Run semgrep with auto-config (default security audit ruleset)
26
+ cmd = [
27
+ str(self.binary_path),
28
+ "scan",
29
+ "--config=auto",
30
+ "--json",
31
+ "--quiet",
32
+ "--no-git-ignore"
33
+ ]
34
+
35
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=300)
36
+
37
+ findings = FindingCounts()
38
+ items = []
39
+
40
+ try:
41
+ data = json.loads(stdout)
42
+ results = data.get("results", [])
43
+
44
+ for res in results:
45
+ raw_sev = str(res.get("extra", {}).get("severity", "INFO")).upper()
46
+ rule_id = res.get("check_id", "SemgrepRule")
47
+ msg = res.get("extra", {}).get("message", "Semgrep finding")
48
+ rel_path = res.get("path", "")
49
+ start_line = str(res.get("start", {}).get("line", ""))
50
+
51
+ sev_level = "LOW"
52
+ if raw_sev == "ERROR":
53
+ findings.high += 1
54
+ sev_level = "HIGH"
55
+ elif raw_sev == "WARNING":
56
+ findings.medium += 1
57
+ sev_level = "MEDIUM"
58
+ else:
59
+ findings.low += 1
60
+ sev_level = "LOW"
61
+
62
+ items.append(
63
+ FindingDetail(
64
+ severity=sev_level,
65
+ tool=self.name,
66
+ file=rel_path,
67
+ line=start_line,
68
+ rule=rule_id,
69
+ description=msg
70
+ )
71
+ )
72
+
73
+ except Exception:
74
+ pass
75
+
76
+ if (findings.critical + findings.high) > 0:
77
+ status = StatusEnum.FAIL
78
+ summary = f"Semgrep detected {findings.critical} Critical, {findings.high} High issue(s)"
79
+ elif (findings.medium + findings.low) > 0:
80
+ status = StatusEnum.PASS
81
+ summary = f"Semgrep detected {findings.medium + findings.low} non-blocking issue(s)"
82
+ else:
83
+ status = StatusEnum.PASS
84
+ summary = "Semgrep fast SAST analysis passed"
85
+
86
+ return ToolResult(
87
+ tool_name=self.name,
88
+ category=self.category,
89
+ status=status,
90
+ exit_code=code,
91
+ summary=summary,
92
+ findings=findings,
93
+ duration_seconds=elapsed,
94
+ items=items
95
+ )