devsecpac 2.0.0__tar.gz → 3.0.1__tar.gz

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.
Files changed (41) hide show
  1. {devsecpac-2.0.0 → devsecpac-3.0.1}/PKG-INFO +15 -1
  2. {devsecpac-2.0.0 → devsecpac-3.0.1}/README.md +14 -0
  3. {devsecpac-2.0.0 → devsecpac-3.0.1}/pyproject.toml +1 -1
  4. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/cli.py +55 -17
  5. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/discovery.py +17 -1
  6. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/installer.py +6 -3
  7. devsecpac-3.0.1/src/devsec_cli/remediation.py +88 -0
  8. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/reporter.py +92 -43
  9. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/runner.py +9 -1
  10. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/codeql.py +4 -2
  11. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/sca.py +6 -1
  12. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/sonar.py +67 -23
  13. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsecpac.egg-info/PKG-INFO +15 -1
  14. devsecpac-2.0.0/src/devsec_cli/remediation.py +0 -63
  15. {devsecpac-2.0.0 → devsecpac-3.0.1}/setup.cfg +0 -0
  16. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/__init__.py +0 -0
  17. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/bypass.py +0 -0
  18. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/ci.py +0 -0
  19. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/contracts.py +0 -0
  20. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/correlator.py +0 -0
  21. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/ingestion.py +0 -0
  22. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/__init__.py +0 -0
  23. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/base.py +0 -0
  24. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/cosign.py +0 -0
  25. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/dast.py +0 -0
  26. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/docker.py +0 -0
  27. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/iac.py +0 -0
  28. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/k8s_audit.py +0 -0
  29. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/kyverno.py +0 -0
  30. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/mobsf.py +0 -0
  31. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/nmap.py +0 -0
  32. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/sbom.py +0 -0
  33. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/schemathesis.py +0 -0
  34. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/secrets.py +0 -0
  35. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsec_cli/scanners/semgrep.py +0 -0
  36. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsecpac.egg-info/SOURCES.txt +0 -0
  37. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsecpac.egg-info/dependency_links.txt +0 -0
  38. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsecpac.egg-info/entry_points.txt +0 -0
  39. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsecpac.egg-info/requires.txt +0 -0
  40. {devsecpac-2.0.0 → devsecpac-3.0.1}/src/devsecpac.egg-info/top_level.txt +0 -0
  41. {devsecpac-2.0.0 → devsecpac-3.0.1}/tests/test_scanners.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: devsecpac
3
- Version: 2.0.0
3
+ Version: 3.0.1
4
4
  Summary: Universal Autonomous DevSecOps Scanner Orchestrator
5
5
  Author-email: Fahad Shaikh <iamfahadshaikh@users.noreply.github.com>
6
6
  License: MIT
@@ -137,6 +137,20 @@ echo "Dockerfile:DL3008" >> .devsecignore
137
137
  echo "CVE-2024-XXXX" >> .devsecignore
138
138
  ```
139
139
 
140
+ #### 9. Native Debian Package & System Manual Pages
141
+ Build and install `devsecpac` natively on Debian/Ubuntu/Kali with system man-page integration:
142
+ ```bash
143
+ # Build Debian package
144
+ ./scripts/build_deb.sh
145
+
146
+ # Install system-wide
147
+ sudo dpkg -i dist/devsecpac_3.0.0_all.deb
148
+
149
+ # View manual page
150
+ man devsecpac
151
+ man devsec
152
+ ```
153
+
140
154
  ---
141
155
 
142
156
  ### Section 2: Running via Docker Image
@@ -110,6 +110,20 @@ echo "Dockerfile:DL3008" >> .devsecignore
110
110
  echo "CVE-2024-XXXX" >> .devsecignore
111
111
  ```
112
112
 
113
+ #### 9. Native Debian Package & System Manual Pages
114
+ Build and install `devsecpac` natively on Debian/Ubuntu/Kali with system man-page integration:
115
+ ```bash
116
+ # Build Debian package
117
+ ./scripts/build_deb.sh
118
+
119
+ # Install system-wide
120
+ sudo dpkg -i dist/devsecpac_3.0.0_all.deb
121
+
122
+ # View manual page
123
+ man devsecpac
124
+ man devsec
125
+ ```
126
+
113
127
  ---
114
128
 
115
129
  ### Section 2: Running via Docker Image
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "devsecpac"
7
- version = "2.0.0"
7
+ version = "3.0.1"
8
8
  description = "Universal Autonomous DevSecOps Scanner Orchestrator"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -3,6 +3,7 @@
3
3
  import argparse
4
4
  import os
5
5
  import sys
6
+ import platform
6
7
  import time
7
8
  from pathlib import Path
8
9
  from typing import List, Optional
@@ -138,6 +139,12 @@ def run_scan(
138
139
  installer = ToolInstaller()
139
140
  installer.install_all()
140
141
 
142
+ # Windows notice: DevSecPac is engineered natively for Linux / Container environments
143
+ if platform.system().lower() == "windows":
144
+ console.print("[bold yellow][!] Windows Environment Detected:[/bold yellow]")
145
+ console.print(" [dim]DevSecPac was built for Linux, containers, and cloud CI/CD pipelines.[/dim]")
146
+ console.print(" [italic cyan]It will run on Windows, but to unlock its full speed and firepower, do yourself a favor and run it on Linux (or Docker).[/italic cyan]\n")
147
+
141
148
  console.print(f"\n[bold green]Initiating DevSecOps Scan on:[/bold green] [bold white]{target_path.resolve()}[/bold white]\n")
142
149
 
143
150
  try:
@@ -279,11 +286,10 @@ def run_scan(
279
286
  total_all_issues = total_crit + total_high + total_med + total_low
280
287
 
281
288
  if total_all_issues > 0:
282
- console.print("[bold cyan]Automated Remediation & Fix Suggestions:[/bold cyan]")
283
- console.print(" Generate a recommended remediation patch to test locally before committing:")
289
+ console.print("[bold cyan]Advisory Remediation & Recommended Fixes:[/bold cyan]")
290
+ console.print(" Generate a recommended remediation patch preview to inspect:")
284
291
  console.print(" [bold white]devsec fix . --patch-output devsec-fix.patch[/bold white]")
285
- console.print(" Inspect and test the patch locally (e.g. [dim]git apply --check devsec-fix.patch[/dim]).")
286
- console.print(" Once verified in your local environment, commit and push the updates.")
292
+ console.print(" [dim]Note: Patches are advisory suggestions. Always inspect diffs before applying.[/dim]")
287
293
  console.print()
288
294
  console.print("[bold yellow]False Positive or Accepted Risk Bypass:[/bold yellow]")
289
295
  console.print(" To permanently suppress a specific finding without altering your global quality gate,")
@@ -313,13 +319,51 @@ def run_scan(
313
319
 
314
320
 
315
321
  def main():
322
+ help_epilog = """
323
+ [bold cyan]QUICK USAGE EXAMPLES:[/bold cyan]
324
+ [green]Autonomous Local Scan:[/green]
325
+ devsecpac scan .
326
+
327
+ [green]Scan Remote GitHub Repo:[/green]
328
+ devsecpac scan -r https://github.com/owner/repo.git
329
+
330
+ [green]Select Specific Security Engines:[/green]
331
+ devsecpac scan . -t gitleaks,semgrep,trivy
332
+
333
+ [green]Export & Push Directly to DefectDojo ASPM:[/green]
334
+ devsecpac scan . --defectdojo-push --defectdojo-url http://localhost:8080 --defectdojo-key <TOKEN> --defectdojo-engagement 1
335
+
336
+ [green]Environment & Auto-Configuration:[/green]
337
+ devsecpac info Show detected status of all 16 security engines
338
+ devsecpac setup Automatically install missing binary security tools
339
+ devsecpac fix . Generate local advisory remediation patch preview
340
+ devsecpac pr-comment Generate GitHub PR Markdown audit comment
341
+
342
+ [bold cyan]SUPPORTED ENGINES (16 Multi-Stage Tools):[/bold cyan]
343
+ * SAST: Semgrep, GitHub CodeQL, SonarQube, MobSF
344
+ * SCA: Aqua Trivy, OWASP Dependency-Check
345
+ * Secrets: Gitleaks, TruffleHog
346
+ * Container: Hadolint
347
+ * IaC / K8s: Checkov, Kubeconform, Kyverno, K8s Python Inspector
348
+ * SBOM/Sign: Syft (CycloneDX), Cosign (Sigstore)
349
+ * DAST/API: OWASP ZAP Baseline, Schemathesis, Nmap
350
+ """
351
+
316
352
  parser = argparse.ArgumentParser(
317
353
  prog="devsecpac",
318
- description="devsecpac: Universal Autonomous DevSecOps Scanner Orchestrator"
354
+ description="devsecpac: Universal Autonomous DevSecOps Scanner Orchestrator with Enterprise ASPM (DefectDojo) & PR Integration",
355
+ epilog=help_epilog,
356
+ formatter_class=argparse.RawDescriptionHelpFormatter
319
357
  )
320
358
  subparsers = parser.add_subparsers(dest="command", help="Command to execute")
321
359
 
322
- # scan command
360
+ # 1. info command
361
+ subparsers.add_parser("info", help="Show environment tool discovery status")
362
+
363
+ # 2. setup command
364
+ subparsers.add_parser("setup", help="Auto-download and configure missing DevSecOps tools into user bin")
365
+
366
+ # 3. scan command
323
367
  scan_parser = subparsers.add_parser("scan", help="Run full security scan against target path or remote Git repo")
324
368
  scan_parser.add_argument("target", nargs="?", default=None, help="Local target path to scan (use '.' for current folder)")
325
369
  scan_parser.add_argument("-r", "--repo", help="Remote Git repository URL (HTTPS or SSH, e.g. https://github.com/org/repo.git)")
@@ -337,18 +381,12 @@ def main():
337
381
  scan_parser.add_argument("--defectdojo-key", default=os.environ.get("DEFECTDOJO_KEY", ""), help="DefectDojo API v2 Key")
338
382
  scan_parser.add_argument("--defectdojo-engagement", type=int, default=int(os.environ.get("DEFECTDOJO_ENGAGEMENT_ID", "1")), help="Target DefectDojo Engagement ID")
339
383
 
340
- # info command
341
- subparsers.add_parser("info", help="Show environment tool discovery status")
342
-
343
- # setup command
344
- subparsers.add_parser("setup", help="Auto-download and configure missing DevSecOps tools into user bin")
345
-
346
- # fix command
347
- fix_parser = subparsers.add_parser("fix", help="Generate recommended remediation patch for detected issues")
348
- fix_parser.add_argument("target", nargs="?", default=".", help="Local target path to fix (default: .)")
349
- fix_parser.add_argument("--patch-output", default="devsec-fix.patch", help="Path for output unified git patch file")
384
+ # 4. fix command
385
+ fix_parser = subparsers.add_parser("fix", help="Generate advisory remediation patch preview for detected issues")
386
+ fix_parser.add_argument("target", nargs="?", default=".", help="Local target path to inspect (default: .)")
387
+ fix_parser.add_argument("--patch-output", default="devsec-fix.patch", help="Path for advisory patch preview file")
350
388
 
351
- # pr-comment command
389
+ # 5. pr-comment command
352
390
  pr_parser = subparsers.add_parser("pr-comment", help="Generate or post interactive GitHub PR comment from scan results")
353
391
  pr_parser.add_argument("--json", default="devsec-report.json", help="Path of existing scan JSON report")
354
392
  pr_parser.add_argument("--output", default="devsec-pr-comment.md", help="Path to write PR markdown comment")
@@ -24,6 +24,17 @@ class TargetDiscovery:
24
24
  "ruby": {"gemfile", "gemfile.lock"}
25
25
  }
26
26
 
27
+ LANG_EXTENSIONS = {
28
+ "nodejs": {".js", ".mjs", ".cjs", ".ts", ".jsx", ".tsx"},
29
+ "python": {".py"},
30
+ "java": {".java"},
31
+ "golang": {".go"},
32
+ "rust": {".rs"},
33
+ "dotnet": {".cs", ".fs"},
34
+ "php": {".php"},
35
+ "ruby": {".rb"}
36
+ }
37
+
27
38
  def __init__(self, target_dir: Path):
28
39
  self.target_dir = target_dir.resolve()
29
40
  self._cached = False
@@ -84,7 +95,7 @@ class TargetDiscovery:
84
95
  except Exception:
85
96
  pass
86
97
 
87
- # Language runtime detection
98
+ # Language runtime detection by project manifest
88
99
  for lang, patterns in self.LANG_PATTERNS.items():
89
100
  if lang == "dotnet":
90
101
  if any(f_lower.endswith(ext) for ext in patterns):
@@ -92,6 +103,11 @@ class TargetDiscovery:
92
103
  elif f_lower in patterns:
93
104
  lang_matches[lang].add(f)
94
105
 
106
+ # Fallback language runtime detection by source file extensions
107
+ for lang, exts in self.LANG_EXTENSIONS.items():
108
+ if any(f_lower.endswith(ext) for ext in exts):
109
+ lang_matches[lang].add(f)
110
+
95
111
  self._scannable_files = sorted(scannable)
96
112
  self._dockerfiles = dockerfiles
97
113
  self._k8s_manifests = k8s
@@ -49,9 +49,12 @@ class ToolInstaller:
49
49
  bin_path = shutil.which(tool_name)
50
50
  if bin_path and Path(bin_path).is_file():
51
51
  return True
52
- # Also check directly in install_dir
53
- local_bin = self.install_dir / (f"{tool_name}.exe" if self.os_type == "windows" else tool_name)
54
- return local_bin.is_file() and os.access(local_bin, os.X_OK)
52
+ # Also check directly in install_dir (handling .exe, .cmd, and bare names)
53
+ for ext in (".exe", ".cmd", ".bat", ""):
54
+ cand = self.install_dir / f"{tool_name}{ext}"
55
+ if cand.is_file():
56
+ return True
57
+ return False
55
58
 
56
59
  def install_all(self):
57
60
  console.print(f"\n[bold green]DevSecOps Autonomous Toolchain Installer[/bold green]")
@@ -0,0 +1,88 @@
1
+ """Autonomous Remediation Engine for DevSecPac v3.0."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Dict
5
+ import re
6
+ import difflib
7
+ from rich.console import Console
8
+ from .contracts import FindingDetail
9
+
10
+ console = Console()
11
+
12
+
13
+ class RemediationEngine:
14
+ """Analyzes findings and generates standard unified git patches for common fixable issues.
15
+
16
+ Supported Auto-Fixes:
17
+ - Dockerfile caching: adds --no-cache-dir to pip install (DL3042)
18
+ - Dockerfile package cleanup: adds -y --no-install-recommends and list cleanup to apt-get (DL3008)
19
+ - Dockerfile numeric UID enforcement: replaces username with numeric UID if defined (DL3066)
20
+ - Standard unified git diff generation compatible with `git apply --check`
21
+ """
22
+
23
+ def __init__(self, target_dir: Path):
24
+ self.target_dir = target_dir
25
+
26
+ def generate_remediation_patch(self, findings: List[FindingDetail], patch_path: Path) -> int:
27
+ """Generates a standard unified git patch for fixable issues using difflib."""
28
+ all_diffs = []
29
+ fixes_applied = 0
30
+
31
+ # Scan for Dockerfile issues
32
+ dockerfiles = list(self.target_dir.glob("**/Dockerfile*"))
33
+ for df in dockerfiles:
34
+ if not df.is_file() or ".git" in df.parts:
35
+ continue
36
+
37
+ orig_text = df.read_text(encoding="utf-8")
38
+ content = orig_text
39
+
40
+ # Fix DL3042: Avoid cache directory with pip install by adding --no-cache-dir
41
+ if re.search(r"pip\s+install\s+(?!.*--no-cache-dir)", content):
42
+ content = re.sub(r"(pip\s+install\s+)", r"\1--no-cache-dir ", content)
43
+ fixes_applied += 1
44
+
45
+ # Fix DL3008: apt-get install without cleanup or without --no-install-recommends
46
+ if "apt-get install" in content:
47
+ if "--no-install-recommends" not in content:
48
+ content = content.replace("apt-get install", "apt-get install -y --no-install-recommends")
49
+ fixes_applied += 1
50
+ if "rm -rf /var/lib/apt/lists/*" not in content and "apt-get update" in content:
51
+ content = content.replace("apt-get update", "apt-get update && rm -rf /var/lib/apt/lists/* # devsec-fix")
52
+ fixes_applied += 1
53
+
54
+ # Fix DL3066: Non-numeric user-id (e.g. USER devsecuser -> USER 10001)
55
+ uid_match = re.search(r"useradd\s+.*?-u\s+(\d+)\s+.*?(\w+)\s*(?:&&|$)", content)
56
+ if uid_match:
57
+ uid, uname = uid_match.group(1), uid_match.group(2)
58
+ user_stmt = f"USER {uname}"
59
+ if user_stmt in content:
60
+ count = content.count(user_stmt)
61
+ content = content.replace(user_stmt, f"USER {uid}")
62
+ fixes_applied += count
63
+
64
+ if content != orig_text:
65
+ rel_path = df.relative_to(self.target_dir).as_posix()
66
+ orig_lines = orig_text.splitlines(keepends=True)
67
+ new_lines = content.splitlines(keepends=True)
68
+ diff = list(difflib.unified_diff(
69
+ orig_lines,
70
+ new_lines,
71
+ fromfile=f"a/{rel_path}",
72
+ tofile=f"b/{rel_path}",
73
+ n=3
74
+ ))
75
+ if diff:
76
+ all_diffs.extend(diff)
77
+
78
+ if all_diffs:
79
+ patch_content = "".join(all_diffs)
80
+ # Write with newline='\n' to ensure clean Unix diff formatting for git apply
81
+ with open(patch_path, "w", encoding="utf-8", newline="\n") as f:
82
+ f.write(patch_content)
83
+ console.print(f"[bold green][OK][/bold green] Generated unified remediation patch: [bold cyan]{patch_path.name}[/bold cyan] ({fixes_applied} auto-fixable issue(s))")
84
+ console.print(f"[dim]Tip: Review the suggested diff and apply with: git apply {patch_path.name}[/dim]")
85
+ else:
86
+ console.print("[dim yellow]No deterministic auto-fixes identified for current findings.[/dim yellow]")
87
+
88
+ return fixes_applied
@@ -14,30 +14,23 @@ class Reporter:
14
14
  self.console = console or Console()
15
15
 
16
16
  def print_terminal_table(self, results: List[ToolResult]):
17
- """Prints a refined, non-wrapping terminal table of active scanner results.
18
- Filters out NOT_APPLICABLE tools with 0 findings to keep outputs clean."""
17
+ """Prints a refined, responsive terminal table of active scanner results.
18
+ Automatically adapts to terminal width to prevent header distortion or ugly truncation."""
19
19
  active_results = [
20
20
  r for r in results
21
21
  if not (r.status == StatusEnum.NOT_APPLICABLE and r.findings.total == 0)
22
22
  ]
23
23
 
24
+ term_width = self.console.width or 120
25
+ is_compact = term_width < 105
26
+
24
27
  table = Table(
25
28
  title="DevSecOps Autonomous Pipeline Scan Results",
26
29
  show_lines=True,
27
30
  header_style="bold cyan",
28
- expand=False
31
+ expand=True
29
32
  )
30
33
 
31
- table.add_column("Scanner / Tool", style="bold white", no_wrap=True)
32
- table.add_column("Category", style="magenta", no_wrap=True)
33
- table.add_column("Status", justify="center", no_wrap=True)
34
- table.add_column("Crit", justify="right", style="bold red", no_wrap=True)
35
- table.add_column("High", justify="right", style="red", no_wrap=True)
36
- table.add_column("Med", justify="right", style="yellow", no_wrap=True)
37
- table.add_column("Low", justify="right", style="blue", no_wrap=True)
38
- table.add_column("Time", justify="right", style="dim", no_wrap=True)
39
- table.add_column("Summary", style="dim white")
40
-
41
34
  status_styles = {
42
35
  StatusEnum.PASS: "[bold green]PASS[/bold green]",
43
36
  StatusEnum.FAIL: "[bold red]FAIL[/bold red]",
@@ -46,19 +39,54 @@ class Reporter:
46
39
  StatusEnum.ERROR: "[bold white on red]ERROR[/bold white on red]",
47
40
  }
48
41
 
49
- for r in active_results:
50
- styled_status = status_styles.get(r.status, r.status.value)
51
- table.add_row(
52
- r.tool_name,
53
- r.category,
54
- styled_status,
55
- str(r.findings.critical),
56
- str(r.findings.high),
57
- str(r.findings.medium),
58
- str(r.findings.low),
59
- f"{r.duration_seconds}s",
60
- r.summary
61
- )
42
+ if is_compact:
43
+ # Compact mode for narrow terminals (e.g. 70-100 cols): combine findings into one column
44
+ table.add_column("Scanner", style="bold white", min_width=14, no_wrap=True)
45
+ table.add_column("Status", justify="center", width=8, no_wrap=True)
46
+ table.add_column("Findings (C/H/M/L)", justify="center", width=18, no_wrap=True)
47
+ table.add_column("Time", justify="right", style="dim", width=7, no_wrap=True)
48
+ table.add_column("Summary", style="dim white", ratio=1)
49
+
50
+ for r in active_results:
51
+ styled_status = status_styles.get(r.status, r.status.value)
52
+ crit_s = f"[bold red]{r.findings.critical}[/bold red]" if r.findings.critical else "0"
53
+ high_s = f"[red]{r.findings.high}[/red]" if r.findings.high else "0"
54
+ med_s = f"[yellow]{r.findings.medium}[/yellow]" if r.findings.medium else "0"
55
+ low_s = f"[blue]{r.findings.low}[/blue]" if r.findings.low else "0"
56
+ findings_str = f"{crit_s}/{high_s}/{med_s}/{low_s}"
57
+
58
+ table.add_row(
59
+ r.tool_name,
60
+ styled_status,
61
+ findings_str,
62
+ f"{r.duration_seconds}s",
63
+ r.summary
64
+ )
65
+ else:
66
+ # Full layout for normal / wide terminals (>= 105 cols)
67
+ table.add_column("Scanner / Tool", style="bold white", min_width=16, no_wrap=True)
68
+ table.add_column("Category", style="magenta", min_width=14, no_wrap=True)
69
+ table.add_column("Status", justify="center", width=8, no_wrap=True)
70
+ table.add_column("Crit", justify="right", style="bold red", width=5, no_wrap=True)
71
+ table.add_column("High", justify="right", style="red", width=5, no_wrap=True)
72
+ table.add_column("Med", justify="right", style="yellow", width=5, no_wrap=True)
73
+ table.add_column("Low", justify="right", style="blue", width=5, no_wrap=True)
74
+ table.add_column("Time", justify="right", style="dim", width=8, no_wrap=True)
75
+ table.add_column("Summary", style="dim white", ratio=1)
76
+
77
+ for r in active_results:
78
+ styled_status = status_styles.get(r.status, r.status.value)
79
+ table.add_row(
80
+ r.tool_name,
81
+ r.category,
82
+ styled_status,
83
+ str(r.findings.critical),
84
+ str(r.findings.high),
85
+ str(r.findings.medium),
86
+ str(r.findings.low),
87
+ f"{r.duration_seconds}s",
88
+ r.summary
89
+ )
62
90
 
63
91
  self.console.print()
64
92
  self.console.print(table)
@@ -92,19 +120,16 @@ class Reporter:
92
120
  f"[blue]{total_low} Low[/blue]{dedup_info}"
93
121
  )
94
122
 
123
+ term_width = self.console.width or 120
124
+ is_compact = term_width < 105
125
+
95
126
  table = Table(
96
127
  title=summary_title,
97
128
  show_lines=True,
98
129
  header_style="bold yellow",
99
- expand=False
130
+ expand=True if is_compact else False
100
131
  )
101
132
 
102
- table.add_column("Severity", justify="center", no_wrap=True)
103
- table.add_column("Scanner", style="cyan", no_wrap=True)
104
- table.add_column("Location (File:Line)", style="bold white")
105
- table.add_column("Rule / CVE", style="bold magenta", no_wrap=True)
106
- table.add_column("Description", style="dim white")
107
-
108
133
  sev_styles = {
109
134
  "CRITICAL": "[bold white on red] CRIT [/bold white on red]",
110
135
  "HIGH": "[bold red] HIGH [/bold red]",
@@ -113,16 +138,40 @@ class Reporter:
113
138
  "INFO": "[dim] INFO [/dim]",
114
139
  }
115
140
 
116
- # Show in priority order: CRITICAL -> HIGH -> MEDIUM -> LOW
117
- for item in (crit_items + high_items + med_items + low_items):
118
- loc = f"{item.file}:{item.line}" if item.line else item.file
119
- table.add_row(
120
- sev_styles.get(item.severity.upper(), item.severity),
121
- item.tool,
122
- loc,
123
- item.rule or "-",
124
- item.description
125
- )
141
+ if is_compact:
142
+ # Compact view for narrow / default 80-col terminals (e.g. Docker non-TTY or CI runners)
143
+ table.add_column("Sev", justify="center", width=7, no_wrap=True)
144
+ table.add_column("Scanner", style="cyan", width=12, no_wrap=True)
145
+ table.add_column("Location & Rule", style="bold white", ratio=2)
146
+ table.add_column("Description", style="dim white", ratio=3)
147
+
148
+ for item in (crit_items + high_items + med_items + low_items):
149
+ loc = f"{item.file}:{item.line}" if item.line else item.file
150
+ loc_rule = f"{loc}\n[dim magenta]{item.rule or '-'}[/dim magenta]"
151
+ table.add_row(
152
+ sev_styles.get(item.severity.upper(), item.severity),
153
+ item.tool,
154
+ loc_rule,
155
+ item.description
156
+ )
157
+ else:
158
+ # Full view for normal / wide terminals
159
+ table.add_column("Severity", justify="center", no_wrap=True)
160
+ table.add_column("Scanner", style="cyan", no_wrap=True)
161
+ table.add_column("Location (File:Line)", style="bold white")
162
+ table.add_column("Rule / CVE", style="bold magenta", no_wrap=True)
163
+ table.add_column("Description", style="dim white")
164
+
165
+ # Show in priority order: CRITICAL -> HIGH -> MEDIUM -> LOW
166
+ for item in (crit_items + high_items + med_items + low_items):
167
+ loc = f"{item.file}:{item.line}" if item.line else item.file
168
+ table.add_row(
169
+ sev_styles.get(item.severity.upper(), item.severity),
170
+ item.tool,
171
+ loc,
172
+ item.rule or "-",
173
+ item.description
174
+ )
126
175
 
127
176
  self.console.print(table)
128
177
  self.console.print()
@@ -60,9 +60,17 @@ class ProcessRunner:
60
60
  )
61
61
  elapsed = round(time.time() - start, 2)
62
62
  return process.returncode, process.stdout, process.stderr, elapsed
63
- except subprocess.TimeoutExpired:
63
+ except subprocess.TimeoutExpired as exc:
64
64
  elapsed = round(time.time() - start, 2)
65
+ # On Windows, child processes created by batch/cmd files don't terminate automatically on timeout
66
+ try:
67
+ if hasattr(exc, 'stdout') and exc.stdout:
68
+ pass
69
+ except Exception:
70
+ pass
65
71
  return -1, "", f"Command timed out after {timeout} seconds", elapsed
72
+ except KeyboardInterrupt:
73
+ raise
66
74
  except Exception as e:
67
75
  elapsed = round(time.time() - start, 2)
68
76
  return -1, "", str(e), elapsed
@@ -2,8 +2,10 @@
2
2
 
3
3
  from pathlib import Path
4
4
  import json
5
+ import os
5
6
  import shutil
6
7
  import tempfile
8
+ import time
7
9
  from .base import BaseScanner
8
10
  from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
9
11
  from ..runner import ProcessRunner
@@ -45,8 +47,8 @@ class CodeQLScanner(BaseScanner):
45
47
  status = StatusEnum.PASS
46
48
  summary = f"CodeQL SAST analysis completed for {codeql_lang}"
47
49
 
48
- sarif_out = target_dir / ".codeql_results.sarif"
49
- db_dir = target_dir / ".codeql_db"
50
+ sarif_out = Path(tempfile.gettempdir()) / f".codeql_results_{os.getpid()}_{int(time.time())}.sarif"
51
+ db_dir = Path(tempfile.gettempdir()) / f".codeql_db_{os.getpid()}_{int(time.time())}"
50
52
 
51
53
  try:
52
54
  # 1. Create database
@@ -118,8 +118,13 @@ class DependencyCheckScanner(BaseScanner):
118
118
  # Without an NVD API key, NIST rate-limits download requests heavily
119
119
  # Pass noupdate if local database cache exists to avoid 10-minute freezes
120
120
  data_dir = Path.home() / ".local" / "opt" / "dependency-check" / "data"
121
- if (data_dir / "odc.mv.db").exists():
121
+ win_data_dir = Path(os.environ.get("USERPROFILE", ".")) / ".local" / "opt" / "dependency-check" / "data"
122
+ if (data_dir / "odc.mv.db").exists() or (win_data_dir / "odc.mv.db").exists():
122
123
  cmd.append("--noupdate")
124
+ elif not nvd_api_key:
125
+ # First run on host without NVD key will freeze for 15+ minutes due to NIST rate-limiting
126
+ # Skip gracefully if Aqua Trivy is already active (Trivy provides instant SCA without NVD rate-limits)
127
+ return self.create_skipped_result("Skipped slow NVD database initialization (Trivy active; export NVD_API_KEY to enable)")
123
128
 
124
129
  code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=120)
125
130
 
@@ -2,10 +2,13 @@
2
2
 
3
3
  from pathlib import Path
4
4
  import os
5
+ import sys
6
+ import platform
5
7
  import json
6
8
  import time
7
9
  import requests
8
10
  import base64
11
+ from typing import Tuple, Optional
9
12
  from rich.prompt import Confirm
10
13
  from rich.console import Console
11
14
  from .base import BaseScanner
@@ -148,35 +151,63 @@ class SonarQubeScanner(BaseScanner):
148
151
  except Exception:
149
152
  return ""
150
153
 
151
- def _prompt_start_sonarqube(self, sonar_host: str) -> str:
152
- """Prompts user if they want to start a local SonarQube container automatically."""
153
- import sys
154
- if not sys.stdin.isatty():
155
- return ""
156
-
154
+ def _ensure_docker_available(self) -> Tuple[bool, str]:
155
+ """Checks if Docker is available. On Linux, attempts auto-install if missing. On Windows, prints installation guide."""
157
156
  docker_bin = ProcessRunner.find_binary("docker")
158
157
  if not docker_bin:
159
- return ""
158
+ if platform.system().lower() == "windows":
159
+ console.print("\n[bold yellow][!] Docker is required for autonomous SonarQube launch on Windows.[/bold yellow]")
160
+ console.print(" Please install Docker Desktop: [bold cyan]https://www.docker.com/products/docker-desktop/[/bold cyan]\n")
161
+ return False, ""
162
+ else:
163
+ # On Linux, autonomously install docker.io
164
+ console.print("\n[bold blue][..] Docker not detected. Attempting autonomous Docker installation via apt...[/bold blue]")
165
+ code, _, _, _ = ProcessRunner.run_command(["sudo", "apt-get", "update", "-y"])
166
+ code, _, _, _ = ProcessRunner.run_command(["sudo", "apt-get", "install", "-y", "--no-install-recommends", "docker.io"])
167
+ ProcessRunner.run_command(["sudo", "systemctl", "start", "docker"])
168
+ docker_bin = ProcessRunner.find_binary("docker")
169
+ if not docker_bin:
170
+ return False, ""
171
+
172
+ # Check if docker daemon is running
173
+ code, _, _, _ = ProcessRunner.run_command([docker_bin, "info"], timeout=5)
174
+ if code != 0:
175
+ if platform.system().lower() == "windows":
176
+ console.print("\n[bold yellow][!] Docker Desktop is installed but the daemon is not running.[/bold yellow]")
177
+ console.print(" Please start Docker Desktop to enable SonarQube autonomous spin-up.\n")
178
+ return False, ""
179
+ else:
180
+ ProcessRunner.run_command(["sudo", "systemctl", "start", "docker"])
181
+ code, _, _, _ = ProcessRunner.run_command([docker_bin, "info"], timeout=5)
182
+ if code != 0:
183
+ return False, ""
160
184
 
161
- console.print("\n[bold yellow]SonarQube server is not reachable.[/bold yellow]")
162
- if not Confirm.ask("Would you like devsec to launch a SonarQube container via Docker?"):
185
+ return True, docker_bin
186
+
187
+ def _auto_start_sonarqube(self, sonar_host: str) -> str:
188
+ """Autonomously launches or resumes SonarQube container via Docker without interactive prompts."""
189
+ has_docker, docker_bin = self._ensure_docker_available()
190
+ if not has_docker:
163
191
  return ""
164
192
 
165
- # Check if container named 'sonarqube' already exists
193
+ console.print("\n[bold cyan][*] Autonomously bootstrapping local SonarQube server via Docker...[/bold cyan]")
194
+
195
+ # Check if container named 'sonarqube' exists
166
196
  code, stdout, _, _ = ProcessRunner.run_command([docker_bin, "ps", "-a", "--filter", "name=sonarqube", "--format", "{{.Names}}"])
167
197
  if "sonarqube" in stdout:
168
- console.print(" * Starting existing [bold cyan]sonarqube[/bold cyan] container...")
198
+ console.print(" * Resuming existing [bold green]sonarqube[/bold green] container...")
169
199
  ProcessRunner.run_command([docker_bin, "start", "sonarqube"])
170
200
  else:
171
- console.print(" * Pulling and starting [bold cyan]sonarqube:lts-community[/bold cyan] on port 9000...")
201
+ console.print(" * Pulling & launching [bold green]sonarqube:lts-community[/bold green] on port 9000...")
172
202
  ProcessRunner.run_command([
173
203
  docker_bin, "run", "-d", "--name", "sonarqube",
204
+ "--restart", "unless-stopped",
174
205
  "-p", "9000:9000", "sonarqube:lts-community"
175
206
  ])
176
207
 
177
- # Wait for SonarQube to be UP
178
- with console.status("[bold blue]Waiting for SonarQube server to become ready (this may take up to 45s)...[/bold blue]"):
179
- for _ in range(60):
208
+ # Wait for SonarQube to become ready
209
+ with console.status("[bold blue]Waiting for SonarQube server readiness (Compute Engine initializing)...[/bold blue]"):
210
+ for _ in range(45):
180
211
  if self._check_server_reachable(sonar_host):
181
212
  break
182
213
  time.sleep(2)
@@ -185,7 +216,7 @@ class SonarQubeScanner(BaseScanner):
185
216
  token = self._auto_generate_token(sonar_host)
186
217
  if token:
187
218
  self._save_cached_token(token)
188
- console.print(f" * [bold green][OK][/bold green] Generated analysis token: [dim]{token[:12]}...[/dim]")
219
+ console.print(f" * [bold green][OK][/bold green] Autonomous analysis token generated: [dim]{token[:12]}...[/dim]")
189
220
  return token
190
221
 
191
222
  def scan(self, target_dir: Path) -> ToolResult:
@@ -198,16 +229,29 @@ class SonarQubeScanner(BaseScanner):
198
229
  if not self.is_tool_available():
199
230
  return self.create_skipped_result("sonar-scanner binary not found in PATH")
200
231
 
201
- sonar_host = os.environ.get("SONAR_HOST_URL", "http://localhost:9000")
232
+ sonar_host = os.environ.get("SONAR_HOST_URL", "")
233
+ if not sonar_host:
234
+ # Check if default localhost:9000 is reachable, otherwise probe container bridge host.docker.internal:9000
235
+ if self._check_server_reachable("http://localhost:9000"):
236
+ sonar_host = "http://localhost:9000"
237
+ elif self._check_server_reachable("http://host.docker.internal:9000"):
238
+ sonar_host = "http://host.docker.internal:9000"
239
+ else:
240
+ sonar_host = "http://localhost:9000"
241
+
202
242
  sonar_token = self._resolve_token()
203
243
 
204
- # If not reachable and no token, prompt user to start it or auto-connect
244
+ # If not reachable and no token, autonomously spin up SonarQube via Docker
205
245
  if not self._check_server_reachable(sonar_host):
206
- new_token = self._prompt_start_sonarqube(sonar_host)
207
- if new_token:
208
- sonar_token = new_token
209
- elif not self._check_server_reachable(sonar_host):
210
- return self.create_skipped_result("SonarQube server unreachable (export SONAR_HOST_URL & SONAR_TOKEN)")
246
+ # Check host.docker.internal in case running inside container
247
+ if sonar_host == "http://localhost:9000" and self._check_server_reachable("http://host.docker.internal:9000"):
248
+ sonar_host = "http://host.docker.internal:9000"
249
+ else:
250
+ new_token = self._auto_start_sonarqube(sonar_host)
251
+ if new_token:
252
+ sonar_token = new_token
253
+ elif not self._check_server_reachable(sonar_host):
254
+ return self.create_skipped_result("SonarQube server unreachable (export SONAR_HOST_URL & SONAR_TOKEN)")
211
255
 
212
256
  # When new container was created, old conf properties has old token that fails
213
257
  # Verify token by testing /api/authentication/validate
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: devsecpac
3
- Version: 2.0.0
3
+ Version: 3.0.1
4
4
  Summary: Universal Autonomous DevSecOps Scanner Orchestrator
5
5
  Author-email: Fahad Shaikh <iamfahadshaikh@users.noreply.github.com>
6
6
  License: MIT
@@ -137,6 +137,20 @@ echo "Dockerfile:DL3008" >> .devsecignore
137
137
  echo "CVE-2024-XXXX" >> .devsecignore
138
138
  ```
139
139
 
140
+ #### 9. Native Debian Package & System Manual Pages
141
+ Build and install `devsecpac` natively on Debian/Ubuntu/Kali with system man-page integration:
142
+ ```bash
143
+ # Build Debian package
144
+ ./scripts/build_deb.sh
145
+
146
+ # Install system-wide
147
+ sudo dpkg -i dist/devsecpac_3.0.0_all.deb
148
+
149
+ # View manual page
150
+ man devsecpac
151
+ man devsec
152
+ ```
153
+
140
154
  ---
141
155
 
142
156
  ### Section 2: Running via Docker Image
@@ -1,63 +0,0 @@
1
- """Autonomous Remediation Engine for DevSecPac v2.0."""
2
-
3
- from pathlib import Path
4
- from typing import List, Dict
5
- import re
6
- from rich.console import Console
7
- from .contracts import FindingDetail
8
-
9
- console = Console()
10
-
11
-
12
- class RemediationEngine:
13
- """Analyzes findings and generates automatic patches or fixes for common vulnerabilities.
14
-
15
- Supported Auto-Fixes:
16
- - Pinning base Dockerfile images or package-install commands (DL3008, DL3042)
17
- - Package lockfile remediation recommendations
18
- - Patch file generation (devsec-fix.patch)
19
- """
20
-
21
- def __init__(self, target_dir: Path):
22
- self.target_dir = target_dir
23
-
24
- def generate_remediation_patch(self, findings: List[FindingDetail], patch_path: Path) -> int:
25
- """Generates a standard unified git patch for fixable issues."""
26
- diff_lines = []
27
- fixes_applied = 0
28
-
29
- # Scan for Dockerfile issues (e.g. Hadolint DL3008, DL3042)
30
- dockerfiles = list(self.target_dir.glob("**/Dockerfile*"))
31
- for df in dockerfiles:
32
- if not df.is_file() or ".git" in df.parts:
33
- continue
34
-
35
- content = df.read_text(encoding="utf-8")
36
- original_content = content
37
-
38
- # Fix DL3042: Avoid cache directory with pip install by adding --no-cache-dir
39
- if re.search(r"pip\s+install\s+(?!.*--no-cache-dir)", content):
40
- content = re.sub(r"(pip\s+install\s+)", r"\1--no-cache-dir ", content)
41
- fixes_applied += 1
42
-
43
- # Fix DL3008: apt-get install without cleanup
44
- if "apt-get install" in content and "rm -rf /var/lib/apt/lists/*" not in content:
45
- content = content.replace("apt-get install", "apt-get install -y --no-install-recommends")
46
- fixes_applied += 1
47
-
48
- if content != original_content:
49
- rel_path = df.relative_to(self.target_dir)
50
- diff_lines.append(f"--- a/{rel_path}")
51
- diff_lines.append(f"+++ b/{rel_path}")
52
- diff_lines.append("@@ -1 +1 @@")
53
- diff_lines.append(f"-{original_content.splitlines()[0] if original_content.splitlines() else ''}")
54
- diff_lines.append(f"+{content.splitlines()[0] if content.splitlines() else ''}")
55
-
56
- if diff_lines:
57
- patch_path.write_text("\n".join(diff_lines) + "\n", encoding="utf-8")
58
- console.print(f"[bold green][OK][/bold green] Generated unified remediation patch: [bold cyan]{patch_path.name}[/bold cyan] ({fixes_applied} auto-fixable issue(s))")
59
- console.print(f"[dim]Tip: Review the suggested diff and apply with: git apply {patch_path.name}[/dim]")
60
- else:
61
- console.print("[dim yellow]No deterministic auto-fixes identified for current findings.[/dim yellow]")
62
-
63
- return fixes_applied
File without changes