stackparity 1.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.
Files changed (212) hide show
  1. stackparity/__init__.py +17 -0
  2. stackparity/_engine/agents/investigator.py +294 -0
  3. stackparity/_engine/agents/memory_agent.py +37 -0
  4. stackparity/_engine/agents/pipeline_agent.py +152 -0
  5. stackparity/_engine/agents/remediation_agent.py +248 -0
  6. stackparity/_engine/agents/runtime.py +177 -0
  7. stackparity/_engine/agents/specialists.py +709 -0
  8. stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
  9. stackparity/_engine/cli/__init__.py +2 -0
  10. stackparity/_engine/cli/main.py +1252 -0
  11. stackparity/_engine/cli/remediate.py +461 -0
  12. stackparity/_engine/cli/term.py +44 -0
  13. stackparity/_engine/config/__init__.py +0 -0
  14. stackparity/_engine/config/constants.py +88 -0
  15. stackparity/_engine/config/loader.py +155 -0
  16. stackparity/_engine/config/settings.py +108 -0
  17. stackparity/_engine/containers/__init__.py +12 -0
  18. stackparity/_engine/containers/discovery.py +143 -0
  19. stackparity/_engine/containers/models.py +72 -0
  20. stackparity/_engine/containers/trivy_image_scanner.py +165 -0
  21. stackparity/_engine/core/__init__.py +0 -0
  22. stackparity/_engine/core/capabilities.py +107 -0
  23. stackparity/_engine/core/finding_schema.py +305 -0
  24. stackparity/_engine/core/git_manager.py +206 -0
  25. stackparity/_engine/core/http.py +64 -0
  26. stackparity/_engine/core/models.py +109 -0
  27. stackparity/_engine/core/netpolicy.py +242 -0
  28. stackparity/_engine/core/plugins.py +43 -0
  29. stackparity/_engine/core/repository_inspector.py +243 -0
  30. stackparity/_engine/core/safe_env.py +48 -0
  31. stackparity/_engine/core/scan_orchestrator.py +289 -0
  32. stackparity/_engine/core/scan_state.py +58 -0
  33. stackparity/_engine/core/url_validator.py +135 -0
  34. stackparity/_engine/ecosystems/__init__.py +1 -0
  35. stackparity/_engine/ecosystems/registry.py +138 -0
  36. stackparity/_engine/evidence/__init__.py +1 -0
  37. stackparity/_engine/evidence/store.py +65 -0
  38. stackparity/_engine/explainability/__init__.py +0 -0
  39. stackparity/_engine/explainability/evidence_formatter.py +30 -0
  40. stackparity/_engine/explainability/explanation_engine.py +132 -0
  41. stackparity/_engine/explainability/explanation_validator.py +54 -0
  42. stackparity/_engine/explainability/prompt_templates.py +18 -0
  43. stackparity/_engine/graph/__init__.py +0 -0
  44. stackparity/_engine/graph/dependency_tracer.py +86 -0
  45. stackparity/_engine/graph/graph_builder.py +165 -0
  46. stackparity/_engine/graph/graph_diff.py +57 -0
  47. stackparity/_engine/graph/graph_exporter.py +194 -0
  48. stackparity/_engine/graph/graph_validator.py +46 -0
  49. stackparity/_engine/graph/impact_analyzer.py +23 -0
  50. stackparity/_engine/graph/tree_view.py +185 -0
  51. stackparity/_engine/intel/__init__.py +0 -0
  52. stackparity/_engine/intel/epss.py +53 -0
  53. stackparity/_engine/llm/__init__.py +1 -0
  54. stackparity/_engine/llm/client.py +138 -0
  55. stackparity/_engine/monitor/__init__.py +0 -0
  56. stackparity/_engine/monitor/watch.py +171 -0
  57. stackparity/_engine/non_cve/__init__.py +7 -0
  58. stackparity/_engine/non_cve/base.py +62 -0
  59. stackparity/_engine/non_cve/iac.py +144 -0
  60. stackparity/_engine/non_cve/sast.py +272 -0
  61. stackparity/_engine/non_cve/supply_chain.py +147 -0
  62. stackparity/_engine/orchestration/__init__.py +1 -0
  63. stackparity/_engine/orchestration/pipeline.py +279 -0
  64. stackparity/_engine/orchestration/supervisor.py +167 -0
  65. stackparity/_engine/pipeline_analysis/__init__.py +0 -0
  66. stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
  67. stackparity/_engine/pipeline_analysis/ci.py +189 -0
  68. stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
  69. stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
  70. stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
  71. stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
  72. stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
  73. stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
  74. stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
  75. stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
  76. stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
  77. stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
  78. stackparity/_engine/pipeline_analysis/eol.py +62 -0
  79. stackparity/_engine/pipeline_analysis/models.py +37 -0
  80. stackparity/_engine/policy/__init__.py +0 -0
  81. stackparity/_engine/policy/engine.py +216 -0
  82. stackparity/_engine/policy/resources/default.yaml +56 -0
  83. stackparity/_engine/policy/resources/strict.yaml +35 -0
  84. stackparity/_engine/reachability/__init__.py +0 -0
  85. stackparity/_engine/reachability/app_reachability.py +186 -0
  86. stackparity/_engine/reachability/scanners.py +215 -0
  87. stackparity/_engine/remediation/__init__.py +0 -0
  88. stackparity/_engine/remediation/adapters.py +198 -0
  89. stackparity/_engine/remediation/apply_local.py +309 -0
  90. stackparity/_engine/remediation/code_fixes.py +383 -0
  91. stackparity/_engine/remediation/compat.py +156 -0
  92. stackparity/_engine/remediation/container_plan.py +127 -0
  93. stackparity/_engine/remediation/delivery.py +31 -0
  94. stackparity/_engine/remediation/export.py +44 -0
  95. stackparity/_engine/remediation/lifecycle.py +623 -0
  96. stackparity/_engine/remediation/local_trial.py +358 -0
  97. stackparity/_engine/remediation/patchers.py +215 -0
  98. stackparity/_engine/remediation/planner.py +285 -0
  99. stackparity/_engine/remediation/pr_template_engine.py +234 -0
  100. stackparity/_engine/remediation/reachability_impact.py +147 -0
  101. stackparity/_engine/remediation/versions.py +92 -0
  102. stackparity/_engine/remediation/whatif.py +64 -0
  103. stackparity/_engine/remediation/worktree_pr.py +434 -0
  104. stackparity/_engine/reporting/__init__.py +0 -0
  105. stackparity/_engine/reporting/counts.py +63 -0
  106. stackparity/_engine/reporting/fix_pdf.py +343 -0
  107. stackparity/_engine/reporting/fix_report.py +135 -0
  108. stackparity/_engine/reporting/json_exporter.py +61 -0
  109. stackparity/_engine/reporting/report_generator.py +200 -0
  110. stackparity/_engine/reporting/sarif.py +71 -0
  111. stackparity/_engine/reporting/vex.py +57 -0
  112. stackparity/_engine/reporting/view.py +166 -0
  113. stackparity/_engine/risk_analysis/__init__.py +0 -0
  114. stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
  115. stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
  116. stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
  117. stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
  118. stackparity/_engine/risk_analysis/function_impact.py +184 -0
  119. stackparity/_engine/risk_analysis/production_context.py +252 -0
  120. stackparity/_engine/risk_analysis/risk_rules.py +81 -0
  121. stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
  122. stackparity/_engine/sandbox/__init__.py +0 -0
  123. stackparity/_engine/sandbox/runner.py +142 -0
  124. stackparity/_engine/sbom/__init__.py +0 -0
  125. stackparity/_engine/sbom/adapters/__init__.py +19 -0
  126. stackparity/_engine/sbom/adapters/builtin.py +29 -0
  127. stackparity/_engine/sbom/adapters/syft.py +26 -0
  128. stackparity/_engine/sbom/adapters/trivy.py +76 -0
  129. stackparity/_engine/sbom/builtin_generator.py +227 -0
  130. stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
  131. stackparity/_engine/sbom/exporters.py +153 -0
  132. stackparity/_engine/sbom/fusion/__init__.py +5 -0
  133. stackparity/_engine/sbom/fusion/engine.py +315 -0
  134. stackparity/_engine/sbom/fusion/hashes.py +47 -0
  135. stackparity/_engine/sbom/fusion/ledger.py +96 -0
  136. stackparity/_engine/sbom/fusion/registries.py +271 -0
  137. stackparity/_engine/sbom/fusion/resolver.py +143 -0
  138. stackparity/_engine/sbom/fusion/writer.py +114 -0
  139. stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
  140. stackparity/_engine/sbom/merge.py +71 -0
  141. stackparity/_engine/sbom/package_extractors/common.py +104 -0
  142. stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
  143. stackparity/_engine/sbom/package_extractors/npm.py +206 -0
  144. stackparity/_engine/sbom/package_extractors/others.py +267 -0
  145. stackparity/_engine/sbom/package_extractors/python.py +143 -0
  146. stackparity/_engine/sbom/quality_analyzer.py +191 -0
  147. stackparity/_engine/sbom/scanner_engine.py +98 -0
  148. stackparity/_engine/sbom/syft_runner.py +100 -0
  149. stackparity/_engine/sbom/tool_locator.py +69 -0
  150. stackparity/_engine/sbom/trivy_runner.py +82 -0
  151. stackparity/_engine/storage/__init__.py +0 -0
  152. stackparity/_engine/storage/cache.py +56 -0
  153. stackparity/_engine/storage/database.py +295 -0
  154. stackparity/_engine/storage/memory.py +146 -0
  155. stackparity/_engine/suspicious_changes/__init__.py +12 -0
  156. stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
  157. stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
  158. stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
  159. stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
  160. stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
  161. stackparity/_engine/suspicious_changes/package_risk.py +78 -0
  162. stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
  163. stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
  164. stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
  165. stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
  166. stackparity/_engine/tools/__init__.py +1 -0
  167. stackparity/_engine/tools/builtin.py +93 -0
  168. stackparity/_engine/tools/registry.py +66 -0
  169. stackparity/_engine/ui/__init__.py +0 -0
  170. stackparity/_engine/ui/components/__init__.py +0 -0
  171. stackparity/_engine/ui/components/common.py +238 -0
  172. stackparity/_engine/ui/components/live_progress.py +157 -0
  173. stackparity/_engine/ui/components/memory_panel.py +82 -0
  174. stackparity/_engine/ui/pages/__init__.py +0 -0
  175. stackparity/_engine/ui/pages/agents_page.py +76 -0
  176. stackparity/_engine/ui/pages/architecture_page.py +44 -0
  177. stackparity/_engine/ui/pages/fixes_page.py +98 -0
  178. stackparity/_engine/ui/pages/graph_page.py +203 -0
  179. stackparity/_engine/ui/pages/health_page.py +117 -0
  180. stackparity/_engine/ui/pages/monitor_page.py +67 -0
  181. stackparity/_engine/ui/pages/pipeline_page.py +219 -0
  182. stackparity/_engine/ui/pages/remediation_page.py +409 -0
  183. stackparity/_engine/ui/pages/reports_page.py +54 -0
  184. stackparity/_engine/ui/pages/sbom_page.py +210 -0
  185. stackparity/_engine/ui/pages/scan_page.py +131 -0
  186. stackparity/_engine/ui/pages/suspicious_page.py +551 -0
  187. stackparity/_engine/ui/pages/vulns_page.py +201 -0
  188. stackparity/_engine/ui/state.py +116 -0
  189. stackparity/_engine/ui/theme.py +201 -0
  190. stackparity/_engine/ui/visualizations/__init__.py +0 -0
  191. stackparity/_engine/ui/visualizations/graphs.py +373 -0
  192. stackparity/_engine/vulnerability/__init__.py +0 -0
  193. stackparity/_engine/vulnerability/cvss.py +58 -0
  194. stackparity/_engine/vulnerability/kev_client.py +47 -0
  195. stackparity/_engine/vulnerability/nvd_client.py +74 -0
  196. stackparity/_engine/vulnerability/osv_client.py +139 -0
  197. stackparity/_engine/vulnerability/remediation_engine.py +50 -0
  198. stackparity/_engine/vulnerability/verification.py +94 -0
  199. stackparity/_engine/vulnerability/version_matcher.py +299 -0
  200. stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
  201. stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
  202. stackparity/cli.py +30 -0
  203. stackparity/dashboard_app.py +95 -0
  204. stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
  205. stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
  206. stackparity/web_dist/index.html +13 -0
  207. stackparity/web_server.py +533 -0
  208. stackparity-1.0.0.dist-info/METADATA +204 -0
  209. stackparity-1.0.0.dist-info/RECORD +212 -0
  210. stackparity-1.0.0.dist-info/WHEEL +4 -0
  211. stackparity-1.0.0.dist-info/entry_points.txt +2 -0
  212. stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,144 @@
1
+ """Layer 3 Non-CVE Scanner: Infrastructure-as-Code (Kubernetes, Terraform, Helm) security rules."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import yaml
9
+
10
+ from core.repository_inspector import safe_read_text, walk_repo
11
+ from non_cve.base import ScanContext, register_scanner
12
+
13
+ _K8S_KINDS = {"Pod", "Deployment", "DaemonSet", "StatefulSet", "ReplicaSet", "Job", "CronJob"}
14
+
15
+ _TF_RULES: list[tuple[re.Pattern[str], str, str, str, str]] = [
16
+ (re.compile(r'cidr_blocks\s*=\s*\[\s*"0\.0\.0\.0/0"\s*\]'), "IAC-TF-001", "Terraform security group open to 0.0.0.0/0", "HIGH",
17
+ "Restrict ingress CIDR blocks to trusted IP ranges."),
18
+ (re.compile(r'acl\s*=\s*"public-read(?:-write)?"'), "IAC-TF-002", "Public S3 bucket ACL configured", "CRITICAL",
19
+ "Set S3 bucket ACL to 'private' and enforce public access blocks."),
20
+ (re.compile(r'storage_encrypted\s*=\s*false|encrypted\s*=\s*false'), "IAC-TF-003", "Unencrypted storage resource in Terraform", "HIGH",
21
+ "Enable encryption at rest (encrypted = true / storage_encrypted = true)."),
22
+ (re.compile(r'"Action"\s*:\s*"\*"[^}]*"Resource"\s*:\s*"\*"', re.S), "IAC-TF-004", "Wildcard IAM policy (*:*) in Terraform", "CRITICAL",
23
+ "Scope IAM actions and resources to least-privilege."),
24
+ ]
25
+
26
+
27
+ def _scan_k8s_doc(rel_path: str, doc: dict[str, Any]) -> list[dict[str, Any]]:
28
+ out: list[dict[str, Any]] = []
29
+ if not isinstance(doc, dict) or doc.get("kind") not in _K8S_KINDS:
30
+ return out
31
+ spec = doc.get("spec") or {}
32
+ if "template" in spec and isinstance(spec["template"], dict):
33
+ spec = spec["template"].get("spec") or {}
34
+ if not isinstance(spec, dict):
35
+ return out
36
+
37
+ if spec.get("hostNetwork") or spec.get("hostPID") or spec.get("hostIPC"):
38
+ out.append({
39
+ "finding_id": f"IAC-K8S-{len(out) + 1:03d}",
40
+ "rule_id": "IAC-K8S-001",
41
+ "title": "Kubernetes Pod shares host namespace (hostNetwork/hostPID/hostIPC)",
42
+ "description": f"{doc.get('kind')} in {rel_path} enables host-level namespace sharing.",
43
+ "classification": "CONFIGURATION_RISK",
44
+ "severity": "HIGH",
45
+ "confidence": "HIGH",
46
+ "file_path": rel_path,
47
+ "evidence_kind": "pipeline",
48
+ "remediation_text": "Disable hostNetwork, hostPID, and hostIPC unless strictly required.",
49
+ })
50
+
51
+ for c in (spec.get("containers") or []) + (spec.get("initContainers") or []):
52
+ if not isinstance(c, dict):
53
+ continue
54
+ cname = c.get("name", "container")
55
+ sc = c.get("securityContext") or {}
56
+ if sc.get("privileged") is True:
57
+ out.append({
58
+ "finding_id": f"IAC-K8S-{len(out) + 1:03d}",
59
+ "rule_id": "IAC-K8S-002",
60
+ "title": f"Privileged Kubernetes container '{cname}'",
61
+ "description": f"Container '{cname}' in {rel_path} runs with privileged: true.",
62
+ "classification": "CONFIGURATION_RISK",
63
+ "severity": "CRITICAL",
64
+ "confidence": "HIGH",
65
+ "file_path": rel_path,
66
+ "evidence_kind": "pipeline",
67
+ "remediation_text": "Set privileged: false and drop unnecessary Linux capabilities.",
68
+ })
69
+ if sc.get("allowPrivilegeEscalation") is True:
70
+ out.append({
71
+ "finding_id": f"IAC-K8S-{len(out) + 1:03d}",
72
+ "rule_id": "IAC-K8S-003",
73
+ "title": f"Privilege escalation allowed on container '{cname}'",
74
+ "description": f"Container '{cname}' in {rel_path} allows privilege escalation.",
75
+ "classification": "CONFIGURATION_RISK",
76
+ "severity": "HIGH",
77
+ "confidence": "HIGH",
78
+ "file_path": rel_path,
79
+ "evidence_kind": "pipeline",
80
+ "remediation_text": "Set allowPrivilegeEscalation: false.",
81
+ })
82
+ img = str(c.get("image") or "")
83
+ if img and (":" not in img.split("/")[-1] or img.endswith(":latest")) and "@sha256:" not in img:
84
+ out.append({
85
+ "finding_id": f"IAC-K8S-{len(out) + 1:03d}",
86
+ "rule_id": "IAC-K8S-004",
87
+ "title": f"Unpinned Kubernetes container image '{img}'",
88
+ "description": f"Container '{cname}' in {rel_path} uses an unpinned or ':latest' image tag.",
89
+ "classification": "CONFIGURATION_RISK",
90
+ "severity": "MEDIUM",
91
+ "confidence": "HIGH",
92
+ "file_path": rel_path,
93
+ "evidence_kind": "pipeline",
94
+ "remediation_text": "Pin container images to an immutable version tag or @sha256 digest.",
95
+ })
96
+ return out
97
+
98
+
99
+ class IacSecurityScanner:
100
+ name = "iac_scanner"
101
+ category = "iac"
102
+
103
+ def scan(self, ctx: ScanContext) -> dict[str, Any]:
104
+ findings: list[dict[str, Any]] = []
105
+ files_scanned = 0
106
+ for rel_path, size in walk_repo(ctx.repo_dir):
107
+ if size > 512 * 1024:
108
+ continue
109
+ ext = Path(rel_path).suffix.lower()
110
+ if ext not in (".tf", ".yaml", ".yml"):
111
+ continue
112
+ text = safe_read_text(ctx.repo_dir, rel_path, max_bytes=512 * 1024)
113
+ if not text:
114
+ continue
115
+ files_scanned += 1
116
+ if ext == ".tf":
117
+ for pat, rule_id, title, sev, rem in _TF_RULES:
118
+ for m in pat.finditer(text):
119
+ ln = text.count("\n", 0, m.start()) + 1
120
+ findings.append({
121
+ "finding_id": f"IAC-TF-{len(findings) + 1:03d}",
122
+ "rule_id": rule_id,
123
+ "title": title,
124
+ "description": f"Terraform security rule {rule_id} matched in {rel_path}:{ln}.",
125
+ "classification": "CONFIGURATION_RISK",
126
+ "severity": sev,
127
+ "confidence": "HIGH",
128
+ "file_path": rel_path,
129
+ "line": ln,
130
+ "snippet": m.group(0).strip()[:200],
131
+ "evidence_kind": "pipeline",
132
+ "remediation_text": rem,
133
+ })
134
+ elif ext in (".yaml", ".yml") and "kind:" in text:
135
+ try:
136
+ for doc in yaml.safe_load_all(text):
137
+ if isinstance(doc, dict):
138
+ findings.extend(_scan_k8s_doc(rel_path, doc))
139
+ except yaml.YAMLError:
140
+ pass
141
+ return {"findings": findings, "limitations": [], "meta": {"files_scanned": files_scanned, "findings": len(findings)}}
142
+
143
+
144
+ register_scanner(IacSecurityScanner())
@@ -0,0 +1,272 @@
1
+ """Layer 2 Non-CVE Scanner: SAST, taint analysis and framework rules.
2
+
3
+ Uses ``semgrep`` when installed (online scans), and always runs
4
+ built-in Python AST taint analysis + multi-language framework security rules.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ import json
10
+ import re
11
+ import shutil
12
+ import subprocess
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from core.repository_inspector import safe_read_text, walk_repo
17
+ from core.safe_env import scrubbed_env
18
+ from non_cve.base import ScanContext, register_scanner
19
+
20
+ _TAINT_SOURCES_PY = {"request", "req", "args", "form", "json", "params", "query", "headers", "cookies", "environ", "argv", "input"}
21
+ _SINKS_PY = {
22
+ "eval": ("SAST-PY-001", "Arbitrary code execution via eval()", "CRITICAL"),
23
+ "exec": ("SAST-PY-002", "Arbitrary code execution via exec()", "CRITICAL"),
24
+ "system": ("SAST-PY-003", "OS command execution via os.system()", "HIGH"),
25
+ "popen": ("SAST-PY-004", "OS command execution via os.popen()", "HIGH"),
26
+ "pickle.loads": ("SAST-PY-005", "Unsafe deserialization via pickle/marshal loads()", "HIGH"),
27
+ "marshal.loads": ("SAST-PY-005", "Unsafe deserialization via pickle/marshal loads()", "HIGH"),
28
+ }
29
+
30
+ _FRAMEWORK_REGEX_RULES: list[tuple[tuple[str, ...], re.Pattern[str], str, str, str, str]] = [
31
+ ((".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"),
32
+ re.compile(r"child_process\.(?:exec|execSync)\s*\(\s*[^'\"\n]*(\$\{|\+)"),
33
+ "SAST-JS-001", "Command injection in child_process.exec with interpolated input", "CRITICAL",
34
+ "Use execFile/spawn with an argument array instead of shell string interpolation."),
35
+ ((".js", ".jsx", ".ts", ".tsx"),
36
+ re.compile(r"dangerouslySetInnerHTML\s*=\s*\{\s*\{\s*__html\s*:"),
37
+ "SAST-REACT-001", "Potential XSS via dangerouslySetInnerHTML", "HIGH",
38
+ "Sanitize HTML with DOMPurify or render structured JSX instead."),
39
+ ((".js", ".ts"),
40
+ re.compile(r"cors\s*\(\s*\{[^}]*origin\s*:\s*['\"]\*['\"][^}]*credentials\s*:\s*true", re.S),
41
+ "SAST-EXP-001", "Insecure CORS wildcard origin with credentials enabled", "HIGH",
42
+ "Restrict CORS origin to an explicit allow-list."),
43
+ ((".java", ".kt"),
44
+ re.compile(r"Runtime\.getRuntime\(\)\.exec\s*\(|new\s+ObjectInputStream\s*\("),
45
+ "SAST-JAVA-001", "Dangerous command execution or unsafe Java deserialization", "HIGH",
46
+ "Use ProcessBuilder with fixed arguments or safe serialization formats (JSON)."),
47
+ ((".go",),
48
+ re.compile(r"exec\.Command\s*\(\s*\"(?:sh|bash)\"\s*,\s*\"-c\""),
49
+ "SAST-GO-001", "Shell invocation via exec.Command('sh', '-c', ...)", "HIGH",
50
+ "Invoke the target binary directly with exec.Command(bin, arg1, arg2)."),
51
+ ]
52
+
53
+
54
+ def _qualified_name(node: ast.AST | None, imports: dict[str, str]) -> str:
55
+ suffix = []
56
+ while isinstance(node, ast.Attribute):
57
+ suffix.append(node.attr)
58
+ node = node.value
59
+ if not isinstance(node, ast.Name):
60
+ return ""
61
+ return ".".join([imports.get(node.id, node.id), *reversed(suffix)])
62
+
63
+
64
+ def _scan_python_ast(rel_path: str, text: str, offset: int = 0) -> list[dict[str, Any]]:
65
+ findings: list[dict[str, Any]] = []
66
+ try:
67
+ tree = ast.parse(text)
68
+ except (SyntaxError, ValueError, RecursionError):
69
+ return findings
70
+
71
+ tainted_vars: set[str] = set()
72
+ lines = text.splitlines()
73
+ nodes = list(ast.walk(tree))
74
+ imports: dict[str, str] = {}
75
+ for node in nodes:
76
+ if isinstance(node, ast.Import):
77
+ for name in node.names:
78
+ root = name.name.split(".")[0]
79
+ imports[name.asname or root] = name.name if name.asname else root
80
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
81
+ for name in node.names:
82
+ imports[name.asname or name.name] = f"{node.module}.{name.name}"
83
+
84
+ def framework(node: ast.AST, rule_id: str, title: str, severity: str, remediation: str) -> None:
85
+ ln = node.lineno
86
+ findings.append({
87
+ "finding_id": f"SAST-FW-{offset + len(findings) + 1:03d}", "rule_id": rule_id, "title": title,
88
+ "description": f"Framework security rule {rule_id} matched in {rel_path}:{ln}.",
89
+ "classification": "HEURISTIC_FLAG", "severity": severity, "confidence": "MEDIUM",
90
+ "file_path": rel_path, "line": ln, "snippet": lines[ln - 1].strip()[:200],
91
+ "evidence_kind": "ast", "remediation_text": remediation,
92
+ })
93
+
94
+ def _is_tainted(node: ast.AST) -> bool:
95
+ for sub in ast.walk(node):
96
+ if isinstance(sub, ast.Name) and (sub.id in tainted_vars or sub.id in _TAINT_SOURCES_PY):
97
+ return True
98
+ if isinstance(sub, ast.Attribute) and sub.attr in _TAINT_SOURCES_PY:
99
+ return True
100
+ return False
101
+
102
+ for node in nodes:
103
+ if isinstance(node, (ast.Assign, ast.AnnAssign)) and isinstance(node.value, ast.Constant) and node.value.value is True:
104
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
105
+ if any(isinstance(target, ast.Name) and target.id == "DEBUG" for target in targets):
106
+ framework(node, "SAST-PY-010", "Web framework debug mode enabled", "MEDIUM",
107
+ "Disable DEBUG mode in production configurations.")
108
+ if isinstance(node, ast.Assign) and _is_tainted(node.value):
109
+ for t in node.targets:
110
+ if isinstance(t, ast.Name):
111
+ tainted_vars.add(t.id)
112
+ if isinstance(node, ast.Call):
113
+ qualified = _qualified_name(node.func, imports)
114
+ fn_name = node.func.attr if isinstance(node.func, ast.Attribute) else qualified.rpartition(".")[2]
115
+ sink = _SINKS_PY.get(qualified) or _SINKS_PY.get(fn_name)
116
+ if sink and node.args and _is_tainted(node.args[0]):
117
+ rule_id, title, sev = sink
118
+ ln = getattr(node, "lineno", 1)
119
+ snip = lines[ln - 1].strip() if 1 <= ln <= len(lines) else ""
120
+ findings.append({
121
+ "finding_id": f"SAST-AST-{offset + len(findings) + 1:03d}",
122
+ "rule_id": rule_id,
123
+ "title": f"Tainted input reaches {title}",
124
+ "description": f"Untrusted source flows into '{fn_name}()' in {rel_path}:{ln}.",
125
+ "classification": "HEURISTIC_FLAG",
126
+ "severity": sev,
127
+ "confidence": "HIGH",
128
+ "file_path": rel_path,
129
+ "line": ln,
130
+ "snippet": snip[:200],
131
+ "evidence_kind": "taint",
132
+ "remediation_text": f"Validate/sanitize untrusted input or avoid '{fn_name}()'.",
133
+ })
134
+ keywords = {kw.arg: kw.value for kw in node.keywords}
135
+ if qualified == "yaml.load":
136
+ loader = keywords.get("Loader", node.args[1] if len(node.args) > 1 else None)
137
+ if _qualified_name(loader, imports) not in {"yaml.SafeLoader", "yaml.CSafeLoader", "yaml.loader.SafeLoader"}:
138
+ framework(node, "SAST-PY-011", "Unsafe yaml.load() without SafeLoader", "HIGH",
139
+ "Use yaml.safe_load() or Loader=yaml.SafeLoader.")
140
+ if _qualified_name(node.func, {}) == "app.run":
141
+ debug = keywords.get("debug")
142
+ if isinstance(debug, ast.Constant) and debug.value is True:
143
+ framework(node, "SAST-PY-010", "Web framework debug mode enabled", "MEDIUM",
144
+ "Disable DEBUG mode in production configurations.")
145
+ # subprocess(..., shell=True)
146
+ if fn_name in ("run", "Popen", "call", "check_output"):
147
+ for kw in node.keywords:
148
+ if kw.arg == "shell" and isinstance(kw.value, ast.Constant) and kw.value.value is True:
149
+ ln = getattr(node, "lineno", 1)
150
+ snip = lines[ln - 1].strip() if 1 <= ln <= len(lines) else ""
151
+ findings.append({
152
+ "finding_id": f"SAST-SUB-{offset + len(findings) + 1:03d}",
153
+ "rule_id": "SAST-PY-006",
154
+ "title": "Subprocess invoked with shell=True",
155
+ "description": f"shell=True enables command injection if any argument is user-controlled ({rel_path}:{ln}).",
156
+ "classification": "CONFIGURATION_RISK",
157
+ "severity": "HIGH",
158
+ "confidence": "HIGH",
159
+ "file_path": rel_path,
160
+ "line": ln,
161
+ "snippet": snip[:200],
162
+ "evidence_kind": "ast",
163
+ "remediation_text": "Pass an argument list with shell=False.",
164
+ })
165
+ return findings
166
+
167
+
168
+ def _run_optional_semgrep(repo_dir: Path) -> tuple[list[dict[str, Any]], str | None]:
169
+ exe = shutil.which("semgrep")
170
+ if not exe:
171
+ return [], "Semgrep CLI not installed; using built-in AST/taint and framework rules."
172
+ try:
173
+ proc = subprocess.run(
174
+ [exe, "--json", "--quiet", "--no-git-ignore", "--config", "auto", str(repo_dir)],
175
+ capture_output=True,
176
+ text=True,
177
+ timeout=45,
178
+ env=scrubbed_env(),
179
+ shell=False,
180
+ )
181
+ if not proc.stdout.strip():
182
+ return [], f"Semgrep produced no JSON (exit {proc.returncode})."
183
+ data = json.loads(proc.stdout)
184
+ out: list[dict[str, Any]] = []
185
+ for r in data.get("results") or []:
186
+ extra = r.get("extra") or {}
187
+ sev = str(extra.get("severity") or "WARNING").upper()
188
+ sev_map = {"ERROR": "HIGH", "WARNING": "MEDIUM", "INFO": "LOW"}
189
+ out.append({
190
+ "finding_id": f"SEMGREP-{len(out) + 1:03d}",
191
+ "rule_id": str(r.get("check_id") or "semgrep"),
192
+ "title": str(extra.get("message") or r.get("check_id") or "Semgrep finding")[:160],
193
+ "description": str(extra.get("message") or ""),
194
+ "classification": "HEURISTIC_FLAG",
195
+ "severity": sev_map.get(sev, "MEDIUM"),
196
+ "confidence": "HIGH",
197
+ "file_path": str(r.get("path") or ""),
198
+ "line": (r.get("start") or {}).get("line"),
199
+ "snippet": str(extra.get("lines") or "")[:200],
200
+ "evidence_kind": "ast",
201
+ "remediation_text": "Review Semgrep rule guidance and remediate the vulnerable sink.",
202
+ })
203
+ issue = f"Semgrep reported errors (exit {proc.returncode})." if proc.returncode or data.get("errors") else None
204
+ return out, issue
205
+ except Exception as exc:
206
+ return [], f"Semgrep execution skipped ({type(exc).__name__}); using built-in AST/taint rules."
207
+
208
+
209
+ class SastTaintScanner:
210
+ name = "sast_taint"
211
+ category = "sast"
212
+
213
+ def applicable(self, ctx: ScanContext) -> bool:
214
+ if ctx.inspection is None or getattr(ctx.inspection, "truncated", False):
215
+ return True
216
+ languages = set(ctx.inspection.languages)
217
+ return bool(languages & {"Python", "JavaScript", "TypeScript", "Java", "Kotlin", "Go"}
218
+ or (languages and shutil.which("semgrep") and not getattr(ctx.http_client, "offline", False)))
219
+
220
+ def scan(self, ctx: ScanContext) -> dict[str, Any]:
221
+ findings: list[dict[str, Any]] = []
222
+ limitations: list[str] = []
223
+
224
+ if getattr(ctx.http_client, "offline", False):
225
+ sg_findings, sg_lim = [], "Semgrep remote rules disabled in offline mode."
226
+ else:
227
+ sg_findings, sg_lim = _run_optional_semgrep(ctx.repo_dir)
228
+ findings.extend(sg_findings)
229
+ if sg_lim:
230
+ limitations.append(sg_lim)
231
+
232
+ files_scanned = 0
233
+ for rel_path, size in walk_repo(ctx.repo_dir):
234
+ if size > 512 * 1024:
235
+ continue
236
+ ext = Path(rel_path).suffix.lower()
237
+ if ext not in (".py", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".java", ".kt", ".go"):
238
+ continue
239
+ text = safe_read_text(ctx.repo_dir, rel_path, max_bytes=512 * 1024)
240
+ if not text:
241
+ continue
242
+ files_scanned += 1
243
+ if ext == ".py":
244
+ findings.extend(_scan_python_ast(rel_path, text, offset=len(findings)))
245
+ for exts, pat, rule_id, title, sev, rem in _FRAMEWORK_REGEX_RULES:
246
+ if ext not in exts:
247
+ continue
248
+ for m in pat.finditer(text):
249
+ ln = text.count("\n", 0, m.start()) + 1
250
+ findings.append({
251
+ "finding_id": f"SAST-FW-{len(findings) + 1:03d}",
252
+ "rule_id": rule_id,
253
+ "title": title,
254
+ "description": f"Framework security rule {rule_id} matched in {rel_path}:{ln}.",
255
+ "classification": "HEURISTIC_FLAG",
256
+ "severity": sev,
257
+ "confidence": "MEDIUM",
258
+ "file_path": rel_path,
259
+ "line": ln,
260
+ "snippet": m.group(0).strip()[:200],
261
+ "evidence_kind": "ast",
262
+ "remediation_text": rem,
263
+ })
264
+
265
+ return {
266
+ "findings": findings,
267
+ "limitations": limitations,
268
+ "meta": {"status": "ok", "files_scanned": files_scanned, "semgrep": sg_lim is None, "findings": len(findings)},
269
+ }
270
+
271
+
272
+ register_scanner(SastTaintScanner())
@@ -0,0 +1,147 @@
1
+ """Layer 1 Non-CVE Scanner: Supply-Chain Anomaly, Tarball-vs-Git Comparison & Registry Intelligence."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import re
6
+ from typing import Any
7
+
8
+ from non_cve.base import ScanContext, register_scanner
9
+
10
+ _OBFUSCATION_PATTERNS = [
11
+ (re.compile(r"\beval\s*\(|new\s+Function\s*\(|\bexec\s*\("), "SC-OBF-001", "Dynamic code execution in package/install script", "HIGH"),
12
+ (re.compile(r"atob\s*\(|Buffer\.from\s*\([^,]+,\s*['\"]base64['\"]\)|base64\s+-d"), "SC-OBF-002", "Base64 payload decoding in script", "HIGH"),
13
+ (re.compile(r"(?:curl|wget|Invoke-WebRequest|fetch)\s+[^\n]*\|\s*(?:sh|bash|zsh|pwsh|powershell)"), "SC-RCE-001", "Remote script pipe-to-shell execution", "CRITICAL"),
14
+ (re.compile(r"(?:\.ssh/|\.aws/credentials|\.npmrc|\.pypirc|GITHUB_TOKEN|NPM_TOKEN|AWS_SECRET_ACCESS_KEY)"), "SC-EXF-001", "Credential or secret file access in package metadata/script", "HIGH"),
15
+ ]
16
+
17
+
18
+ def _shannon_entropy(s: str) -> float:
19
+ if not s:
20
+ return 0.0
21
+ freq: dict[str, int] = {}
22
+ for ch in s:
23
+ freq[ch] = freq.get(ch, 0) + 1
24
+ n = len(s)
25
+ return -sum((c / n) * math.log2(c / n) for c in freq.values())
26
+
27
+
28
+ class SupplyChainAnomalyScanner:
29
+ name = "supply_chain_anomaly"
30
+ category = "supply_chain"
31
+
32
+ def scan(self, ctx: ScanContext) -> dict[str, Any]:
33
+ findings: list[dict[str, Any]] = []
34
+ limitations: list[str] = []
35
+ checked = 0
36
+
37
+ for comp in ctx.components:
38
+ if getattr(comp, "is_self", False):
39
+ continue
40
+ checked += 1
41
+ pkg = getattr(comp, "name", "") or "unknown"
42
+ eco = getattr(comp, "ecosystem", "") or "unknown"
43
+ ver = getattr(comp, "version", "") or ""
44
+ resolved = getattr(comp, "resolved_url", None) or ""
45
+ src_type = getattr(comp, "source_type", None) or ""
46
+ ext_refs = getattr(comp, "external_refs", None) or []
47
+ integrity = getattr(comp, "integrity", None) or {}
48
+ install_script = bool(getattr(comp, "install_script", False))
49
+
50
+ # 1. Tarball-vs-Git / Source Repository Verification
51
+ has_vcs = any((r.get("type") in ("vcs", "repository", "source")) and r.get("url") for r in ext_refs if isinstance(r, dict))
52
+ if src_type in ("url", "git") and resolved:
53
+ findings.append({
54
+ "finding_id": f"SC-SRC-{len(findings) + 1:03d}",
55
+ "rule_id": "SC-TARBALL-001",
56
+ "title": f"Non-registry / mutable {src_type} dependency source for {pkg}",
57
+ "description": (
58
+ f"{pkg}@{ver} ({eco}) resolves from '{resolved}' instead of an immutable registry release. "
59
+ "Tarball-vs-Git integrity cannot be guaranteed by registry checksums."
60
+ ),
61
+ "classification": "OBSERVED_CHANGE",
62
+ "severity": "HIGH" if src_type == "url" else "MEDIUM",
63
+ "confidence": "HIGH",
64
+ "package_name": pkg,
65
+ "snippet": resolved[:240],
66
+ "provenance": {"scanner": self.name, "ecosystem": eco, "source_type": src_type},
67
+ "remediation_text": f"Pin {pkg} to a verified registry release with an integrity hash.",
68
+ })
69
+ elif ext_refs and not has_vcs and install_script:
70
+ findings.append({
71
+ "finding_id": f"SC-VCS-{len(findings) + 1:03d}",
72
+ "rule_id": "SC-TARBALL-002",
73
+ "title": f"Package {pkg} has install scripts but no verifiable VCS source link",
74
+ "description": (
75
+ f"{pkg}@{ver} ({eco}) executes install-time scripts and lacks a declared source repository reference, "
76
+ "preventing tarball-vs-Git source auditing."
77
+ ),
78
+ "classification": "HEURISTIC_FLAG",
79
+ "severity": "HIGH",
80
+ "confidence": "MEDIUM",
81
+ "package_name": pkg,
82
+ "provenance": {"scanner": self.name, "ecosystem": eco},
83
+ "remediation_text": f"Audit the published tarball for {pkg}@{ver} before installing.",
84
+ })
85
+
86
+ # 2. Registry Integrity & Attestation Anomalies
87
+ if integrity.get("status") == "mismatch":
88
+ findings.append({
89
+ "finding_id": f"SC-INT-{len(findings) + 1:03d}",
90
+ "rule_id": "SC-INTEGRITY-001",
91
+ "title": f"Lockfile digest mismatch against registry for {pkg}@{ver}",
92
+ "description": "The lockfile integrity hash differs from the upstream package registry digest (possible tarball tampering or cache poisoning).",
93
+ "classification": "OBSERVED_CHANGE",
94
+ "severity": "CRITICAL",
95
+ "confidence": "HIGH",
96
+ "package_name": pkg,
97
+ "provenance": {"scanner": self.name, "integrity": integrity},
98
+ "remediation_text": f"Re-verify {pkg}@{ver} lockfile checksums and inspect recent registry releases.",
99
+ })
100
+
101
+ # 3. Inspect lockfile-embedded scripts / resolved URLs for obfuscated payloads
102
+ for dep in ctx.lock_deps:
103
+ meta = getattr(dep, "meta", None) or {}
104
+ script_text = " ".join(str(v) for k, v in meta.items() if "script" in k.lower() and v)
105
+ if not script_text:
106
+ continue
107
+ for pat, rule_id, title, sev in _OBFUSCATION_PATTERNS:
108
+ m = pat.search(script_text)
109
+ if m:
110
+ findings.append({
111
+ "finding_id": f"SC-BEH-{len(findings) + 1:03d}",
112
+ "rule_id": rule_id,
113
+ "title": f"{title} ({dep.name})",
114
+ "description": f"Suspicious behavioral pattern detected in lockfile metadata for {dep.name}@{dep.version or '?'}.",
115
+ "classification": "HEURISTIC_FLAG",
116
+ "severity": sev,
117
+ "confidence": "MEDIUM",
118
+ "package_name": dep.name,
119
+ "file_path": getattr(dep, "lockfile", None),
120
+ "snippet": m.group(0)[:200],
121
+ "provenance": {"scanner": self.name, "ecosystem": dep.ecosystem},
122
+ "remediation_text": f"Inspect {dep.lockfile} and package {dep.name} before running package manager install scripts.",
123
+ })
124
+ if len(script_text) > 120 and _shannon_entropy(script_text) > 5.0:
125
+ findings.append({
126
+ "finding_id": f"SC-ENT-{len(findings) + 1:03d}",
127
+ "rule_id": "SC-OBF-003",
128
+ "title": f"High-entropy obfuscated script in {dep.name}",
129
+ "description": f"Install script metadata for {dep.name} has unusually high Shannon entropy ({_shannon_entropy(script_text):.2f}).",
130
+ "classification": "HEURISTIC_FLAG",
131
+ "severity": "HIGH",
132
+ "confidence": "MEDIUM",
133
+ "package_name": dep.name,
134
+ "file_path": getattr(dep, "lockfile", None),
135
+ "snippet": script_text[:160],
136
+ "provenance": {"scanner": self.name, "entropy": round(_shannon_entropy(script_text), 2)},
137
+ "remediation_text": "Decode and review the obfuscated script or replace the dependency.",
138
+ })
139
+
140
+ return {
141
+ "findings": findings,
142
+ "limitations": limitations,
143
+ "meta": {"components_checked": checked, "lock_deps_checked": len(ctx.lock_deps), "findings": len(findings)},
144
+ }
145
+
146
+
147
+ register_scanner(SupplyChainAnomalyScanner())
@@ -0,0 +1 @@
1
+ """LangGraph orchestration of the agent pipeline (see ``pipeline.py``)."""