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.
- devsec_cli/__init__.py +4 -0
- devsec_cli/bypass.py +98 -0
- devsec_cli/ci.py +163 -0
- devsec_cli/cli.py +431 -0
- devsec_cli/contracts.py +67 -0
- devsec_cli/correlator.py +110 -0
- devsec_cli/discovery.py +129 -0
- devsec_cli/ingestion.py +140 -0
- devsec_cli/installer.py +453 -0
- devsec_cli/remediation.py +63 -0
- devsec_cli/reporter.py +207 -0
- devsec_cli/runner.py +68 -0
- devsec_cli/scanners/__init__.py +1 -0
- devsec_cli/scanners/base.py +45 -0
- devsec_cli/scanners/codeql.py +140 -0
- devsec_cli/scanners/cosign.py +69 -0
- devsec_cli/scanners/dast.py +127 -0
- devsec_cli/scanners/docker.py +92 -0
- devsec_cli/scanners/iac.py +170 -0
- devsec_cli/scanners/k8s_audit.py +132 -0
- devsec_cli/scanners/kyverno.py +82 -0
- devsec_cli/scanners/mobsf.py +155 -0
- devsec_cli/scanners/nmap.py +72 -0
- devsec_cli/scanners/sbom.py +39 -0
- devsec_cli/scanners/sca.py +192 -0
- devsec_cli/scanners/schemathesis.py +77 -0
- devsec_cli/scanners/secrets.py +170 -0
- devsec_cli/scanners/semgrep.py +95 -0
- devsec_cli/scanners/sonar.py +322 -0
- devsecpac-2.0.0.dist-info/METADATA +249 -0
- devsecpac-2.0.0.dist-info/RECORD +34 -0
- devsecpac-2.0.0.dist-info/WHEEL +5 -0
- devsecpac-2.0.0.dist-info/entry_points.txt +3 -0
- devsecpac-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Dockerfile linting with Hadolint."""
|
|
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 HadolintScanner(BaseScanner):
|
|
12
|
+
def __init__(self):
|
|
13
|
+
super().__init__(name="Hadolint", category="Container Security", binary_name="hadolint")
|
|
14
|
+
|
|
15
|
+
def scan(self, target_dir: Path) -> ToolResult:
|
|
16
|
+
discovery = TargetDiscovery(target_dir)
|
|
17
|
+
dockerfiles = discovery.discover_dockerfiles()
|
|
18
|
+
|
|
19
|
+
if not dockerfiles:
|
|
20
|
+
return self.create_not_applicable_result("No Dockerfile detected in repository")
|
|
21
|
+
|
|
22
|
+
if not self.is_tool_available():
|
|
23
|
+
return self.create_skipped_result("hadolint binary not found in PATH")
|
|
24
|
+
|
|
25
|
+
findings = FindingCounts()
|
|
26
|
+
items = []
|
|
27
|
+
total_issues = 0
|
|
28
|
+
total_time = 0.0
|
|
29
|
+
file_timings = {}
|
|
30
|
+
|
|
31
|
+
for df in dockerfiles:
|
|
32
|
+
rel_file = str(Path(df).relative_to(target_dir)) if str(df).startswith(str(target_dir)) else Path(df).name
|
|
33
|
+
cmd = [
|
|
34
|
+
str(self.binary_path),
|
|
35
|
+
"--format", "json",
|
|
36
|
+
str(df)
|
|
37
|
+
]
|
|
38
|
+
code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir))
|
|
39
|
+
total_time += elapsed
|
|
40
|
+
file_timings[rel_file] = round(elapsed, 3)
|
|
41
|
+
|
|
42
|
+
if stdout.strip():
|
|
43
|
+
try:
|
|
44
|
+
entries = json.loads(stdout)
|
|
45
|
+
for entry in entries:
|
|
46
|
+
total_issues += 1
|
|
47
|
+
level = entry.get("level", "info").lower()
|
|
48
|
+
sev = "INFO"
|
|
49
|
+
if level == "error":
|
|
50
|
+
findings.high += 1
|
|
51
|
+
sev = "HIGH"
|
|
52
|
+
elif level == "warning":
|
|
53
|
+
findings.medium += 1
|
|
54
|
+
sev = "MEDIUM"
|
|
55
|
+
elif level == "info":
|
|
56
|
+
findings.low += 1
|
|
57
|
+
sev = "LOW"
|
|
58
|
+
else:
|
|
59
|
+
findings.info += 1
|
|
60
|
+
|
|
61
|
+
rel_file = str(Path(df).relative_to(target_dir)) if str(df).startswith(str(target_dir)) else Path(df).name
|
|
62
|
+
items.append(
|
|
63
|
+
FindingDetail(
|
|
64
|
+
severity=sev,
|
|
65
|
+
tool=self.name,
|
|
66
|
+
file=rel_file,
|
|
67
|
+
line=str(entry.get("line", "")),
|
|
68
|
+
rule=entry.get("code", "HadolintRule"),
|
|
69
|
+
description=entry.get("message", "")
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
except Exception:
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
status = StatusEnum.FAIL if findings.has_blocking else StatusEnum.PASS
|
|
76
|
+
summary = (
|
|
77
|
+
f"Analyzed {len(dockerfiles)} Dockerfile(s): {total_issues} issue(s) found "
|
|
78
|
+
f"({findings.high} High, {findings.medium} Med, {findings.low} Low)"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
return ToolResult(
|
|
82
|
+
tool_name=self.name,
|
|
83
|
+
category=self.category,
|
|
84
|
+
status=status,
|
|
85
|
+
exit_code=0,
|
|
86
|
+
summary=summary,
|
|
87
|
+
findings=findings,
|
|
88
|
+
duration_seconds=round(total_time, 2),
|
|
89
|
+
files_scanned=len(dockerfiles),
|
|
90
|
+
file_timings=file_timings,
|
|
91
|
+
items=items
|
|
92
|
+
)
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Infrastructure-as-Code and Kubernetes schema scanners: Checkov & Kubeconform."""
|
|
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 CheckovScanner(BaseScanner):
|
|
12
|
+
def __init__(self):
|
|
13
|
+
super().__init__(name="Checkov", category="IaC Security", binary_name="checkov")
|
|
14
|
+
|
|
15
|
+
def scan(self, target_dir: Path) -> ToolResult:
|
|
16
|
+
discovery = TargetDiscovery(target_dir)
|
|
17
|
+
k8s_files = discovery.discover_k8s_manifests()
|
|
18
|
+
iac_files = discovery.discover_iac_files()
|
|
19
|
+
|
|
20
|
+
if not k8s_files and not iac_files:
|
|
21
|
+
return self.create_not_applicable_result("No IaC or Kubernetes files detected")
|
|
22
|
+
|
|
23
|
+
if not self.is_tool_available():
|
|
24
|
+
return self.create_skipped_result("checkov binary not found in PATH")
|
|
25
|
+
|
|
26
|
+
cmd = [
|
|
27
|
+
str(self.binary_path),
|
|
28
|
+
"-d", str(target_dir),
|
|
29
|
+
"-o", "json",
|
|
30
|
+
"--soft-fail",
|
|
31
|
+
"--compact"
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=600)
|
|
35
|
+
|
|
36
|
+
findings = FindingCounts()
|
|
37
|
+
items = []
|
|
38
|
+
summary = "No IaC security violations detected"
|
|
39
|
+
|
|
40
|
+
if stdout.strip():
|
|
41
|
+
try:
|
|
42
|
+
data = json.loads(stdout)
|
|
43
|
+
reports = data if isinstance(data, list) else [data]
|
|
44
|
+
for report in reports:
|
|
45
|
+
results = report.get("results", {})
|
|
46
|
+
failed_checks = results.get("failed_checks", [])
|
|
47
|
+
for check in failed_checks:
|
|
48
|
+
raw_sev = str(check.get("severity") or "").upper()
|
|
49
|
+
sev = "MEDIUM"
|
|
50
|
+
if raw_sev == "CRITICAL":
|
|
51
|
+
findings.critical += 1
|
|
52
|
+
sev = "CRITICAL"
|
|
53
|
+
elif raw_sev == "HIGH":
|
|
54
|
+
findings.high += 1
|
|
55
|
+
sev = "HIGH"
|
|
56
|
+
elif raw_sev == "MEDIUM":
|
|
57
|
+
findings.medium += 1
|
|
58
|
+
sev = "MEDIUM"
|
|
59
|
+
elif raw_sev == "LOW":
|
|
60
|
+
findings.low += 1
|
|
61
|
+
sev = "LOW"
|
|
62
|
+
else:
|
|
63
|
+
findings.medium += 1
|
|
64
|
+
|
|
65
|
+
file_path = check.get("file_path", "unknown")
|
|
66
|
+
line_range = check.get("file_line_range", [])
|
|
67
|
+
line_str = f"{line_range[0]}-{line_range[1]}" if len(line_range) >= 2 else ""
|
|
68
|
+
check_id = check.get("check_id", "CheckovRule")
|
|
69
|
+
check_name = check.get("check_name", "")
|
|
70
|
+
|
|
71
|
+
items.append(
|
|
72
|
+
FindingDetail(
|
|
73
|
+
severity=sev,
|
|
74
|
+
tool=self.name,
|
|
75
|
+
file=file_path.lstrip("/"),
|
|
76
|
+
line=line_str,
|
|
77
|
+
rule=check_id,
|
|
78
|
+
description=check_name
|
|
79
|
+
)
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
if findings.total > 0:
|
|
83
|
+
summary = (
|
|
84
|
+
f"Found {findings.total} IaC misconfigurations "
|
|
85
|
+
f"({findings.critical} Crit, {findings.high} High, {findings.medium} Med, {findings.low} Low)"
|
|
86
|
+
)
|
|
87
|
+
except Exception:
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
status = StatusEnum.FAIL if findings.has_blocking else StatusEnum.PASS
|
|
91
|
+
|
|
92
|
+
return ToolResult(
|
|
93
|
+
tool_name=self.name,
|
|
94
|
+
category=self.category,
|
|
95
|
+
status=status,
|
|
96
|
+
exit_code=0,
|
|
97
|
+
summary=summary,
|
|
98
|
+
findings=findings,
|
|
99
|
+
duration_seconds=elapsed,
|
|
100
|
+
items=items
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class KubeconformScanner(BaseScanner):
|
|
105
|
+
def __init__(self):
|
|
106
|
+
super().__init__(name="Kubeconform", category="Kubernetes Security", binary_name="kubeconform")
|
|
107
|
+
|
|
108
|
+
def scan(self, target_dir: Path) -> ToolResult:
|
|
109
|
+
discovery = TargetDiscovery(target_dir)
|
|
110
|
+
k8s_files = discovery.discover_k8s_manifests()
|
|
111
|
+
|
|
112
|
+
if not k8s_files:
|
|
113
|
+
return self.create_not_applicable_result("No Kubernetes manifests detected")
|
|
114
|
+
|
|
115
|
+
if not self.is_tool_available():
|
|
116
|
+
return self.create_skipped_result("kubeconform binary not found in PATH")
|
|
117
|
+
|
|
118
|
+
cmd = [
|
|
119
|
+
str(self.binary_path),
|
|
120
|
+
"-summary",
|
|
121
|
+
"-output", "json",
|
|
122
|
+
"-strict",
|
|
123
|
+
str(target_dir)
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir))
|
|
127
|
+
|
|
128
|
+
findings = FindingCounts()
|
|
129
|
+
items = []
|
|
130
|
+
status = StatusEnum.PASS
|
|
131
|
+
summary = f"Validated {len(k8s_files)} Kubernetes manifest(s) successfully"
|
|
132
|
+
|
|
133
|
+
if stdout.strip():
|
|
134
|
+
try:
|
|
135
|
+
data = json.loads(stdout)
|
|
136
|
+
summary_data = data.get("summary", {})
|
|
137
|
+
invalid_count = summary_data.get("invalid", 0)
|
|
138
|
+
error_count = summary_data.get("errors", 0)
|
|
139
|
+
if invalid_count > 0 or error_count > 0:
|
|
140
|
+
findings.high = invalid_count + error_count
|
|
141
|
+
status = StatusEnum.FAIL
|
|
142
|
+
summary = f"Schema validation failed: {invalid_count} invalid, {error_count} errors"
|
|
143
|
+
|
|
144
|
+
resources = data.get("resources", [])
|
|
145
|
+
for res in resources:
|
|
146
|
+
if res.get("status") in ("Invalid", "Error", "statusError", "statusInvalid"):
|
|
147
|
+
items.append(
|
|
148
|
+
FindingDetail(
|
|
149
|
+
severity="HIGH",
|
|
150
|
+
tool=self.name,
|
|
151
|
+
file=res.get("filename", "k8s.yaml"),
|
|
152
|
+
line="",
|
|
153
|
+
rule="SchemaViolation",
|
|
154
|
+
description=res.get("msg", "Invalid resource definition")
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
except Exception:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
return ToolResult(
|
|
161
|
+
tool_name=self.name,
|
|
162
|
+
category=self.category,
|
|
163
|
+
status=status,
|
|
164
|
+
exit_code=code,
|
|
165
|
+
summary=summary,
|
|
166
|
+
findings=findings,
|
|
167
|
+
duration_seconds=elapsed,
|
|
168
|
+
files_scanned=len(k8s_files),
|
|
169
|
+
items=items
|
|
170
|
+
)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Native Python structural Kubernetes security inspector.
|
|
2
|
+
|
|
3
|
+
Evaluates manifests for pod security standards, privileged containers, root execution,
|
|
4
|
+
host mounts, and resource constraints without external binaries.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import time
|
|
9
|
+
import yaml
|
|
10
|
+
from .base import BaseScanner
|
|
11
|
+
from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
|
|
12
|
+
from ..discovery import TargetDiscovery
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class K8sStructuralAuditScanner(BaseScanner):
|
|
16
|
+
def __init__(self):
|
|
17
|
+
super().__init__(name="K8s Structural Security Inspector", category="Kubernetes Security", binary_name=None)
|
|
18
|
+
|
|
19
|
+
def scan(self, target_dir: Path) -> ToolResult:
|
|
20
|
+
start_time = time.time()
|
|
21
|
+
discovery = TargetDiscovery(target_dir)
|
|
22
|
+
manifests = discovery.discover_k8s_manifests()
|
|
23
|
+
|
|
24
|
+
if not manifests:
|
|
25
|
+
return self.create_not_applicable_result("No Kubernetes manifests detected")
|
|
26
|
+
|
|
27
|
+
findings = FindingCounts()
|
|
28
|
+
items = []
|
|
29
|
+
|
|
30
|
+
for manifest_path in manifests:
|
|
31
|
+
try:
|
|
32
|
+
content = manifest_path.read_text(encoding="utf-8", errors="ignore")
|
|
33
|
+
docs = yaml.safe_load_all(content)
|
|
34
|
+
rel_name = str(manifest_path.relative_to(target_dir)) if str(manifest_path).startswith(str(target_dir)) else manifest_path.name
|
|
35
|
+
for doc in docs:
|
|
36
|
+
if not isinstance(doc, dict):
|
|
37
|
+
continue
|
|
38
|
+
self._audit_document(doc, rel_name, findings, items)
|
|
39
|
+
except Exception as e:
|
|
40
|
+
findings.low += 1
|
|
41
|
+
items.append(
|
|
42
|
+
FindingDetail(
|
|
43
|
+
severity="LOW",
|
|
44
|
+
tool=self.name,
|
|
45
|
+
file=manifest_path.name,
|
|
46
|
+
line="",
|
|
47
|
+
rule="YAMLParseError",
|
|
48
|
+
description=f"Failed to parse YAML: {e}"
|
|
49
|
+
)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
elapsed = round(time.time() - start_time, 2)
|
|
53
|
+
status = StatusEnum.FAIL if findings.has_blocking else StatusEnum.PASS
|
|
54
|
+
|
|
55
|
+
if findings.total == 0:
|
|
56
|
+
summary = f"Audited {len(manifests)} manifest(s): All Pod Security Standards passed!"
|
|
57
|
+
else:
|
|
58
|
+
summary = (
|
|
59
|
+
f"Audited {len(manifests)} manifest(s): {findings.total} risk(s) identified "
|
|
60
|
+
f"({findings.critical} Crit, {findings.high} High, {findings.medium} Med, {findings.low} Low)"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
return ToolResult(
|
|
64
|
+
tool_name=self.name,
|
|
65
|
+
category=self.category,
|
|
66
|
+
status=status,
|
|
67
|
+
exit_code=1 if status == StatusEnum.FAIL else 0,
|
|
68
|
+
summary=summary,
|
|
69
|
+
findings=findings,
|
|
70
|
+
duration_seconds=elapsed,
|
|
71
|
+
items=items
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def _audit_document(self, doc: dict, filename: str, findings: FindingCounts, items: list):
|
|
75
|
+
kind = doc.get("kind", "")
|
|
76
|
+
pod_spec = None
|
|
77
|
+
if kind == "Pod":
|
|
78
|
+
pod_spec = doc.get("spec", {})
|
|
79
|
+
elif kind in ("Deployment", "DaemonSet", "StatefulSet", "Job"):
|
|
80
|
+
pod_spec = doc.get("spec", {}).get("template", {}).get("spec", {})
|
|
81
|
+
elif kind == "CronJob":
|
|
82
|
+
pod_spec = doc.get("spec", {}).get("jobTemplate", {}).get("spec", {}).get("template", {}).get("spec", {})
|
|
83
|
+
|
|
84
|
+
if not pod_spec:
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
# 1. Host Network / PID / IPC checks (High)
|
|
88
|
+
if pod_spec.get("hostNetwork", False):
|
|
89
|
+
findings.high += 1
|
|
90
|
+
items.append(FindingDetail("HIGH", self.name, filename, "", "K8S-HOST-NET", f"[{kind}] Shares host network namespace (hostNetwork: true)"))
|
|
91
|
+
if pod_spec.get("hostPID", False):
|
|
92
|
+
findings.high += 1
|
|
93
|
+
items.append(FindingDetail("HIGH", self.name, filename, "", "K8S-HOST-PID", f"[{kind}] Shares host PID namespace (hostPID: true)"))
|
|
94
|
+
if pod_spec.get("hostIPC", False):
|
|
95
|
+
findings.high += 1
|
|
96
|
+
items.append(FindingDetail("HIGH", self.name, filename, "", "K8S-HOST-IPC", f"[{kind}] Shares host IPC namespace (hostIPC: true)"))
|
|
97
|
+
|
|
98
|
+
# 2. HostPath Volume checks (Critical)
|
|
99
|
+
volumes = pod_spec.get("volumes", [])
|
|
100
|
+
if isinstance(volumes, list):
|
|
101
|
+
for vol in volumes:
|
|
102
|
+
if isinstance(vol, dict) and "hostPath" in vol:
|
|
103
|
+
findings.critical += 1
|
|
104
|
+
items.append(FindingDetail("CRITICAL", self.name, filename, "", "K8S-HOST-PATH", f"[{kind}] Insecure host volume mount ({vol.get('name')})"))
|
|
105
|
+
|
|
106
|
+
# 3. Container SecurityContext & Resource checks
|
|
107
|
+
containers = pod_spec.get("containers", [])
|
|
108
|
+
if isinstance(containers, list):
|
|
109
|
+
for container in containers:
|
|
110
|
+
if not isinstance(container, dict):
|
|
111
|
+
continue
|
|
112
|
+
c_name = container.get("name", "unknown")
|
|
113
|
+
sec_ctx = container.get("securityContext", {}) or {}
|
|
114
|
+
|
|
115
|
+
if sec_ctx.get("privileged", False):
|
|
116
|
+
findings.critical += 1
|
|
117
|
+
items.append(FindingDetail("CRITICAL", self.name, filename, "", "K8S-PRIVILEGED", f"[{kind}/{c_name}] Container runs in privileged mode"))
|
|
118
|
+
|
|
119
|
+
run_as_user = sec_ctx.get("runAsUser")
|
|
120
|
+
run_as_non_root = sec_ctx.get("runAsNonRoot")
|
|
121
|
+
if run_as_user == 0 or run_as_non_root is False:
|
|
122
|
+
findings.high += 1
|
|
123
|
+
items.append(FindingDetail("HIGH", self.name, filename, "", "K8S-RUN-AS-ROOT", f"[{kind}/{c_name}] Explicitly configured to run as root"))
|
|
124
|
+
|
|
125
|
+
if sec_ctx.get("allowPrivilegeEscalation") is True:
|
|
126
|
+
findings.medium += 1
|
|
127
|
+
items.append(FindingDetail("MEDIUM", self.name, filename, "", "K8S-PRIV-ESC", f"[{kind}/{c_name}] allowPrivilegeEscalation is enabled"))
|
|
128
|
+
|
|
129
|
+
resources = container.get("resources", {}) or {}
|
|
130
|
+
if not resources.get("limits"):
|
|
131
|
+
findings.low += 1
|
|
132
|
+
items.append(FindingDetail("LOW", self.name, filename, "", "K8S-NO-LIMITS", f"[{kind}/{c_name}] Missing CPU/Memory resource limits"))
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Kyverno CLI Policy-as-Code scanner for Kubernetes manifests."""
|
|
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 KyvernoScanner(BaseScanner):
|
|
12
|
+
def __init__(self):
|
|
13
|
+
super().__init__(name="Kyverno CLI", category="Policy-as-Code", binary_name="kyverno")
|
|
14
|
+
|
|
15
|
+
def scan(self, target_dir: Path) -> ToolResult:
|
|
16
|
+
discovery = TargetDiscovery(target_dir)
|
|
17
|
+
k8s_files = discovery.discover_k8s_manifests()
|
|
18
|
+
|
|
19
|
+
if not k8s_files:
|
|
20
|
+
return self.create_not_applicable_result("No Kubernetes manifests detected")
|
|
21
|
+
|
|
22
|
+
if not self.is_tool_available():
|
|
23
|
+
return self.create_skipped_result("kyverno binary not found in PATH")
|
|
24
|
+
|
|
25
|
+
# Kyverno apply checks manifests against built-in or directory policies
|
|
26
|
+
# Using kyverno apply or test
|
|
27
|
+
cmd = [
|
|
28
|
+
str(self.binary_path),
|
|
29
|
+
"apply",
|
|
30
|
+
str(target_dir),
|
|
31
|
+
"-r", str(target_dir),
|
|
32
|
+
"-o", "json"
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir))
|
|
36
|
+
|
|
37
|
+
findings = FindingCounts()
|
|
38
|
+
items = []
|
|
39
|
+
status = StatusEnum.PASS
|
|
40
|
+
summary = f"Evaluated {len(k8s_files)} manifest(s) against policy rules"
|
|
41
|
+
|
|
42
|
+
if stdout.strip():
|
|
43
|
+
try:
|
|
44
|
+
# Kyverno json format can output array of results
|
|
45
|
+
data = json.loads(stdout)
|
|
46
|
+
entries = data if isinstance(data, list) else [data]
|
|
47
|
+
for entry in entries:
|
|
48
|
+
res_status = str(entry.get("status") or "").lower()
|
|
49
|
+
if res_status in ("fail", "error"):
|
|
50
|
+
findings.high += 1
|
|
51
|
+
policy_name = entry.get("policy", "KyvernoPolicy")
|
|
52
|
+
rule_name = entry.get("rule", "PolicyRule")
|
|
53
|
+
res_name = entry.get("resource", "resource")
|
|
54
|
+
msg = entry.get("message", "Policy validation failed")
|
|
55
|
+
items.append(
|
|
56
|
+
FindingDetail(
|
|
57
|
+
severity="HIGH",
|
|
58
|
+
tool=self.name,
|
|
59
|
+
file=res_name,
|
|
60
|
+
line="",
|
|
61
|
+
rule=f"{policy_name}/{rule_name}",
|
|
62
|
+
description=msg
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
except Exception:
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
if findings.has_blocking:
|
|
69
|
+
status = StatusEnum.FAIL
|
|
70
|
+
summary = f"Detected {findings.high} Kyverno policy violation(s)"
|
|
71
|
+
|
|
72
|
+
return ToolResult(
|
|
73
|
+
tool_name=self.name,
|
|
74
|
+
category=self.category,
|
|
75
|
+
status=status,
|
|
76
|
+
exit_code=code,
|
|
77
|
+
summary=summary,
|
|
78
|
+
findings=findings,
|
|
79
|
+
duration_seconds=elapsed,
|
|
80
|
+
files_scanned=len(k8s_files),
|
|
81
|
+
items=items
|
|
82
|
+
)
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Mobile Security Framework (MobSF) SAST Scanner for Android, iOS, Flutter, and React Native."""
|
|
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 MobSFScanner(BaseScanner):
|
|
12
|
+
def __init__(self):
|
|
13
|
+
super().__init__(name="MobSF (Mobile SAST)", category="Mobile Security", binary_name="mobsfscan")
|
|
14
|
+
|
|
15
|
+
def _detect_mobile_project(self, target_dir: Path) -> dict:
|
|
16
|
+
"""
|
|
17
|
+
Detects Android, iOS, Flutter, or React Native project footprints.
|
|
18
|
+
Returns a dict with 'is_mobile': bool and 'framework': str.
|
|
19
|
+
"""
|
|
20
|
+
res = {"is_mobile": False, "framework": None, "files": []}
|
|
21
|
+
|
|
22
|
+
# 1. Flutter detection
|
|
23
|
+
pubspec = target_dir / "pubspec.yaml"
|
|
24
|
+
if pubspec.exists():
|
|
25
|
+
try:
|
|
26
|
+
content = pubspec.read_text(encoding="utf-8", errors="ignore")
|
|
27
|
+
if "flutter:" in content:
|
|
28
|
+
res["is_mobile"] = True
|
|
29
|
+
res["framework"] = "Flutter"
|
|
30
|
+
res["files"].append("pubspec.yaml")
|
|
31
|
+
return res
|
|
32
|
+
except Exception:
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
# 2. React Native detection
|
|
36
|
+
pkg_json = target_dir / "package.json"
|
|
37
|
+
if pkg_json.exists():
|
|
38
|
+
try:
|
|
39
|
+
content = pkg_json.read_text(encoding="utf-8", errors="ignore")
|
|
40
|
+
if "react-native" in content:
|
|
41
|
+
res["is_mobile"] = True
|
|
42
|
+
res["framework"] = "React Native"
|
|
43
|
+
res["files"].append("package.json")
|
|
44
|
+
return res
|
|
45
|
+
except Exception:
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
# 3. Android Native / Hybrid detection
|
|
49
|
+
for p in target_dir.rglob("AndroidManifest.xml"):
|
|
50
|
+
if not any(ign in p.parts for ign in (".git", "node_modules", "build", "dist")):
|
|
51
|
+
res["is_mobile"] = True
|
|
52
|
+
res["framework"] = "Android"
|
|
53
|
+
res["files"].append(p.name)
|
|
54
|
+
return res
|
|
55
|
+
|
|
56
|
+
# 4. iOS Native detection
|
|
57
|
+
for p in target_dir.rglob("*.xcodeproj"):
|
|
58
|
+
if not any(ign in p.parts for ign in (".git", "node_modules", "build", "dist")):
|
|
59
|
+
res["is_mobile"] = True
|
|
60
|
+
res["framework"] = "iOS"
|
|
61
|
+
res["files"].append(p.name)
|
|
62
|
+
return res
|
|
63
|
+
|
|
64
|
+
for p in target_dir.rglob("Podfile"):
|
|
65
|
+
if not any(ign in p.parts for ign in (".git", "node_modules")):
|
|
66
|
+
res["is_mobile"] = True
|
|
67
|
+
res["framework"] = "iOS"
|
|
68
|
+
res["files"].append("Podfile")
|
|
69
|
+
return res
|
|
70
|
+
|
|
71
|
+
return res
|
|
72
|
+
|
|
73
|
+
def scan(self, target_dir: Path) -> ToolResult:
|
|
74
|
+
detection = self._detect_mobile_project(target_dir)
|
|
75
|
+
if not detection["is_mobile"]:
|
|
76
|
+
return self.create_not_applicable_result("No mobile application project detected (Android/iOS/Flutter/React Native)")
|
|
77
|
+
|
|
78
|
+
framework = detection["framework"]
|
|
79
|
+
|
|
80
|
+
# mobsfscan is the official CLI tool from MobSF for static code analysis
|
|
81
|
+
if not self.is_tool_available():
|
|
82
|
+
return self.create_skipped_result(f"mobsfscan binary not found in PATH for {framework} SAST")
|
|
83
|
+
|
|
84
|
+
out_json = target_dir / ".mobsf_results.json"
|
|
85
|
+
cmd = [
|
|
86
|
+
str(self.binary_path),
|
|
87
|
+
str(target_dir),
|
|
88
|
+
"--json",
|
|
89
|
+
"-o", str(out_json)
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=600)
|
|
93
|
+
|
|
94
|
+
findings = FindingCounts()
|
|
95
|
+
items = []
|
|
96
|
+
status = StatusEnum.PASS
|
|
97
|
+
summary = f"Completed mobile SAST analysis for {framework}"
|
|
98
|
+
|
|
99
|
+
if out_json.exists():
|
|
100
|
+
try:
|
|
101
|
+
data = json.loads(out_json.read_text(encoding="utf-8"))
|
|
102
|
+
results = data.get("results", {})
|
|
103
|
+
for rule_id, details in results.items():
|
|
104
|
+
meta = details.get("metadata", {})
|
|
105
|
+
raw_sev = str(meta.get("severity", "WARNING")).upper()
|
|
106
|
+
desc = meta.get("description", "Mobile security warning")
|
|
107
|
+
|
|
108
|
+
files_list = details.get("files", [])
|
|
109
|
+
for f in files_list:
|
|
110
|
+
file_path = f.get("file_path", "unknown")
|
|
111
|
+
line_range = f.get("match_lines", [])
|
|
112
|
+
line_str = str(line_range[0]) if line_range else ""
|
|
113
|
+
|
|
114
|
+
sev = "MEDIUM"
|
|
115
|
+
if raw_sev in ("ERROR", "CRITICAL", "HIGH"):
|
|
116
|
+
findings.high += 1
|
|
117
|
+
sev = "HIGH"
|
|
118
|
+
elif raw_sev in ("WARNING", "MEDIUM"):
|
|
119
|
+
findings.medium += 1
|
|
120
|
+
sev = "MEDIUM"
|
|
121
|
+
else:
|
|
122
|
+
findings.low += 1
|
|
123
|
+
sev = "LOW"
|
|
124
|
+
|
|
125
|
+
items.append(
|
|
126
|
+
FindingDetail(
|
|
127
|
+
severity=sev,
|
|
128
|
+
tool=self.name,
|
|
129
|
+
file=file_path,
|
|
130
|
+
line=line_str,
|
|
131
|
+
rule=rule_id,
|
|
132
|
+
description=f"[{framework}] {desc}"
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
137
|
+
finally:
|
|
138
|
+
out_json.unlink(missing_ok=True)
|
|
139
|
+
|
|
140
|
+
if findings.has_blocking:
|
|
141
|
+
status = StatusEnum.FAIL
|
|
142
|
+
summary = f"Detected {findings.high} High severity mobile security issue(s) in {framework}"
|
|
143
|
+
elif findings.total > 0:
|
|
144
|
+
summary = f"Detected {findings.total} mobile security issue(s) in {framework}"
|
|
145
|
+
|
|
146
|
+
return ToolResult(
|
|
147
|
+
tool_name=self.name,
|
|
148
|
+
category=self.category,
|
|
149
|
+
status=status,
|
|
150
|
+
exit_code=code,
|
|
151
|
+
summary=summary,
|
|
152
|
+
findings=findings,
|
|
153
|
+
duration_seconds=elapsed,
|
|
154
|
+
items=items
|
|
155
|
+
)
|