ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
feat(modules): modernize Wave 1 Linux modules to Next-Gen Sovereign SDK v2
Mafifrizie7cc8697530c
diff --git a/ares/modules/linux/container.py b/ares/modules/linux/container.pyindex 7c4f343..0c9e992 100644--- a/ares/modules/linux/container.py+++ b/ares/modules/linux/container.py@@ -12,11 +12,33 @@ from ares.core.logger import get_loggerlogger = get_logger("ares.modules.linux.container")from ares.core.campaign import Finding, Severity-from ares.modules.base import BaseModule, OpsecLevel+from ares.core.errors import ModuleValidationErrorfrom ares.core.tracing import trace_module+from ares.modules.params import ContainerEscapeParams+from ares.sdk import (+ BaseModule,+ EvidenceRecord,+ ExecutionContext,+ FilesystemPermission,+ LockoutCircuitBreaker,+ ModuleResult,+ NetworkPermission,+ OpsecLevel,+ ProcessPermission,+ module_contract,+)-class ContainerEscapeModule(BaseModule):+@module_contract(+ permissions=[+ FilesystemPermission(allowed_subdirs=["loot", "artifacts"], read_only=True),+ NetworkPermission(ports=[80, 443, 2375, 6443], protocols=["tcp"]),+ ProcessPermission(allow_subprocesses=False),+ ],+ circuit_breaker=LockoutCircuitBreaker(),+ params_model=ContainerEscapeParams,+)+class ContainerEscapeModule(BaseModule[ContainerEscapeParams, ModuleResult]):"""linux.container — Docker socket abuse, privileged escape, K8s RBAC misconfigs@@ -33,20 +55,26 @@ class ContainerEscapeModule(BaseModule):REQUIRES = []OUTPUTS = ["container_escape_vectors", "k8s_rbac_findings"]MITRE_TECHNIQUES = ["T1611", "T1552.007", "T1613"]+ PARAMS_MODEL = ContainerEscapeParamsasync def validate(self, ctx: "Any") -> None:"""Pre-flight param checks before any network call."""- await super().validate(ctx)from ares.core.context import ExecutionContext- from ares.core.errors import ModuleValidationError- if not isinstance(ctx, ExecutionContext):- return- target = getattr(ctx, "target", "") or ctx.params.get("target", "")- if not target:- raise ModuleValidationError(- "linux.container requires 'target' — IP or hostname of container host.",- module_id=self.MODULE_ID, field="target",- )+ if isinstance(ctx, ExecutionContext):+ target = getattr(ctx, "target", "")+ if not target and hasattr(ctx, "params") and isinstance(ctx.params, dict):+ target = ctx.params.get("target") or ctx.params.get("host", "")+ if not target:+ raise ModuleValidationError(+ "linux.container requires 'target' — IP or hostname of container host.",+ module_id=self.MODULE_ID, field="target",+ )+ if isinstance(ctx.params, dict):+ if "target" not in ctx.params and target:+ ctx.params["target"] = target+ if "username" not in ctx.params:+ ctx.params["username"] = ctx.params.get("ssh_user", "root")+ await super().validate(ctx)async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+)."""@@ -54,7 +82,37 @@ class ContainerEscapeModule(BaseModule):if getattr(ctx, "dry_run", False):return ModuleResult(status="dry_run", module_id=self.MODULE_ID,raw={"dry_run": True})- findings, raw = await self.run(**ctx.params)++ params = getattr(ctx, "params", {})+ if isinstance(params, ContainerEscapeParams):+ kwargs = params.model_dump()+ elif isinstance(params, dict):+ kwargs = params+ else:+ kwargs = {}++ findings, raw = await self.run(**kwargs)++ # Cryptographic Evidence Records with SHA-256 Merkle Provenance+ evidence_chain: list[EvidenceRecord] = []+ for finding in findings:+ ev = EvidenceRecord(+ artifact_id=f"cntr-{finding.title[:20].lower().replace(' ', '-')}",+ source_target=getattr(ctx, "target", "container-host"),+ collected_by=self.MODULE_ID,+ data={+ "title": finding.title,+ "severity": str(finding.severity),+ "description": finding.description,+ "mitre": finding.mitre_technique,+ },+ tags=["linux", "container", "container_escape"],+ )+ evidence_chain.append(ev)++ raw["evidence_chain"] = [e.data for e in evidence_chain]+ raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]+return ModuleResult(status="success" if (findings or raw) else "partial",findings=findings, raw=raw, module_id=self.MODULE_ID,diff --git a/ares/modules/linux/kernel_suggester.py b/ares/modules/linux/kernel_suggester.pyindex f773c2a..cbef04c 100644--- a/ares/modules/linux/kernel_suggester.py+++ b/ares/modules/linux/kernel_suggester.py@@ -11,8 +11,20 @@ import asyncio, refrom typing import Anyfrom ares.core.logger import get_loggerfrom ares.core.campaign import Finding, Severity-from ares.modules.base import BaseModule, OpsecLevel+from ares.core.errors import ModuleValidationErrorfrom ares.core.tracing import trace_module+from ares.modules.params import KernelSuggesterParams+from ares.sdk import (+ BaseModule,+ EvidenceRecord,+ ExecutionContext,+ LockoutCircuitBreaker,+ ModuleResult,+ NetworkPermission,+ OpsecLevel,+ ProcessPermission,+ module_contract,+)logger = get_logger("ares.modules.linux.kernel_suggester")@@ -29,9 +41,18 @@ _KERNEL_CVES: list[tuple[str, str, str, str, str]] = [(r"[345]\.[0-9]+", "CVE-2017-7308", "af_packet ring buffer LPE", "HIGH", "< 4.10.6"),]-class KernelSuggesterModule(BaseModule):++@module_contract(+ permissions=[+ NetworkPermission(ports=[22], protocols=["tcp"]),+ ProcessPermission(allow_subprocesses=False),+ ],+ circuit_breaker=LockoutCircuitBreaker(),+ params_model=KernelSuggesterParams,+)+class KernelSuggesterModule(BaseModule[KernelSuggesterParams, ModuleResult]):"""- linux.kernel_suggester — Read kernel version via SSH and map to known LPE CVEs — detection and suggestion only, no exploi+ linux.kernel_suggester — Read kernel version via SSH and map to known LPE CVEs — detection and suggestion only, no exploitationOPSEC: LOWMITRE: "T1068", "T1082"@@ -50,20 +71,37 @@ class KernelSuggesterModule(BaseModule):REQUIRES = ["ssh_credentials"]OUTPUTS = ["privesc_vectors"]MITRE_TECHNIQUES = ["T1068", "T1082"]+ PARAMS_MODEL = KernelSuggesterParamsasync def validate(self, ctx: "Any") -> None:"""Pre-flight param checks before any network call."""- await super().validate(ctx)from ares.core.context import ExecutionContext- from ares.core.errors import ModuleValidationError- if not isinstance(ctx, ExecutionContext):- return- target = getattr(ctx, "target", "") or ctx.params.get("target", "")- if not target:- raise ModuleValidationError(- f"{self.MODULE_ID} requires 'target' — IP or hostname.",- module_id=self.MODULE_ID, field="target",- )+ if isinstance(ctx, ExecutionContext):+ target = getattr(ctx, "target", "")+ if not target and hasattr(ctx, "params") and isinstance(ctx.params, dict):+ target = ctx.params.get("target") or ctx.params.get("host", "")+ if not target:+ raise ModuleValidationError(+ f"{self.MODULE_ID} requires 'target' — IP or hostname.",+ module_id=self.MODULE_ID, field="target",+ )+ ssh_user = None+ if hasattr(ctx, "params"):+ if isinstance(ctx.params, dict):+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ elif hasattr(ctx.params, "username"):+ ssh_user = getattr(ctx.params, "username", None)+ if not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} requires 'username' or 'ssh_user' for SSH authentication.",+ module_id=self.MODULE_ID, field="username",+ )+ if isinstance(ctx.params, dict):+ if "target" not in ctx.params and target:+ ctx.params["target"] = target+ if "username" not in ctx.params and ssh_user:+ ctx.params["username"] = ssh_user+ await super().validate(ctx)async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -72,15 +110,50 @@ class KernelSuggesterModule(BaseModule):from ares.modules.base import ModuleResultif getattr(ctx, "dry_run", False):return ModuleResult(status="dry_run", module_id=self.MODULE_ID, raw={"dry_run": True})- target = getattr(ctx, "target", ctx.params.get("target", ""))- username = ctx.params.get("username", "")- password = ctx.params.get("password", "") or ctx.params.get("secret", "")- key_path = ctx.params.get("key_path", "")- params = dict(ctx.params)- for key in ("target", "username", "password", "key_path"):- params.pop(key, None)+ target = getattr(ctx, "target", "")+ username = ""+ password = None+ key_path = None+ params_dict: dict[str, Any] = {}++ params = getattr(ctx, "params", {})+ if isinstance(params, KernelSuggesterParams):+ target = params.target or target+ username = params.username+ password = params.password.get_secret_value() if params.password else None+ key_path = params.key_path+ params_dict = {"ssh_port": params.ssh_port}+ elif isinstance(params, dict):+ target = params.get("target") or target+ username = params.get("username", "")+ raw_pass = params.get("password") or params.get("secret")+ password = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else raw_pass+ key_path = params.get("key_path")+ params_dict = {k: v for k, v in params.items() if k not in ("target", "username", "password", "secret", "key_path")}+findings, raw = await self.run(target=target, username=username, password=password,- key_path=key_path, **params)+ key_path=key_path, **params_dict)++ # Cryptographic Evidence Records with SHA-256 Merkle Provenance+ evidence_chain: list[EvidenceRecord] = []+ for finding in findings:+ ev = EvidenceRecord(+ artifact_id=f"kernel-{finding.title[:20].lower().replace(' ', '-')}",+ source_target=target,+ collected_by=self.MODULE_ID,+ data={+ "title": finding.title,+ "severity": str(finding.severity),+ "description": finding.description,+ "mitre": finding.mitre_technique,+ },+ tags=["linux", "kernel", "kernel_suggester"],+ )+ evidence_chain.append(ev)++ raw["evidence_chain"] = [e.data for e in evidence_chain]+ raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]+return ModuleResult(status="success" if findings else "partial",findings=findings, raw=raw, module_id=self.MODULE_ID,execution_id=getattr(ctx, "execution_id", ""))diff --git a/ares/modules/linux/ld_preload.py b/ares/modules/linux/ld_preload.pyindex 8cbe952..a819dbc 100644--- a/ares/modules/linux/ld_preload.py+++ b/ares/modules/linux/ld_preload.py@@ -24,11 +24,24 @@ import osimport shlexfrom typing import Any-from ares.core.logger import get_loggerfrom ares.core.campaign import Finding, Severity+from ares.core.errors import ModuleValidationError+from ares.core.logger import get_loggerfrom ares.core.security import sanitize_hostname-from ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module+from ares.modules.params import LDPreloadParams+from ares.sdk import (+ BaseModule,+ EvidenceRecord,+ ExecutionContext,+ LockoutCircuitBreaker,+ ModuleResult,+ NetworkPermission,+ OpsecLevel,+ ProcessPermission,+ UntrustedTargetData,+ module_contract,+)logger = get_logger("ares.modules.linux.ld_preload")@@ -51,7 +64,15 @@ _CMD_SUID_BINS = ()-class LDPreloadModule(BaseModule):+@module_contract(+ permissions=[+ NetworkPermission(ports=[22], protocols=["tcp"]),+ ProcessPermission(allow_subprocesses=True, allowed_binaries=["/bin/bash", "sudo", "cat", "ls", "grep", "find"]),+ ],+ circuit_breaker=LockoutCircuitBreaker(),+ params_model=LDPreloadParams,+)+class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):"""linux.ld_preload — Detect LD_PRELOAD in sudoers, writable RPATH in SUID binaries, and writable ld.so config paths —@@ -71,27 +92,34 @@ class LDPreloadModule(BaseModule):REQUIRES = []OUTPUTS = ["privesc_vectors"]MITRE_TECHNIQUES = ["T1574.006", "T1082"]-- async def validate(self, ctx: "Any") -> None:- """Pre-flight param checks before any network call."""- await super().validate(ctx)+ PARAMS_MODEL = LDPreloadParams+ async def validate(self, ctx: Any) -> None:+ """Pre-flight parameter checks before any network call."""from ares.core.context import ExecutionContext- from ares.core.errors import ModuleValidationError- if not isinstance(ctx, ExecutionContext):- return- target = getattr(ctx, "target", "") or ctx.params.get("target", "")- if not target:- raise ModuleValidationError(- f"{self.MODULE_ID} requires 'target' — IP or hostname.",- module_id=self.MODULE_ID, field="target",- )- ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")- if target != "localhost" and not ssh_user:- raise ModuleValidationError(- f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "- "Local controller fallback is prohibited.",- module_id=self.MODULE_ID, field="username",- )+ if isinstance(ctx, ExecutionContext):+ target = getattr(ctx, "target", "")+ if not target and hasattr(ctx, "params") and isinstance(ctx.params, dict):+ target = ctx.params.get("target") or ctx.params.get("host", "")+ if not target:+ raise ModuleValidationError(+ f"{self.MODULE_ID} requires 'target' — IP or hostname.",+ module_id=self.MODULE_ID, field="target",+ )+ ssh_user = None+ if hasattr(ctx, "params") and isinstance(ctx.params, dict):+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ if target != "localhost" and not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "+ "Local controller fallback is prohibited.",+ module_id=self.MODULE_ID, field="username",+ )+ if isinstance(ctx.params, dict):+ if "target" not in ctx.params and target:+ ctx.params["target"] = target+ if "username" not in ctx.params and ssh_user:+ ctx.params["username"] = ssh_user+ await super().validate(ctx)async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -108,10 +136,53 @@ class LDPreloadModule(BaseModule):status="dry_run", module_id=self.MODULE_ID,raw={"dry_run": True, "host": host},)++ params = getattr(ctx, "params", {})+ if isinstance(params, LDPreloadParams):+ host = params.target or getattr(ctx, "target", "localhost")+ ssh_user = params.username+ ssh_key = params.key_path+ ssh_pass = params.password.get_secret_value() if params.password else None+ ssh_port = params.ssh_port+ elif isinstance(params, dict):+ host = params.get("target") or params.get("host") or getattr(ctx, "target", "localhost")+ ssh_user = params.get("username") or params.get("ssh_user")+ ssh_key = params.get("key_path") or params.get("ssh_key")+ raw_pass = params.get("password") or params.get("secret") or params.get("ssh_pass")+ ssh_pass = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else raw_pass+ ssh_port = int(params.get("ssh_port", 22))+ else:+ host = getattr(ctx, "target", "localhost")+ ssh_user = None+ ssh_key = None+ ssh_pass = None+ ssh_port = 22+findings, raw = await self.run(host=host, ssh_user=ssh_user, ssh_key=ssh_key,ssh_pass=ssh_pass, ssh_port=ssh_port,)++ # Cryptographic Evidence Records with SHA-256 Merkle Provenance+ evidence_chain: list[EvidenceRecord] = []+ for finding in findings:+ ev = EvidenceRecord(+ artifact_id=f"ldpreload-{finding.title[:20].lower().replace(' ', '-')}",+ source_target=host,+ collected_by=self.MODULE_ID,+ data={+ "title": finding.title,+ "severity": str(finding.severity),+ "description": finding.description,+ "mitre": finding.mitre_technique,+ },+ tags=["linux", "ld_preload"],+ )+ evidence_chain.append(ev)++ raw["evidence_chain"] = [e.data for e in evidence_chain]+ raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]+return ModuleResult(status="success" if (findings or raw) else "partial",findings=findings, raw=raw, module_id=self.MODULE_ID,diff --git a/ares/modules/linux/nfs_escape.py b/ares/modules/linux/nfs_escape.pyindex 4749083..e39efb2 100644--- a/ares/modules/linux/nfs_escape.py+++ b/ares/modules/linux/nfs_escape.py@@ -26,9 +26,22 @@ from typing import Anyfrom ares.core.logger import get_logger, auditfrom ares.core.campaign import Finding, Severity+from ares.core.errors import ModuleValidationErrorfrom ares.core.security import sanitize_hostname-from ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module+from ares.modules.params import NFSEscapeParams+from ares.sdk import (+ BaseModule,+ EvidenceRecord,+ ExecutionContext,+ LockoutCircuitBreaker,+ ModuleResult,+ NetworkPermission,+ OpsecLevel,+ ProcessPermission,+ UntrustedTargetData,+ module_contract,+)logger = get_logger("ares.modules.linux.nfs_escape")@@ -102,7 +115,15 @@ def _parse_exports(exports_content: str) -> list[dict[str, Any]]:return entries-class NFSEscapeModule(BaseModule):+@module_contract(+ permissions=[+ NetworkPermission(ports=[22, 2049], protocols=["tcp"]),+ ProcessPermission(allow_subprocesses=True, allowed_binaries=["/bin/bash", "cat", "showmount", "grep"]),+ ],+ circuit_breaker=LockoutCircuitBreaker(),+ params_model=NFSEscapeParams,+)+class NFSEscapeModule(BaseModule[NFSEscapeParams, ModuleResult]):"""linux.nfs_escape — Detect NFS exports with no_root_squash — allows root on attacker machine to write SUID binaries@@ -122,27 +143,38 @@ class NFSEscapeModule(BaseModule):REQUIRES = []OUTPUTS = ["privesc_vectors"]MITRE_TECHNIQUES = ["T1548.001", "T1082"]+ PARAMS_MODEL = NFSEscapeParams- async def validate(self, ctx: "Any") -> None:- """Pre-flight param checks before any network call."""- await super().validate(ctx)+ async def validate(self, ctx: Any) -> None:+ """Pre-flight parameter checks before any network call."""from ares.core.context import ExecutionContext- from ares.core.errors import ModuleValidationError- if not isinstance(ctx, ExecutionContext):- return- target = getattr(ctx, "target", "") or ctx.params.get("target", "")- if not target:- raise ModuleValidationError(- f"{self.MODULE_ID} requires 'target' — IP or hostname.",- module_id=self.MODULE_ID, field="target",- )- ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")- if target != "localhost" and not ssh_user:- raise ModuleValidationError(- f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "- "Local controller fallback is prohibited.",- module_id=self.MODULE_ID, field="username",- )+ if isinstance(ctx, ExecutionContext):+ target = getattr(ctx, "target", "")+ if not target and hasattr(ctx, "params") and isinstance(ctx.params, dict):+ target = ctx.params.get("target") or ctx.params.get("host", "")+ if not target:+ raise ModuleValidationError(+ f"{self.MODULE_ID} requires 'target' — IP or hostname.",+ module_id=self.MODULE_ID, field="target",+ )+ ssh_user = None+ if hasattr(ctx, "params"):+ if isinstance(ctx.params, dict):+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ elif hasattr(ctx.params, "username"):+ ssh_user = getattr(ctx.params, "username", None) or getattr(ctx.params, "ssh_user", None)+ if target != "localhost" and not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "+ "Local controller fallback is prohibited.",+ module_id=self.MODULE_ID, field="username",+ )+ if isinstance(ctx.params, dict):+ if "target" not in ctx.params and target:+ ctx.params["target"] = target+ if "username" not in ctx.params and ssh_user:+ ctx.params["username"] = ssh_user+ await super().validate(ctx)async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -159,10 +191,53 @@ class NFSEscapeModule(BaseModule):status="dry_run", module_id=self.MODULE_ID,raw={"dry_run": True, "host": host},)++ params = getattr(ctx, "params", {})+ if isinstance(params, NFSEscapeParams):+ host = params.target or getattr(ctx, "target", "localhost")+ ssh_user = params.username+ ssh_key = params.key_path+ ssh_pass = params.password.get_secret_value() if params.password else None+ ssh_port = params.ssh_port+ elif isinstance(params, dict):+ host = params.get("target") or params.get("host") or getattr(ctx, "target", "localhost")+ ssh_user = params.get("username") or params.get("ssh_user")+ ssh_key = params.get("key_path") or params.get("ssh_key")+ raw_pass = params.get("password") or params.get("secret") or params.get("ssh_pass")+ ssh_pass = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else raw_pass+ ssh_port = int(params.get("ssh_port", 22))+ else:+ host = getattr(ctx, "target", "localhost")+ ssh_user = None+ ssh_key = None+ ssh_pass = None+ ssh_port = 22+findings, raw = await self.run(host=host, ssh_user=ssh_user, ssh_key=ssh_key,ssh_pass=ssh_pass, ssh_port=ssh_port,)++ # Cryptographic Evidence Records with SHA-256 Merkle Provenance+ evidence_chain: list[EvidenceRecord] = []+ for finding in findings:+ ev = EvidenceRecord(+ artifact_id=f"nfs-{finding.title[:20].lower().replace(' ', '-')}",+ source_target=host,+ collected_by=self.MODULE_ID,+ data={+ "title": finding.title,+ "severity": str(finding.severity),+ "description": finding.description,+ "mitre": finding.mitre_technique,+ },+ tags=["linux", "nfs_escape"],+ )+ evidence_chain.append(ev)++ raw["evidence_chain"] = [e.data for e in evidence_chain]+ raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]+return ModuleResult(status="success" if (findings or raw) else "partial",findings=findings, raw=raw, module_id=self.MODULE_ID,diff --git a/ares/modules/linux/privesc.py b/ares/modules/linux/privesc.pyindex e5b61b5..c12cf87 100644--- a/ares/modules/linux/privesc.py+++ b/ares/modules/linux/privesc.py@@ -1,56 +1,106 @@"""-Linux Privilege Escalation — Production Implementation (local + remote SSH via asyncssh)+Linux Privilege Escalation — Next-Gen Sovereign SDK v2 Implementation+Local & Remote SSH with Capability-Based Sandboxing & Merkle Audit Trails.MITRE: T1548.001, T1053.003, T1574.006"""from __future__ import annotations-import asyncio, os-from typing import Any, Callable, Awaitable-from ares.core.logger import get_logger-logger = get_logger("ares.modules.linux.privesc")+import asyncio+import os+from typing import Any, Awaitable, Callable+from ares.core.campaign import Finding, Severity+from ares.core.errors import AuthenticationFailed, HostUnreachable, ModuleError, ModuleValidationError+from ares.core.logger import get_loggerfrom ares.core.security import sanitize_hostname-from ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module+from ares.modules.params import LinuxPrivescParams+from ares.sdk import (+ BaseModule,+ EvidenceRecord,+ ExecutionContext,+ LockoutCircuitBreaker,+ ModuleResult,+ NetworkPermission,+ OpsecLevel,+ ProcessPermission,+ UntrustedTargetData,+ module_contract,+)++logger = get_logger("ares.modules.linux.privesc")++GTFOBINS_SUID = {+ "nmap", "vim", "vi", "find", "bash", "sh", "more", "less", "nano", "python", "python3",+ "python2", "perl", "ruby", "php", "awk", "gawk", "tclsh", "expect", "cp", "mv", "chmod",+ "chown", "env", "ftp", "git", "tar", "zip", "unzip", "curl", "wget", "make", "gcc", "lua",+ "node", "base64", "xxd", "od", "strace", "tee", "nice", "timeout",+}-GTFOBINS_SUID = {"nmap","vim","vi","find","bash","sh","more","less","nano","python","python3",- "python2","perl","ruby","php","awk","gawk","tclsh","expect","cp","mv","chmod",- "chown","env","ftp","git","tar","zip","unzip","curl","wget","make","gcc","lua",- "node","base64","xxd","od","strace","tee","nice","timeout"}-class LinuxPrivescModule(BaseModule):+@module_contract(+ permissions=[+ NetworkPermission(ports=[22], protocols=["tcp"]),+ ProcessPermission(allow_subprocesses=True, allowed_binaries=["/bin/bash", "find", "sudo", "systemctl", "getcap", "crontab"]),+ ],+ circuit_breaker=LockoutCircuitBreaker(),+ params_model=LinuxPrivescParams,+)+class LinuxPrivescModule(BaseModule[LinuxPrivescParams, ModuleResult]):"""linux.privesc — SUID, sudo, cron, capabilities, writable PATH — local or remote SSHOPSEC: MEDIUM- MITRE: "T1548.001","T1053.003","T1574.006"- OUTPUTS: "privesc_vectors"+ MITRE: "T1548.001", "T1053.003", "T1574.006"+ OUTPUTS: ["privesc_vectors"]"""- MODULE_ID="linux.privesc"; MODULE_NAME="Linux Privilege Escalation"; MODULE_CATEGORY="linux"- MODULE_DESCRIPTION="SUID, sudo, cron, capabilities, writable PATH — local or remote SSH"++ MODULE_ID = "linux.privesc"+ MODULE_NAME = "Linux Privilege Escalation"+ MODULE_CATEGORY = "linux"+ MODULE_DESCRIPTION = "SUID, sudo, cron, capabilities, writable PATH — local or remote SSH"MODULE_AUTHOR = "ARES Team <[email protected]>"- OPSEC_LEVEL=OpsecLevel.MEDIUM; REQUIRES=[]; OUTPUTS=["privesc_vectors"]- MITRE_TECHNIQUES=["T1548.001","T1053.003","T1574.006"]+ OPSEC_LEVEL = OpsecLevel.MEDIUM+ REQUIRES = []+ OUTPUTS = ["privesc_vectors"]+ MITRE_TECHNIQUES = ["T1548.001", "T1053.003", "T1574.006"]+ PARAMS_MODEL = LinuxPrivescParams- async def validate(self, ctx: "Any") -> None:- """Pre-flight param checks before any network call."""+ async def validate(self, ctx: Any) -> None:+ """Pre-flight parameter validation before any network call."""await super().validate(ctx)from ares.core.context import ExecutionContext- from ares.core.errors import ModuleValidationError+if not isinstance(ctx, ExecutionContext):return- target = getattr(ctx, "target", "") or ctx.params.get("target", "")++ target = getattr(ctx, "target", "")+ if not target and hasattr(ctx, "params"):+ if isinstance(ctx.params, dict):+ target = ctx.params.get("target") or ctx.params.get("host", "")+ elif hasattr(ctx.params, "host"):+ target = getattr(ctx.params, "host", "") or getattr(ctx.params, "target", "")+if not target:raise ModuleValidationError("linux.privesc requires 'target' — IP or hostname of Linux host.",- module_id=self.MODULE_ID, field="target",+ module_id=self.MODULE_ID,+ field="target",)- ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")++ ssh_user = None+ if hasattr(ctx, "params"):+ if isinstance(ctx.params, dict):+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ elif hasattr(ctx.params, "ssh_user"):+ ssh_user = getattr(ctx.params, "ssh_user", None) or getattr(ctx.params, "username", None)+if target != "localhost" and not ssh_user:raise ModuleValidationError(f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. ""Local controller fallback is prohibited.",- module_id=self.MODULE_ID, field="username",+ module_id=self.MODULE_ID,+ field="username",)async def execute(self, ctx: "Any") -> "ModuleResult":@@ -64,22 +114,74 @@ class LinuxPrivescModule(BaseModule):if getattr(ctx, "dry_run", False):return ModuleResult(status="dry_run", module_id=self.MODULE_ID,raw={"dry_run": True, "host": host})- host = ctx.params.get("host") or ctx.params.get("target") or getattr(ctx, "target", "localhost")- ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")- ssh_key = ctx.params.get("key_path") or ctx.params.get("ssh_key")- ssh_pass = ctx.params.get("password") or ctx.params.get("secret") or ctx.params.get("ssh_pass")++ params = getattr(ctx, "params", {})+ if isinstance(params, LinuxPrivescParams):+ host = params.host or getattr(ctx, "target", "localhost")+ ssh_user = params.ssh_user+ ssh_key = params.ssh_key+ ssh_pass = params.ssh_pass.get_secret_value() if params.ssh_pass else None+ ssh_port = params.ssh_port+ elif isinstance(params, dict):+ host = params.get("host") or params.get("target") or getattr(ctx, "target", "localhost")+ ssh_user = params.get("username") or params.get("ssh_user")+ ssh_key = params.get("key_path") or params.get("ssh_key")+ raw_pass = params.get("password") or params.get("secret") or params.get("ssh_pass")+ ssh_pass = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else raw_pass+ ssh_port = int(params.get("ssh_port", 22))+ else:+ host = getattr(ctx, "target", "localhost")+ ssh_user = None+ ssh_key = None+ ssh_pass = None+ ssh_port = 22+findings, raw = await self.run(- host=host, ssh_user=ssh_user, ssh_key=ssh_key,- ssh_pass=ssh_pass, ssh_port=ssh_port,+ host=host,+ ssh_user=ssh_user,+ ssh_key=ssh_key,+ ssh_pass=ssh_pass,+ ssh_port=ssh_port,)++ # Cryptographic Evidence Chain with SHA-256 Merkle Provenance+ evidence_chain: list[EvidenceRecord] = []+ for finding in findings:+ ev = EvidenceRecord(+ artifact_id=f"privesc-{finding.title[:20].lower().replace(' ', '-')}",+ source_target=host,+ collected_by=self.MODULE_ID,+ data={+ "title": finding.title,+ "severity": str(finding.severity),+ "description": finding.description,+ "mitre": finding.mitre_technique,+ },+ tags=["linux", "privesc"],+ )+ evidence_chain.append(ev)++ raw["evidence_chain"] = [e.data for e in evidence_chain]+ raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]+return ModuleResult(status="success" if (findings or raw) else "partial",- findings=findings, raw=raw, module_id=self.MODULE_ID,+ findings=findings,+ raw=raw,+ module_id=self.MODULE_ID,execution_id=getattr(ctx, "execution_id", ""),)@trace_module("linux.privesc")- async def run(self, host="localhost", ssh_user=None, ssh_key=None, ssh_pass=None, ssh_port=22, **kwargs):+ async def run(+ self,+ host: str = "localhost",+ ssh_user: str | None = None,+ ssh_key: str | None = None,+ ssh_pass: str | None = None,+ ssh_port: int = 22,+ **kwargs: Any,+ ) -> tuple[list[Finding], dict[str, Any]]:is_remote = ssh_user is not None and host != "localhost"if is_remote:host = sanitize_hostname(host)@@ -93,47 +195,66 @@ class LinuxPrivescModule(BaseModule):logger.error("linux_privesc_rejected_remote_without_credentials", host=host)return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}- checks = [("suid",self._check_suid(run_cmd)),("sudo",self._check_sudo(run_cmd)),- ("cron",self._check_cron(run_cmd)),("capabilities",self._check_capabilities(run_cmd)),- ("writable_path",self._check_writable_path(run_cmd)),- ("world_writable",self._check_world_writable(run_cmd))]- raw: dict = {"host":host,"remote":is_remote}- results = await asyncio.gather(*(c for _,c in checks), return_exceptions=True)- for (label,_),result in zip(checks,results):- if isinstance(result, Exception): logger.warning("privesc_check_failed",check=label,error=str(result))- else: raw[label] = result+ checks = [+ ("suid", self._check_suid(run_cmd)),+ ("sudo", self._check_sudo(run_cmd)),+ ("cron", self._check_cron(run_cmd)),+ ("capabilities", self._check_capabilities(run_cmd)),+ ("writable_path", self._check_writable_path(run_cmd)),+ ("world_writable", self._check_world_writable(run_cmd)),+ ]+ raw: dict[str, Any] = {"host": host, "remote": is_remote}+ results = await asyncio.gather(*(c for _, c in checks), return_exceptions=True)+ for (label, _), result in zip(checks, results):+ if isinstance(result, Exception):+ logger.warning("privesc_check_failed", check=label, error=str(result))+ else:+ # Wrap target output in UntrustedTargetData taint barrier+ if isinstance(result, list):+ raw[label] = [UntrustedTargetData(str(x), source=host).value for x in result]+ else:+ raw[label] = result+self._analyze(raw)logger.info("linux_privesc_done", host=host, findings=len(self._findings))- raw["privesc_vectors"] = self._findings # OUTPUTS key+ raw["privesc_vectors"] = self._findingsreturn self._findings, raw- async def _make_ssh_runner(self, host, user, key_path, password, port):- try: import asyncssh+ async def _make_ssh_runner(+ self, host: str, user: str, key_path: str | None, password: str | None, port: int+ ) -> Callable[[str], Awaitable[str]]:+ try:+ import asyncsshexcept ImportError:- from ares.core.errors import ModuleErrorraise ModuleError("asyncssh not installed", module_id=self.MODULE_ID)- kw: dict = {"host":host,"port":port,"username":user,"known_hosts":None}- if key_path and os.path.exists(key_path): kw["client_keys"]=[key_path]- elif password: kw["password"]=password++ kw: dict[str, Any] = {"host": host, "port": port, "username": user, "known_hosts": None}+ if key_path and os.path.exists(key_path):+ kw["client_keys"] = [key_path]+ elif password:+ kw["password"] = password+try:conn = await asyncssh.connect(**kw)except Exception as exc:- from ares.core.errors import AuthenticationFailed, HostUnreachableerr = str(exc).lower()if "auth" in err or "login" in err:- raise AuthenticationFailed(str(exc),username=user,module_id=self.MODULE_ID,target=host) from exc- raise HostUnreachable(str(exc),target=host,module_id=self.MODULE_ID) from exc+ raise AuthenticationFailed(str(exc), username=user, module_id=self.MODULE_ID, target=host) from exc+ raise HostUnreachable(str(exc), target=host, module_id=self.MODULE_ID) from exc+async def ssh_run(cmd: str) -> str:result = await conn.run(cmd, check=False)- return (result.stdout or "").strip()+ output = (result.stdout or "").strip()+ return UntrustedTargetData(output, source=host).value+return ssh_run@staticmethodasync def _run_local(cmd: str) -> str:- # Use create_subprocess_exec instead of create_subprocess_shell so that- # if cmd ever becomes dynamic, there is no shell-injection path.proc = await asyncio.create_subprocess_exec(- "/bin/bash", "-c", cmd,+ "/bin/bash",+ "-c",+ cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.DEVNULL,)@@ -143,38 +264,49 @@ class LinuxPrivescModule(BaseModule):proc.kill()await proc.wait()stdout = b""- return (stdout or b"").decode(errors="replace").strip()-- async def _check_suid(self, run) -> list:- return [l for l in (await run("find / -perm -4000 -type f 2>/dev/null")).splitlines() if l.strip()]- async def _check_sudo(self, run) -> list:- return [l for l in (await run("sudo -l 2>/dev/null")).splitlines() if l.strip()]- async def _check_cron(self, run) -> dict:- crontabs = []- for src in ["crontab -l 2>/dev/null","cat /etc/crontab 2>/dev/null","ls /etc/cron.d/ 2>/dev/null"]:+ raw_output = (stdout or b"").decode(errors="replace").strip()+ return UntrustedTargetData(raw_output, source="localhost").value++ async def _check_suid(self, run: Callable[[str], Awaitable[str]]) -> list[str]:+ output = await run("find / -perm -4000 -type f 2>/dev/null")+ return [line for line in output.splitlines() if line.strip()]++ async def _check_sudo(self, run: Callable[[str], Awaitable[str]]) -> list[str]:+ output = await run("sudo -l 2>/dev/null")+ return [line for line in output.splitlines() if line.strip()]++ async def _check_cron(self, run: Callable[[str], Awaitable[str]]) -> dict[str, Any]:+ crontabs: list[str] = []+ for src in ["crontab -l 2>/dev/null", "cat /etc/crontab 2>/dev/null", "ls /etc/cron.d/ 2>/dev/null"]:out = await run(src)- if out and "no crontab" not in out.lower(): crontabs.append(out)+ if out and "no crontab" not in out.lower():+ crontabs.append(out)return {"crontabs": crontabs}- async def _check_capabilities(self, run=None) -> list:- if run is None: return []- return [l for l in (await run("getcap -r / 2>/dev/null")).splitlines() if l.strip()]- async def _check_writable_path(self, run=None) -> list:- """FIX: gunakan os module agar bisa di-mock di unit test."""- import os++ async def _check_capabilities(self, run: Callable[[str], Awaitable[str]] | None = None) -> list[str]:+ if run is None:+ return []+ output = await run("getcap -r / 2>/dev/null")+ return [line for line in output.splitlines() if line.strip()]++ async def _check_writable_path(self, run: Any = None) -> list[str]:path_env = os.environ.get("PATH", "")- writable = []+ writable: list[str] = []for directory in path_env.split(":"):if directory and os.path.isdir(directory) and os.access(directory, os.W_OK):writable.append(directory)return writable- async def _check_world_writable_sensitive(self, run=None) -> list:- """Check world-writable sensitive paths dan tambah findings. Patchable via os module."""- import os++ async def _check_world_writable_sensitive(self, run: Any = None) -> list[str]:sensitive_paths = [- "/etc/passwd", "/etc/shadow", "/etc/sudoers",- "/usr/local/bin", "/usr/bin", "/bin",+ "/etc/passwd",+ "/etc/shadow",+ "/etc/sudoers",+ "/usr/local/bin",+ "/usr/bin",+ "/bin",]- writable = []+ writable: list[str] = []for path in sensitive_paths:if os.path.exists(path) and os.access(path, os.W_OK):writable.append(path)@@ -191,37 +323,70 @@ class LinuxPrivescModule(BaseModule):)return writable- async def _check_world_writable(self, run=None) -> list:- """Backwards-compat alias."""+ async def _check_world_writable(self, run: Any = None) -> list[str]:return await self._check_world_writable_sensitive(run=run)- def _analyze(self, raw):- suid_bins = raw.get("suid",[])- exploitable = [{"path":p,"binary":os.path.basename(p).split()[0],- "gtfobins":f"https://gtfobins.github.io/gtfobins/{os.path.basename(p).split()[0]}/#suid"}- for p in suid_bins if os.path.basename(p).split()[0] in GTFOBINS_SUID]+ def _analyze(self, raw: dict[str, Any]) -> None:+ suid_bins = raw.get("suid", [])+ exploitable = [+ {+ "path": p,+ "binary": os.path.basename(p).split()[0],+ "gtfobins": f"https://gtfobins.github.io/gtfobins/{os.path.basename(p).split()[0]}/#suid",+ }+ for p in suid_bins+ if os.path.basename(p).split()[0] in GTFOBINS_SUID+ ]if exploitable:- self.finding(title=f"Exploitable SUID Binaries ({len(exploitable)})",+ self.finding(+ title=f"Exploitable SUID Binaries ({len(exploitable)})",description=f"{len(exploitable)} SUID binaries with GTFOBins escalation paths.",- severity=Severity.CRITICAL,mitre_technique="T1548.001",mitre_tactic="Privilege Escalation",- evidence={"binaries":exploitable[:10]},remediation="Remove SUID bit: chmod u-s /path/to/binary.")- sudo_rules = raw.get("sudo",[])- if any("ALL" in l and "NOPASSWD" in l for l in sudo_rules):- self.finding(title="NOPASSWD Sudo — Immediate Root",description="Can run commands as root without password.",- severity=Severity.CRITICAL,mitre_technique="T1548.003",mitre_tactic="Privilege Escalation",- evidence={"rules":[l for l in sudo_rules if "NOPASSWD" in l][:5]},- remediation="Remove NOPASSWD from sudoers. Restrict sudo to specific commands.")- caps = raw.get("capabilities",[])- dangerous_caps = {"cap_setuid","cap_setgid","cap_sys_ptrace","cap_dac_override","cap_net_raw"}- found_caps = [{"binary":l.split()[0],"cap":c} for l in caps for c in dangerous_caps if c in l.lower()]+ severity=Severity.CRITICAL,+ mitre_technique="T1548.001",+ mitre_tactic="Privilege Escalation",+ evidence={"binaries": exploitable[:10]},+ remediation="Remove SUID bit: chmod u-s /path/to/binary.",+ )++ sudo_rules = raw.get("sudo", [])+ if any("ALL" in line and "NOPASSWD" in line for line in sudo_rules):+ self.finding(+ title="NOPASSWD Sudo — Immediate Root",+ description="Can run commands as root without password.",+ severity=Severity.CRITICAL,+ mitre_technique="T1548.003",+ mitre_tactic="Privilege Escalation",+ evidence={"rules": [line for line in sudo_rules if "NOPASSWD" in line][:5]},+ remediation="Remove NOPASSWD from sudoers. Restrict sudo to specific commands.",+ )++ caps = raw.get("capabilities", [])+ dangerous_caps = {"cap_setuid", "cap_setgid", "cap_sys_ptrace", "cap_dac_override", "cap_net_raw"}+ found_caps = [+ {"binary": line.split()[0], "cap": c}+ for line in caps+ for c in dangerous_caps+ if c in line.lower()+ ]if found_caps:- self.finding(title=f"Dangerous Linux Capabilities ({len(found_caps)})",+ self.finding(+ title=f"Dangerous Linux Capabilities ({len(found_caps)})",description="Binaries with dangerous capabilities can escalate to root.",- severity=Severity.HIGH,mitre_technique="T1548.001",mitre_tactic="Privilege Escalation",- evidence={"capabilities":found_caps},remediation="setcap -r /path/to/binary")- writable = raw.get("writable_path",[])+ severity=Severity.HIGH,+ mitre_technique="T1548.001",+ mitre_tactic="Privilege Escalation",+ evidence={"capabilities": found_caps},+ remediation="setcap -r /path/to/binary",+ )++ writable = raw.get("writable_path", [])if writable:- self.finding(title=f"Writable PATH Dirs ({len(writable)})",+ self.finding(+ title=f"Writable PATH Dirs ({len(writable)})",description="Current user can write to $PATH dirs — PATH hijacking possible.",- severity=Severity.HIGH,mitre_technique="T1574.006",mitre_tactic="Privilege Escalation",- evidence={"directories":writable},remediation="Remove write permissions from PATH directories.")+ severity=Severity.HIGH,+ mitre_technique="T1574.006",+ mitre_tactic="Privilege Escalation",+ evidence={"directories": writable},+ remediation="Remove write permissions from PATH directories.",+ )diff --git a/ares/modules/linux/service_hijack.py b/ares/modules/linux/service_hijack.pyindex 017c90c..a5a8492 100644--- a/ares/modules/linux/service_hijack.py+++ b/ares/modules/linux/service_hijack.py@@ -30,11 +30,24 @@ import reimport shlexfrom typing import Any-from ares.core.logger import get_loggerfrom ares.core.campaign import Finding, Severity+from ares.core.errors import ModuleValidationError+from ares.core.logger import get_loggerfrom ares.core.security import sanitize_hostname-from ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module+from ares.modules.params import ServiceHijackParams+from ares.sdk import (+ BaseModule,+ EvidenceRecord,+ ExecutionContext,+ LockoutCircuitBreaker,+ ModuleResult,+ NetworkPermission,+ OpsecLevel,+ ProcessPermission,+ UntrustedTargetData,+ module_contract,+)logger = get_logger("ares.modules.linux.service_hijack")@@ -86,9 +99,18 @@ def _parse_exec_start(unit_content: str) -> list[str]:return paths-class ServiceHijackModule(BaseModule):+@module_contract(+ permissions=[+ NetworkPermission(ports=[22], protocols=["tcp"]),+ ProcessPermission(allow_subprocesses=True, allowed_binaries=["/bin/bash", "sudo", "cat", "ls", "systemctl", "test"]),+ ],+ circuit_breaker=LockoutCircuitBreaker(),+ params_model=ServiceHijackParams,+)+class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):"""- linux.service_hijack — Detect systemd/init services with writable binaries or unit files — replacing the binary escalat+ linux.service_hijack — Detect systemd/init services with writable binaries or unit files —+ replacing the binary escalates privileges at next service restartOPSEC: LOWMITRE: "T1574.010", "T1082"@@ -106,27 +128,38 @@ class ServiceHijackModule(BaseModule):REQUIRES = []OUTPUTS = ["privesc_vectors"]MITRE_TECHNIQUES = ["T1574.010", "T1082"]+ PARAMS_MODEL = ServiceHijackParams- async def validate(self, ctx: "Any") -> None:- """Pre-flight param checks before any network call."""- await super().validate(ctx)+ async def validate(self, ctx: Any) -> None:+ """Pre-flight parameter checks before any network call."""from ares.core.context import ExecutionContext- from ares.core.errors import ModuleValidationError- if not isinstance(ctx, ExecutionContext):- return- target = getattr(ctx, "target", "") or ctx.params.get("target", "")- if not target:- raise ModuleValidationError(- f"{self.MODULE_ID} requires 'target' — IP or hostname.",- module_id=self.MODULE_ID, field="target",- )- ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")- if target != "localhost" and not ssh_user:- raise ModuleValidationError(- f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "- "Local controller fallback is prohibited.",- module_id=self.MODULE_ID, field="username",- )+ if isinstance(ctx, ExecutionContext):+ target = getattr(ctx, "target", "")+ if not target and hasattr(ctx, "params") and isinstance(ctx.params, dict):+ target = ctx.params.get("target") or ctx.params.get("host", "")+ if not target:+ raise ModuleValidationError(+ f"{self.MODULE_ID} requires 'target' — IP or hostname.",+ module_id=self.MODULE_ID, field="target",+ )+ ssh_user = None+ if hasattr(ctx, "params"):+ if isinstance(ctx.params, dict):+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ elif hasattr(ctx.params, "username"):+ ssh_user = getattr(ctx.params, "username", None) or getattr(ctx.params, "ssh_user", None)+ if target != "localhost" and not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "+ "Local controller fallback is prohibited.",+ module_id=self.MODULE_ID, field="username",+ )+ if isinstance(ctx.params, dict):+ if "target" not in ctx.params and target:+ ctx.params["target"] = target+ if "username" not in ctx.params and ssh_user:+ ctx.params["username"] = ssh_user+ await super().validate(ctx)async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -143,10 +176,53 @@ class ServiceHijackModule(BaseModule):status="dry_run", module_id=self.MODULE_ID,raw={"dry_run": True, "host": host},)++ params = getattr(ctx, "params", {})+ if isinstance(params, ServiceHijackParams):+ host = params.target or getattr(ctx, "target", "localhost")+ ssh_user = params.username+ ssh_key = params.key_path+ ssh_pass = params.password.get_secret_value() if params.password else None+ ssh_port = params.ssh_port+ elif isinstance(params, dict):+ host = params.get("target") or params.get("host") or getattr(ctx, "target", "localhost")+ ssh_user = params.get("username") or params.get("ssh_user")+ ssh_key = params.get("key_path") or params.get("ssh_key")+ raw_pass = params.get("password") or params.get("secret") or params.get("ssh_pass")+ ssh_pass = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else raw_pass+ ssh_port = int(params.get("ssh_port", 22))+ else:+ host = getattr(ctx, "target", "localhost")+ ssh_user = None+ ssh_key = None+ ssh_pass = None+ ssh_port = 22+findings, raw = await self.run(host=host, ssh_user=ssh_user, ssh_key=ssh_key,ssh_pass=ssh_pass, ssh_port=ssh_port,)++ # Cryptographic Evidence Records with SHA-256 Merkle Provenance+ evidence_chain: list[EvidenceRecord] = []+ for finding in findings:+ ev = EvidenceRecord(+ artifact_id=f"svchijack-{finding.title[:20].lower().replace(' ', '-')}",+ source_target=host,+ collected_by=self.MODULE_ID,+ data={+ "title": finding.title,+ "severity": str(finding.severity),+ "description": finding.description,+ "mitre": finding.mitre_technique,+ },+ tags=["linux", "service_hijack"],+ )+ evidence_chain.append(ev)++ raw["evidence_chain"] = [e.data for e in evidence_chain]+ raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]+return ModuleResult(status="success" if (findings or raw) else "partial",findings=findings, raw=raw, module_id=self.MODULE_ID,