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
fix(resource): close asyncssh connections in finally block - 4 Linux modules (MOD-037)
Mafifrizi6b040aab59dd
diff --git a/ares/modules/linux/ld_preload.py b/ares/modules/linux/ld_preload.pyindex bbe85c3..7ae8d2a 100644--- a/ares/modules/linux/ld_preload.py+++ b/ares/modules/linux/ld_preload.py@@ -250,12 +250,13 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):) -> tuple[list[Finding], dict[str, Any]]:is_remote = ssh_user is not None and host != "localhost"+ conn: Any = Noneif is_remote:host = sanitize_hostname(host)await self.before_request(host, "ssh")logger.info("ld_preload_start", host=host, mode="remote", user=ssh_user)- run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)+ conn, run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)elif host == "localhost":logger.info("ld_preload_start", host="localhost", mode="local")run_cmd = self._run_local@@ -263,232 +264,249 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):logger.error("ld_preload_rejected_remote_without_credentials", host=host)return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}- # Run checks in parallel- (- sudoers_out,- preload_file_out,- ld_conf_out,- suid_bins_out,- ) = await asyncio.gather(- run_cmd(_CMD_SUDOERS_LDPRELOAD),- run_cmd(_CMD_LD_PRELOAD_FILE),- run_cmd(_CMD_LD_CONF_PATHS),- run_cmd(_CMD_SUID_BINS),- return_exceptions=True,- )+ try:- def _safe(v: Any) -> str:- return v if isinstance(v, str) else ""-- sudoers_out = _safe(sudoers_out)- preload_file_out = _safe(preload_file_out)- ld_conf_out = _safe(ld_conf_out)- suid_bins_out = _safe(suid_bins_out)-- # ── Check 1: LD_PRELOAD in sudoers env_keep ────────────────────────- if sudoers_out and "ld_preload" in sudoers_out.lower():- self.finding(- title=f"LD_PRELOAD Preserved in Sudoers on {host}",- description=(- f"The sudoers configuration on {host} preserves the LD_PRELOAD "- "environment variable (env_keep += LD_PRELOAD). "- "An attacker can compile a malicious shared library, set "- "LD_PRELOAD to point to it, and run any command allowed by "- "sudo - causing the library to execute as the sudo target user "- "(often root) before the actual command runs."- ),- severity=Severity.CRITICAL,- mitre_technique="T1574.006",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "sudoers_output": sudoers_out[:300],- "exploitation": (- "1. Compile: gcc -shared -fPIC -o /tmp/evil.so evil.c. "- "2. Set: export LD_PRELOAD=/tmp/evil.so. "- "3. Run any allowed sudo command - evil.so executes as root."- ),- },- remediation=(- "Remove LD_PRELOAD from env_keep in /etc/sudoers. "- "Add 'Defaults env_reset' and 'Defaults!env_reset env_keep=' "- "to explicitly control preserved variables. "- "Use 'visudo' to edit sudoers safely."- ),- host=host, confidence=1.0,+ # Run checks in parallel+ (+ sudoers_out,+ preload_file_out,+ ld_conf_out,+ suid_bins_out,+ ) = await asyncio.gather(+ run_cmd(_CMD_SUDOERS_LDPRELOAD),+ run_cmd(_CMD_LD_PRELOAD_FILE),+ run_cmd(_CMD_LD_CONF_PATHS),+ run_cmd(_CMD_SUID_BINS),+ return_exceptions=True,)- # ── Check 2: Writable /etc/ld.so.preload ──────────────────────────- if preload_file_out:- # File exists - check if writable by current user- writable_preload = await run_cmd(- "[ -w /etc/ld.so.preload ] && echo writable || echo readonly"- ) if not isinstance(preload_file_out, Exception) else ""- writable_preload = writable_preload if isinstance(writable_preload, str) else ""+ def _safe(v: Any) -> str:+ return v if isinstance(v, str) else ""++ sudoers_out = _safe(sudoers_out)+ preload_file_out = _safe(preload_file_out)+ ld_conf_out = _safe(ld_conf_out)+ suid_bins_out = _safe(suid_bins_out)- if "writable" in writable_preload:+ # ── Check 1: LD_PRELOAD in sudoers env_keep ────────────────────────+ if sudoers_out and "ld_preload" in sudoers_out.lower():self.finding(- title=f"/etc/ld.so.preload is Writable on {host}",+ title=f"LD_PRELOAD Preserved in Sudoers on {host}",description=(- f"/etc/ld.so.preload exists and is writable on {host}. "- "This file forces the dynamic linker to preload listed "- "shared libraries for EVERY dynamically linked binary run "- "by any user, including root. "- "Writing a malicious .so path here achieves system-wide "- "code execution as any user running any binary."+ f"The sudoers configuration on {host} preserves the LD_PRELOAD "+ "environment variable (env_keep += LD_PRELOAD). "+ "An attacker can compile a malicious shared library, set "+ "LD_PRELOAD to point to it, and run any command allowed by "+ "sudo - causing the library to execute as the sudo target user "+ "(often root) before the actual command runs."),severity=Severity.CRITICAL,mitre_technique="T1574.006",mitre_tactic="Privilege Escalation",evidence={- "host": host,- "file": "/etc/ld.so.preload",- "current_contents": preload_file_out[:200],+ "host": host,+ "sudoers_output": sudoers_out[:300],"exploitation": (- "1. Compile malicious .so: gcc -shared -fPIC -o /tmp/evil.so evil.c. "- "2. Add to preload: echo '/tmp/evil.so' >> /etc/ld.so.preload. "- "3. Next time any privileged binary runs, evil.so executes first."+ "1. Compile: gcc -shared -fPIC -o /tmp/evil.so evil.c. "+ "2. Set: export LD_PRELOAD=/tmp/evil.so. "+ "3. Run any allowed sudo command - evil.so executes as root."),},remediation=(- "Set correct permissions on /etc/ld.so.preload: "- "chown root:root /etc/ld.so.preload && chmod 644 /etc/ld.so.preload. "- "Verify contents are expected. "- "Monitor this file with auditd: "- "-w /etc/ld.so.preload -p wa -k ld_preload"+ "Remove LD_PRELOAD from env_keep in /etc/sudoers. "+ "Add 'Defaults env_reset' and 'Defaults!env_reset env_keep=' "+ "to explicitly control preserved variables. "+ "Use 'visudo' to edit sudoers safely."),host=host, confidence=1.0,)- # ── Check 3: Writable directories in ld.so.conf ───────────────────- if ld_conf_out:- lib_dirs: list[str] = []- for line in ld_conf_out.splitlines():- line = line.strip()- if line and not line.startswith("#") and line.startswith("/"):- lib_dirs.append(line)-- writable_lib_dirs: list[str] = []- for ldir in lib_dirs[:20]: # check first 20- check = await run_cmd(- f"[ -d {shlex.quote(ldir)} ] && [ -w {shlex.quote(ldir)} ] && echo writable"+ # ── Check 2: Writable /etc/ld.so.preload ──────────────────────────+ if preload_file_out:+ # File exists - check if writable by current user+ writable_preload = await run_cmd(+ "[ -w /etc/ld.so.preload ] && echo writable || echo readonly"+ ) if not isinstance(preload_file_out, Exception) else ""+ writable_preload = writable_preload if isinstance(writable_preload, str) else ""++ if "writable" in writable_preload:+ self.finding(+ title=f"/etc/ld.so.preload is Writable on {host}",+ description=(+ f"/etc/ld.so.preload exists and is writable on {host}. "+ "This file forces the dynamic linker to preload listed "+ "shared libraries for EVERY dynamically linked binary run "+ "by any user, including root. "+ "Writing a malicious .so path here achieves system-wide "+ "code execution as any user running any binary."+ ),+ severity=Severity.CRITICAL,+ mitre_technique="T1574.006",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "file": "/etc/ld.so.preload",+ "current_contents": preload_file_out[:200],+ "exploitation": (+ "1. Compile malicious .so: gcc -shared -fPIC -o /tmp/evil.so evil.c. "+ "2. Add to preload: echo '/tmp/evil.so' >> /etc/ld.so.preload. "+ "3. Next time any privileged binary runs, evil.so executes first."+ ),+ },+ remediation=(+ "Set correct permissions on /etc/ld.so.preload: "+ "chown root:root /etc/ld.so.preload && chmod 644 /etc/ld.so.preload. "+ "Verify contents are expected. "+ "Monitor this file with auditd: "+ "-w /etc/ld.so.preload -p wa -k ld_preload"+ ),+ host=host, confidence=1.0,+ )++ # ── Check 3: Writable directories in ld.so.conf ───────────────────+ if ld_conf_out:+ lib_dirs: list[str] = []+ for line in ld_conf_out.splitlines():+ line = line.strip()+ if line and not line.startswith("#") and line.startswith("/"):+ lib_dirs.append(line)++ writable_lib_dirs: list[str] = []+ for ldir in lib_dirs[:20]: # check first 20+ check = await run_cmd(+ f"[ -d {shlex.quote(ldir)} ] && [ -w {shlex.quote(ldir)} ] && echo writable"+ )+ check = check if isinstance(check, str) else ""+ if "writable" in check:+ writable_lib_dirs.append(ldir)++ if writable_lib_dirs:+ self.finding(+ title=(+ f"Writable Library Path in ld.so.conf on {host} "+ f"({len(writable_lib_dirs)} dir(s))"+ ),+ description=(+ f"The following directories are listed in /etc/ld.so.conf "+ f"and are writable by the current user on {host}: "+ f"{', '.join(writable_lib_dirs)}. "+ "Placing a malicious .so with the same name as a real library "+ "in these directories will cause it to be loaded instead of "+ "the real library for any dynamically linked binary."+ ),+ severity=Severity.HIGH,+ mitre_technique="T1574.006",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "writable_dirs": writable_lib_dirs,+ "all_lib_dirs": lib_dirs[:10],+ },+ remediation=(+ "Remove write permissions from library directories: "+ "chmod 755 <dir> && chown root:root <dir>. "+ "Run ldconfig after any legitimate library change. "+ "Use AppArmor or SELinux to restrict library loading."+ ),+ host=host, confidence=0.95,+ )++ # ── Check 4: SUID binaries with writable RPATH ────────────────────+ suid_bins = [+ b.strip() for b in suid_bins_out.splitlines() if b.strip()+ ]+ writable_rpath_bins: list[dict[str, str]] = []++ for binary in suid_bins[:_RPATH_CHECK_DEPTH]:+ # Read RPATH/RUNPATH from the binary+ rpath_out = await run_cmd(+ f"readelf -d {shlex.quote(binary)} 2>/dev/null | "+ "grep -E '(RPATH|RUNPATH)'")- check = check if isinstance(check, str) else ""- if "writable" in check:- writable_lib_dirs.append(ldir)-- if writable_lib_dirs:+ rpath_out = rpath_out if isinstance(rpath_out, str) else ""+ if not rpath_out:+ continue++ # Extract paths from RPATH output+ # Typical: 0x000000000000000f (RPATH) Library rpath: [/opt/lib:/usr/local/lib]+ import re+ match = re.search(r'\[(.+?)\]', rpath_out)+ if not match:+ continue+ rpath_dirs = [d.strip() for d in match.group(1).split(":") if d.strip()]++ for rdir in rpath_dirs:+ writable = await run_cmd(+ f"[ -d {shlex.quote(rdir)} ] && [ -w {shlex.quote(rdir)} ] && echo writable"+ )+ writable = writable if isinstance(writable, str) else ""+ if "writable" in writable:+ writable_rpath_bins.append({+ "binary": binary,+ "rpath": match.group(1),+ "writable_dir": rdir,+ })++ if writable_rpath_bins:self.finding(title=(- f"Writable Library Path in ld.so.conf on {host} "- f"({len(writable_lib_dirs)} dir(s))"+ f"SUID Binary with Writable RPATH on {host} "+ f"({len(writable_rpath_bins)} binary/binaries)"),description=(- f"The following directories are listed in /etc/ld.so.conf "- f"and are writable by the current user on {host}: "- f"{', '.join(writable_lib_dirs)}. "- "Placing a malicious .so with the same name as a real library "- "in these directories will cause it to be loaded instead of "- "the real library for any dynamically linked binary."+ f"{len(writable_rpath_bins)} SUID binary/binaries on {host} "+ "have RPATH pointing to directories writable by the current user. "+ "By placing a malicious .so in the writable RPATH directory "+ "with the same name as a library the binary loads, "+ "the malicious library executes as the SUID binary owner (often root)."),- severity=Severity.HIGH,+ severity=Severity.CRITICAL,mitre_technique="T1574.006",mitre_tactic="Privilege Escalation",evidence={- "host": host,- "writable_dirs": writable_lib_dirs,- "all_lib_dirs": lib_dirs[:10],+ "host": host,+ "vectors": writable_rpath_bins,+ "exploitation": (+ "1. Run ldd <suid_binary> to find loaded libraries. "+ "2. Compile a fake version of one library as a shared object. "+ "3. Place it in the writable RPATH dir with the exact library name. "+ "4. Execute the SUID binary - your .so runs as root."+ ),},remediation=(- "Remove write permissions from library directories: "- "chmod 755 <dir> && chown root:root <dir>. "- "Run ldconfig after any legitimate library change. "- "Use AppArmor or SELinux to restrict library loading."+ "Recompile the binary without a hardcoded RPATH, or ensure "+ "RPATH only points to root-owned directories. "+ "Use patchelf --remove-rpath to strip RPATH. "+ "Verify with: readelf -d <binary> | grep -E '(RPATH|RUNPATH)'"),- host=host, confidence=0.95,- )-- # ── Check 4: SUID binaries with writable RPATH ────────────────────- suid_bins = [- b.strip() for b in suid_bins_out.splitlines() if b.strip()- ]- writable_rpath_bins: list[dict[str, str]] = []-- for binary in suid_bins[:_RPATH_CHECK_DEPTH]:- # Read RPATH/RUNPATH from the binary- rpath_out = await run_cmd(- f"readelf -d {shlex.quote(binary)} 2>/dev/null | "- "grep -E '(RPATH|RUNPATH)'"- )- rpath_out = rpath_out if isinstance(rpath_out, str) else ""- if not rpath_out:- continue-- # Extract paths from RPATH output- # Typical: 0x000000000000000f (RPATH) Library rpath: [/opt/lib:/usr/local/lib]- import re- match = re.search(r'\[(.+?)\]', rpath_out)- if not match:- continue- rpath_dirs = [d.strip() for d in match.group(1).split(":") if d.strip()]-- for rdir in rpath_dirs:- writable = await run_cmd(- f"[ -d {shlex.quote(rdir)} ] && [ -w {shlex.quote(rdir)} ] && echo writable"+ host=host, confidence=0.9,)- writable = writable if isinstance(writable, str) else ""- if "writable" in writable:- writable_rpath_bins.append({- "binary": binary,- "rpath": match.group(1),- "writable_dir": rdir,- })-- if writable_rpath_bins:- self.finding(- title=(- f"SUID Binary with Writable RPATH on {host} "- f"({len(writable_rpath_bins)} binary/binaries)"- ),- description=(- f"{len(writable_rpath_bins)} SUID binary/binaries on {host} "- "have RPATH pointing to directories writable by the current user. "- "By placing a malicious .so in the writable RPATH directory "- "with the same name as a library the binary loads, "- "the malicious library executes as the SUID binary owner (often root)."- ),- severity=Severity.CRITICAL,- mitre_technique="T1574.006",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "vectors": writable_rpath_bins,- "exploitation": (- "1. Run ldd <suid_binary> to find loaded libraries. "- "2. Compile a fake version of one library as a shared object. "- "3. Place it in the writable RPATH dir with the exact library name. "- "4. Execute the SUID binary - your .so runs as root."- ),- },- remediation=(- "Recompile the binary without a hardcoded RPATH, or ensure "- "RPATH only points to root-owned directories. "- "Use patchelf --remove-rpath to strip RPATH. "- "Verify with: readelf -d <binary> | grep -E '(RPATH|RUNPATH)'"- ),- host=host, confidence=0.9,- )- raw = {- "host": host,- "sudoers_ldpreload": sudoers_out,- "ld_so_preload": preload_file_out,- "ld_conf_dirs": ld_conf_out,- "suid_bins_checked": len(suid_bins[:_RPATH_CHECK_DEPTH]),- "writable_rpath_vectors": writable_rpath_bins,- }- raw["privesc_vectors"] = self._findings # OUTPUTS key- return self._findings[:], raw+ raw = {+ "host": host,+ "sudoers_ldpreload": sudoers_out,+ "ld_so_preload": preload_file_out,+ "ld_conf_dirs": ld_conf_out,+ "suid_bins_checked": len(suid_bins[:_RPATH_CHECK_DEPTH]),+ "writable_rpath_vectors": writable_rpath_bins,+ }+ raw["privesc_vectors"] = self._findings # OUTPUTS key+ return self._findings[:], raw+ finally:+ if conn is not None:+ try:+ close_fn = getattr(conn, "close", None)+ if callable(close_fn):+ res = close_fn()+ if asyncio.iscoroutine(res):+ await res+ wait_fn = getattr(conn, "wait_closed", None)+ if callable(wait_fn):+ res = wait_fn()+ if asyncio.iscoroutine(res):+ await res+ except Exception:+ pass# ── SSH / local runner helpers - identical pattern to linux.privesc ────@@ -529,7 +547,7 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):result = await conn.run(cmd, check=False)return (result.stdout or "").strip()- return ssh_run+ return conn, ssh_run@staticmethodasync def _run_local(cmd: str) -> str:diff --git a/ares/modules/linux/nfs_escape.py b/ares/modules/linux/nfs_escape.pyindex dec3c03..233cc41 100644--- a/ares/modules/linux/nfs_escape.py+++ b/ares/modules/linux/nfs_escape.py@@ -304,12 +304,13 @@ class NFSEscapeModule(BaseModule[NFSEscapeParams, ModuleResult]):) -> tuple[list[Finding], dict[str, Any]]:is_remote = ssh_user is not None and host != "localhost"+ conn: Any = Noneif is_remote:host = sanitize_hostname(host)await self.before_request(host, "ssh")logger.info("nfs_escape_start", host=host, mode="remote", user=ssh_user)- run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)+ conn, run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)elif host == "localhost":logger.info("nfs_escape_start", host="localhost", mode="local")run_cmd = self._run_local@@ -317,128 +318,145 @@ class NFSEscapeModule(BaseModule[NFSEscapeParams, ModuleResult]):logger.error("nfs_escape_rejected_remote_without_credentials", host=host)return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}- # Gather NFS data in parallel- exports_raw, mounts_raw, showmount_raw, nfs_conf_raw = await asyncio.gather(- run_cmd("cat /etc/exports 2>/dev/null"),- run_cmd("cat /proc/mounts 2>/dev/null | grep nfs"),- run_cmd("showmount -e localhost 2>/dev/null"),- run_cmd("cat /etc/nfs.conf 2>/dev/null | head -30"),- return_exceptions=True,- )+ try:++ # Gather NFS data in parallel+ exports_raw, mounts_raw, showmount_raw, nfs_conf_raw = await asyncio.gather(+ run_cmd("cat /etc/exports 2>/dev/null"),+ run_cmd("cat /proc/mounts 2>/dev/null | grep nfs"),+ run_cmd("showmount -e localhost 2>/dev/null"),+ run_cmd("cat /etc/nfs.conf 2>/dev/null | head -30"),+ return_exceptions=True,+ )- # Safely coerce exceptions to empty string- def _safe(v: Any) -> str:- return v if isinstance(v, str) else ""-- exports_raw = _safe(exports_raw)- mounts_raw = _safe(mounts_raw)- showmount_raw = _safe(showmount_raw)- nfs_conf_raw = _safe(nfs_conf_raw)-- entries = _parse_exports(exports_raw)-- # ── Analyse each export entry ──────────────────────────────────────- for entry in entries:- path = entry["path"]- clients = entry["clients"]-- for client in clients:- opts = [o.lower() for o in client.get("options", [])]- client_host = client.get("host", "*")- is_writable = "rw" in opts- no_root_squash = "no_root_squash" in opts- no_all_squash = "no_all_squash" in opts- insecure = "insecure" in opts-- if no_root_squash:- self.finding(- title=f"NFS no_root_squash on {path} (host={client_host})",- description=(- f"NFS export {path!r} on {host} is configured with "- f"no_root_squash for client {client_host!r}. "- "Any client connecting as root retains root privileges "- "on the share. "- + (- "The export is also writable (rw). "- "An attacker with root on a client machine can mount "- "this share and copy a SUID /bin/bash binary, then "- "execute it from a low-priv shell on the NFS server "- "to escalate to root."- if is_writable else- "The export is read-only - no_root_squash is less "- "immediately exploitable but still a misconfiguration."- )- ),- severity=Severity.CRITICAL if is_writable else Severity.HIGH,- mitre_technique="T1548.001",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "export_path": path,- "client": client_host,- "options": client.get("options", []),- "writable": is_writable,- "exploitation": (- f"1. Mount {path} on attacker machine as root. "- "2. Copy /bin/bash to the share and set SUID: "- "cp /bin/bash /mnt/share/ && chmod +s /mnt/share/bash. "- "3. On the NFS server (as low-priv user): "- f"/mnt_nfs{path}/bash -p (opens root shell)."- ) if is_writable else "read-only export - limited impact",- },- remediation=(- f"Remove no_root_squash from {path} export in /etc/exports. "- "Use root_squash (default) to map remote root to nfsnobody. "- "Restrict NFS exports to specific IP ranges, not wildcards. "- "Run: exportfs -ra after editing /etc/exports."- ),- host=host, confidence=1.0,- )-- elif no_all_squash:- self.finding(- title=f"NFS no_all_squash on {path} (host={client_host})",- description=(- f"NFS export {path!r} on {host} has no_all_squash for "- f"client {client_host!r}. "- "UIDs from the client are passed through to the server - "- "if the client has a UID matching a privileged user on "- "the server, it gains their access."- ),- severity=Severity.HIGH if is_writable else Severity.MEDIUM,- mitre_technique="T1548.001",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "export_path": path,- "client": client_host,- "options": client.get("options", []),- "writable": is_writable,- },- remediation=(- "Add all_squash to the export options to map all remote "- "UIDs to anonuid/anongid. "- "Example: /share *(rw,sync,all_squash,anonuid=65534,anongid=65534)"- ),- host=host, confidence=0.9,- )-- # ── Finding: NFS server running but no dangerous exports ───────────- nfs_running = bool(exports_raw.strip()) or bool(mounts_raw.strip())- if nfs_running and not self._findings:- logger.info("nfs_escape_no_dangerous_exports", host=host,- export_count=len(entries))-- raw = {- "host": host,- "exports_raw": exports_raw,- "exports_parsed": entries,- "nfs_mounts": mounts_raw,- "showmount": showmount_raw,- "nfs_conf": nfs_conf_raw,- }- raw["privesc_vectors"] = self._findings # OUTPUTS key- return self._findings[:], raw+ # Safely coerce exceptions to empty string+ def _safe(v: Any) -> str:+ return v if isinstance(v, str) else ""++ exports_raw = _safe(exports_raw)+ mounts_raw = _safe(mounts_raw)+ showmount_raw = _safe(showmount_raw)+ nfs_conf_raw = _safe(nfs_conf_raw)++ entries = _parse_exports(exports_raw)++ # ── Analyse each export entry ──────────────────────────────────────+ for entry in entries:+ path = entry["path"]+ clients = entry["clients"]++ for client in clients:+ opts = [o.lower() for o in client.get("options", [])]+ client_host = client.get("host", "*")+ is_writable = "rw" in opts+ no_root_squash = "no_root_squash" in opts+ no_all_squash = "no_all_squash" in opts+ insecure = "insecure" in opts++ if no_root_squash:+ self.finding(+ title=f"NFS no_root_squash on {path} (host={client_host})",+ description=(+ f"NFS export {path!r} on {host} is configured with "+ f"no_root_squash for client {client_host!r}. "+ "Any client connecting as root retains root privileges "+ "on the share. "+ + (+ "The export is also writable (rw). "+ "An attacker with root on a client machine can mount "+ "this share and copy a SUID /bin/bash binary, then "+ "execute it from a low-priv shell on the NFS server "+ "to escalate to root."+ if is_writable else+ "The export is read-only - no_root_squash is less "+ "immediately exploitable but still a misconfiguration."+ )+ ),+ severity=Severity.CRITICAL if is_writable else Severity.HIGH,+ mitre_technique="T1548.001",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "export_path": path,+ "client": client_host,+ "options": client.get("options", []),+ "writable": is_writable,+ "exploitation": (+ f"1. Mount {path} on attacker machine as root. "+ "2. Copy /bin/bash to the share and set SUID: "+ "cp /bin/bash /mnt/share/ && chmod +s /mnt/share/bash. "+ "3. On the NFS server (as low-priv user): "+ f"/mnt_nfs{path}/bash -p (opens root shell)."+ ) if is_writable else "read-only export - limited impact",+ },+ remediation=(+ f"Remove no_root_squash from {path} export in /etc/exports. "+ "Use root_squash (default) to map remote root to nfsnobody. "+ "Restrict NFS exports to specific IP ranges, not wildcards. "+ "Run: exportfs -ra after editing /etc/exports."+ ),+ host=host, confidence=1.0,+ )++ elif no_all_squash:+ self.finding(+ title=f"NFS no_all_squash on {path} (host={client_host})",+ description=(+ f"NFS export {path!r} on {host} has no_all_squash for "+ f"client {client_host!r}. "+ "UIDs from the client are passed through to the server - "+ "if the client has a UID matching a privileged user on "+ "the server, it gains their access."+ ),+ severity=Severity.HIGH if is_writable else Severity.MEDIUM,+ mitre_technique="T1548.001",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "export_path": path,+ "client": client_host,+ "options": client.get("options", []),+ "writable": is_writable,+ },+ remediation=(+ "Add all_squash to the export options to map all remote "+ "UIDs to anonuid/anongid. "+ "Example: /share *(rw,sync,all_squash,anonuid=65534,anongid=65534)"+ ),+ host=host, confidence=0.9,+ )++ # ── Finding: NFS server running but no dangerous exports ───────────+ nfs_running = bool(exports_raw.strip()) or bool(mounts_raw.strip())+ if nfs_running and not self._findings:+ logger.info("nfs_escape_no_dangerous_exports", host=host,+ export_count=len(entries))++ raw = {+ "host": host,+ "exports_raw": exports_raw,+ "exports_parsed": entries,+ "nfs_mounts": mounts_raw,+ "showmount": showmount_raw,+ "nfs_conf": nfs_conf_raw,+ }+ raw["privesc_vectors"] = self._findings # OUTPUTS key+ return self._findings[:], raw+ finally:+ if conn is not None:+ try:+ close_fn = getattr(conn, "close", None)+ if callable(close_fn):+ res = close_fn()+ if asyncio.iscoroutine(res):+ await res+ wait_fn = getattr(conn, "wait_closed", None)+ if callable(wait_fn):+ res = wait_fn()+ if asyncio.iscoroutine(res):+ await res+ except Exception:+ pass# ── SSH / local runner helpers - identical pattern to linux.privesc ────@@ -479,7 +497,7 @@ class NFSEscapeModule(BaseModule[NFSEscapeParams, ModuleResult]):result = await conn.run(cmd, check=False)return (result.stdout or "").strip()- return ssh_run+ return conn, ssh_run@staticmethodasync def _run_local(cmd: str) -> str:diff --git a/ares/modules/linux/privesc.py b/ares/modules/linux/privesc.pyindex 0333f6e..d0152fe 100644--- a/ares/modules/linux/privesc.py+++ b/ares/modules/linux/privesc.py@@ -232,46 +232,63 @@ class LinuxPrivescModule(BaseModule[LinuxPrivescParams, ModuleResult]):) -> tuple[list[Finding], dict[str, Any]]:self._target_host = hostis_remote = ssh_user is not None and host != "localhost"- if is_remote:- host = sanitize_hostname(host)- await self.before_request(host, "ssh")- logger.info("linux_privesc_start", host=host, mode="remote", user=ssh_user)- run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)- elif host == "localhost":- logger.info("linux_privesc_start", host="localhost", mode="local")- run_cmd = self._run_local- else:- 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[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))+ conn: Any = None+ try:+ if is_remote:+ host = sanitize_hostname(host)+ await self.before_request(host, "ssh")+ logger.info("linux_privesc_start", host=host, mode="remote", user=ssh_user)+ conn, run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)+ elif host == "localhost":+ logger.info("linux_privesc_start", host="localhost", mode="local")+ run_cmd = self._run_localelse:- # Wrap target output in UntrustedTargetData taint barrier- if isinstance(result, list):- raw[label] = [UntrustedTargetData(str(x), source=host).value for x in result]+ 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[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:- raw[label] = result-- self._analyze(raw)- logger.info("linux_privesc_done", host=host, findings=len(self._findings))- raw["privesc_vectors"] = self._findings- return self._findings, raw+ # 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+ return self._findings, raw+ finally:+ if conn is not None:+ try:+ close_fn = getattr(conn, "close", None)+ if callable(close_fn):+ res = close_fn()+ if asyncio.iscoroutine(res):+ await res+ wait_fn = getattr(conn, "wait_closed", None)+ if callable(wait_fn):+ res = wait_fn()+ if asyncio.iscoroutine(res):+ await res+ except Exception:+ passasync def _make_ssh_runner(self, host: str, user: str, key_path: str | None, password: str | None, port: int- ) -> Callable[[str], Awaitable[str]]:+ ) -> tuple[Any, Callable[[str], Awaitable[str]]]:try:import asyncsshexcept ImportError:@@ -296,7 +313,7 @@ class LinuxPrivescModule(BaseModule[LinuxPrivescParams, ModuleResult]):output = (result.stdout or "").strip()return UntrustedTargetData(output, source=host).value- return ssh_run+ return conn, ssh_run@staticmethodasync def _run_local(cmd: str) -> str:diff --git a/ares/modules/linux/service_hijack.py b/ares/modules/linux/service_hijack.pyindex 7357bc6..80c6790 100644--- a/ares/modules/linux/service_hijack.py+++ b/ares/modules/linux/service_hijack.py@@ -290,12 +290,13 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):) -> tuple[list[Finding], dict[str, Any]]:is_remote = ssh_user is not None and host != "localhost"+ conn: Any = Noneif is_remote:host = sanitize_hostname(host)await self.before_request(host, "ssh")logger.info("service_hijack_start", host=host, mode="remote", user=ssh_user)- run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)+ conn, run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)elif host == "localhost":logger.info("service_hijack_start", host="localhost", mode="local")run_cmd = self._run_local@@ -303,228 +304,245 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):logger.error("service_hijack_rejected_remote_without_credentials", host=host)return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}- # ── 1. Collect .service unit files ────────────────────────────────- find_cmd = (- "find "- + " ".join(f"'{d}'" for d in _SYSTEMD_DIRS)- + f" -name '*.service' -type f 2>/dev/null | head -{_MAX_SERVICES}"- )- unit_files_raw = await run_cmd(find_cmd)- unit_files_raw = unit_files_raw if isinstance(unit_files_raw, str) else ""- unit_files = [u.strip() for u in unit_files_raw.splitlines() if u.strip()]-- # Also collect init.d scripts- initd_raw = await run_cmd("ls /etc/init.d/ 2>/dev/null")- initd_raw = initd_raw if isinstance(initd_raw, str) else ""- initd_scripts = [- f"/etc/init.d/{s.strip()}"- for s in initd_raw.splitlines()- if s.strip() and not s.strip().startswith(".")- ]-- writable_binaries: list[dict[str, str]] = []- writable_unit_files: list[dict[str, str]] = []- suspicious_paths: list[dict[str, str]] = []- checked = 0-- # ── 2. Check each systemd unit file ───────────────────────────────- for unit_path in unit_files:- if checked >= _MAX_SERVICES:- break- checked += 1-- # Read unit file content- content = await run_cmd(f"cat {shlex.quote(unit_path)} 2>/dev/null")- content = content if isinstance(content, str) else ""- if not content:- continue-- # Check if the unit file itself is writable- unit_writable = await run_cmd(- f"[ -w {shlex.quote(unit_path)} ] && echo writable"+ try:++ # ── 1. Collect .service unit files ────────────────────────────────+ find_cmd = (+ "find "+ + " ".join(f"'{d}'" for d in _SYSTEMD_DIRS)+ + f" -name '*.service' -type f 2>/dev/null | head -{_MAX_SERVICES}")- unit_writable = unit_writable if isinstance(unit_writable, str) else ""- if "writable" in unit_writable:- writable_unit_files.append({- "unit": unit_path,- "reason": "Unit file writable - modify ExecStart to run arbitrary command",- })-- # Extract ExecStart paths and check writability- exec_paths = _parse_exec_start(content)- for binary in exec_paths:- # Check for user-writable temp/home paths- if any(binary.startswith(p) for p in _USER_WRITABLE_PATHS):- # Extract User= line to determine service privilege level- user_match = re.search(r'^User=(.+)$', content, re.MULTILINE)- service_user = user_match.group(1).strip() if user_match else "root"- suspicious_paths.append({- "unit": unit_path,- "binary": binary,- "runs_as": service_user,- })+ unit_files_raw = await run_cmd(find_cmd)+ unit_files_raw = unit_files_raw if isinstance(unit_files_raw, str) else ""+ unit_files = [u.strip() for u in unit_files_raw.splitlines() if u.strip()]++ # Also collect init.d scripts+ initd_raw = await run_cmd("ls /etc/init.d/ 2>/dev/null")+ initd_raw = initd_raw if isinstance(initd_raw, str) else ""+ initd_scripts = [+ f"/etc/init.d/{s.strip()}"+ for s in initd_raw.splitlines()+ if s.strip() and not s.strip().startswith(".")+ ]++ writable_binaries: list[dict[str, str]] = []+ writable_unit_files: list[dict[str, str]] = []+ suspicious_paths: list[dict[str, str]] = []+ checked = 0++ # ── 2. Check each systemd unit file ───────────────────────────────+ for unit_path in unit_files:+ if checked >= _MAX_SERVICES:+ break+ checked += 1++ # Read unit file content+ content = await run_cmd(f"cat {shlex.quote(unit_path)} 2>/dev/null")+ content = content if isinstance(content, str) else ""+ if not content:continue- # Check if binary is writable- bin_writable = await run_cmd(- f"[ -f {shlex.quote(binary)} ] && [ -w {shlex.quote(binary)} ] && echo writable"+ # Check if the unit file itself is writable+ unit_writable = await run_cmd(+ f"[ -w {shlex.quote(unit_path)} ] && echo writable")- bin_writable = bin_writable if isinstance(bin_writable, str) else ""- if "writable" in bin_writable:- user_match = re.search(r'^User=(.+)$', content, re.MULTILINE)- service_user = user_match.group(1).strip() if user_match else "root"- writable_binaries.append({- "unit": unit_path,- "binary": binary,- "runs_as": service_user,+ unit_writable = unit_writable if isinstance(unit_writable, str) else ""+ if "writable" in unit_writable:+ writable_unit_files.append({+ "unit": unit_path,+ "reason": "Unit file writable - modify ExecStart to run arbitrary command",})- await self.noise.jitter.sleep()- # ── 3. Check init.d scripts for writability ────────────────────────- writable_initd: list[str] = []- for script in initd_scripts[:20]:- check = await run_cmd(- f"[ -f {shlex.quote(script)} ] && [ -w {shlex.quote(script)} ] && echo writable"- )- check = check if isinstance(check, str) else ""- if "writable" in check:- writable_initd.append(script)-- # ── Generate findings ──────────────────────────────────────────────-- if writable_binaries:- self.finding(- title=(- f"Service Binary Writable on {host} "- f"({len(writable_binaries)} service(s))"- ),- description=(- f"{len(writable_binaries)} service binary/binaries are writable "- f"by the current user on {host}. "- "Replacing a service binary with a malicious executable "- "will run it under the service's privilege level "- "(usually root) at the next service restart or system reboot."- ),- severity=Severity.CRITICAL,- mitre_technique="T1574.010",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "vectors": writable_binaries,- "exploitation": (- "1. Backup original binary: cp <binary> /tmp/original. "- "2. Replace with payload: cp /tmp/payload <binary>. "- "3. Wait for service restart or reboot. "- "4. Payload executes under service user context."+ # Extract ExecStart paths and check writability+ exec_paths = _parse_exec_start(content)+ for binary in exec_paths:+ # Check for user-writable temp/home paths+ if any(binary.startswith(p) for p in _USER_WRITABLE_PATHS):+ # Extract User= line to determine service privilege level+ user_match = re.search(r'^User=(.+)$', content, re.MULTILINE)+ service_user = user_match.group(1).strip() if user_match else "root"+ suspicious_paths.append({+ "unit": unit_path,+ "binary": binary,+ "runs_as": service_user,+ })+ continue++ # Check if binary is writable+ bin_writable = await run_cmd(+ f"[ -f {shlex.quote(binary)} ] && [ -w {shlex.quote(binary)} ] && echo writable"+ )+ bin_writable = bin_writable if isinstance(bin_writable, str) else ""+ if "writable" in bin_writable:+ user_match = re.search(r'^User=(.+)$', content, re.MULTILINE)+ service_user = user_match.group(1).strip() if user_match else "root"+ writable_binaries.append({+ "unit": unit_path,+ "binary": binary,+ "runs_as": service_user,+ })+ await self.noise.jitter.sleep()++ # ── 3. Check init.d scripts for writability ────────────────────────+ writable_initd: list[str] = []+ for script in initd_scripts[:20]:+ check = await run_cmd(+ f"[ -f {shlex.quote(script)} ] && [ -w {shlex.quote(script)} ] && echo writable"+ )+ check = check if isinstance(check, str) else ""+ if "writable" in check:+ writable_initd.append(script)++ # ── Generate findings ──────────────────────────────────────────────++ if writable_binaries:+ self.finding(+ title=(+ f"Service Binary Writable on {host} "+ f"({len(writable_binaries)} service(s))"),- },- remediation=(- "Fix binary permissions: chown root:root <binary> && chmod 755 <binary>. "- "Audit service binaries regularly: "- "find /usr /opt -name '*.service' -exec grep ExecStart= {} \\; "- "| awk '{print $2}' | xargs ls -la. "- "Use systemd's ProtectSystem=strict to prevent runtime modification."- ),- host=host, confidence=1.0,- )+ description=(+ f"{len(writable_binaries)} service binary/binaries are writable "+ f"by the current user on {host}. "+ "Replacing a service binary with a malicious executable "+ "will run it under the service's privilege level "+ "(usually root) at the next service restart or system reboot."+ ),+ severity=Severity.CRITICAL,+ mitre_technique="T1574.010",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "vectors": writable_binaries,+ "exploitation": (+ "1. Backup original binary: cp <binary> /tmp/original. "+ "2. Replace with payload: cp /tmp/payload <binary>. "+ "3. Wait for service restart or reboot. "+ "4. Payload executes under service user context."+ ),+ },+ remediation=(+ "Fix binary permissions: chown root:root <binary> && chmod 755 <binary>. "+ "Audit service binaries regularly: "+ "find /usr /opt -name '*.service' -exec grep ExecStart= {} \\; "+ "| awk '{print $2}' | xargs ls -la. "+ "Use systemd's ProtectSystem=strict to prevent runtime modification."+ ),+ host=host, confidence=1.0,+ )- if writable_unit_files:- self.finding(- title=(- f"Writable systemd Unit Files on {host} "- f"({len(writable_unit_files)} file(s))"- ),- description=(- f"{len(writable_unit_files)} systemd unit file(s) on {host} "- "are writable by the current user. "- "Modifying the ExecStart= directive and reloading systemd "- "achieves code execution under that service's user context."- ),- severity=Severity.HIGH,- mitre_technique="T1574.010",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "unit_files": writable_unit_files,- "exploitation": (- "1. Edit unit file ExecStart=/tmp/payload. "- "2. Run: systemctl daemon-reload && systemctl restart <service>. "- "3. Payload runs as the service's User= account."+ if writable_unit_files:+ self.finding(+ title=(+ f"Writable systemd Unit Files on {host} "+ f"({len(writable_unit_files)} file(s))"),- },- remediation=(- "Fix unit file permissions: chmod 644 <unit_file>. "- "Only root should write systemd unit files. "- "Monitor unit file changes with auditd: "- "-w /etc/systemd/system -p wa -k systemd_unit_change"- ),- host=host, confidence=1.0,- )+ description=(+ f"{len(writable_unit_files)} systemd unit file(s) on {host} "+ "are writable by the current user. "+ "Modifying the ExecStart= directive and reloading systemd "+ "achieves code execution under that service's user context."+ ),+ severity=Severity.HIGH,+ mitre_technique="T1574.010",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "unit_files": writable_unit_files,+ "exploitation": (+ "1. Edit unit file ExecStart=/tmp/payload. "+ "2. Run: systemctl daemon-reload && systemctl restart <service>. "+ "3. Payload runs as the service's User= account."+ ),+ },+ remediation=(+ "Fix unit file permissions: chmod 644 <unit_file>. "+ "Only root should write systemd unit files. "+ "Monitor unit file changes with auditd: "+ "-w /etc/systemd/system -p wa -k systemd_unit_change"+ ),+ host=host, confidence=1.0,+ )- if suspicious_paths:- self.finding(- title=(- f"Services with Binaries in User-Writable Paths on {host} "- f"({len(suspicious_paths)} service(s))"- ),- description=(- f"{len(suspicious_paths)} service(s) on {host} execute binaries "- "from user-writable directories (/tmp, /home, /var/tmp, /dev/shm). "- "These paths are trivially writable by unprivileged users - "- "placing a file with the expected name in these directories "- "causes the service to execute it."- ),- severity=Severity.HIGH,- mitre_technique="T1574.010",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "vectors": suspicious_paths,- },- remediation=(- "Move service binaries to protected system directories "- "(e.g. /usr/local/bin or /opt/<service>/bin). "- "Never run services from /tmp or user home directories."- ),- host=host, confidence=0.95,- )+ if suspicious_paths:+ self.finding(+ title=(+ f"Services with Binaries in User-Writable Paths on {host} "+ f"({len(suspicious_paths)} service(s))"+ ),+ description=(+ f"{len(suspicious_paths)} service(s) on {host} execute binaries "+ "from user-writable directories (/tmp, /home, /var/tmp, /dev/shm). "+ "These paths are trivially writable by unprivileged users - "+ "placing a file with the expected name in these directories "+ "causes the service to execute it."+ ),+ severity=Severity.HIGH,+ mitre_technique="T1574.010",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "vectors": suspicious_paths,+ },+ remediation=(+ "Move service binaries to protected system directories "+ "(e.g. /usr/local/bin or /opt/<service>/bin). "+ "Never run services from /tmp or user home directories."+ ),+ host=host, confidence=0.95,+ )- if writable_initd:- self.finding(- title=(- f"Writable SysV Init Scripts on {host} "- f"({len(writable_initd)} script(s))"- ),- description=(- f"{len(writable_initd)} SysV init script(s) in /etc/init.d/ "- f"are writable on {host}: {', '.join(writable_initd[:5])}. "- "These scripts run as root at boot time and during service "- "start/stop operations."- ),- severity=Severity.HIGH,- mitre_technique="T1574.010",- mitre_tactic="Privilege Escalation",- evidence={- "host": host,- "scripts": writable_initd,- },- remediation=(- "Fix permissions: chmod 755 /etc/init.d/<script> && "- "chown root:root /etc/init.d/<script>."- ),- host=host, confidence=1.0,- )+ if writable_initd:+ self.finding(+ title=(+ f"Writable SysV Init Scripts on {host} "+ f"({len(writable_initd)} script(s))"+ ),+ description=(+ f"{len(writable_initd)} SysV init script(s) in /etc/init.d/ "+ f"are writable on {host}: {', '.join(writable_initd[:5])}. "+ "These scripts run as root at boot time and during service "+ "start/stop operations."+ ),+ severity=Severity.HIGH,+ mitre_technique="T1574.010",+ mitre_tactic="Privilege Escalation",+ evidence={+ "host": host,+ "scripts": writable_initd,+ },+ remediation=(+ "Fix permissions: chmod 755 /etc/init.d/<script> && "+ "chown root:root /etc/init.d/<script>."+ ),+ host=host, confidence=1.0,+ )- raw = {- "host": host,- "units_checked": checked,- "writable_binaries": writable_binaries,- "writable_unit_files": writable_unit_files,- "suspicious_paths": suspicious_paths,- "writable_initd": writable_initd,- }- raw["privesc_vectors"] = self._findings # OUTPUTS key- return self._findings[:], raw+ raw = {+ "host": host,+ "units_checked": checked,+ "writable_binaries": writable_binaries,+ "writable_unit_files": writable_unit_files,+ "suspicious_paths": suspicious_paths,+ "writable_initd": writable_initd,+ }+ raw["privesc_vectors"] = self._findings # OUTPUTS key+ return self._findings[:], raw+ finally:+ if conn is not None:+ try:+ close_fn = getattr(conn, "close", None)+ if callable(close_fn):+ res = close_fn()+ if asyncio.iscoroutine(res):+ await res+ wait_fn = getattr(conn, "wait_closed", None)+ if callable(wait_fn):+ res = wait_fn()+ if asyncio.iscoroutine(res):+ await res+ except Exception:+ pass# ── SSH / local runner helpers - identical pattern to linux.privesc ────@@ -565,7 +583,7 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):result = await conn.run(cmd, check=False)return (result.stdout or "").strip()- return ssh_run+ return conn, ssh_run@staticmethodasync def _run_local(cmd: str) -> str:diff --git a/tests/unit/modules/test_mod037_ssh_teardown.py b/tests/unit/modules/test_mod037_ssh_teardown.pynew file mode 100644index 0000000..a156abb--- /dev/null+++ b/tests/unit/modules/test_mod037_ssh_teardown.py@@ -0,0 +1,114 @@+"""+Tests for MOD-037: SSH Connection Leak in 4 Linux Modules.+Ensures asyncssh connections are closed in finally block across:+- ares.modules.linux.privesc (LinuxPrivescModule)+- ares.modules.linux.service_hijack (ServiceHijackModule)+- ares.modules.linux.ld_preload (LDPreloadModule)+- ares.modules.linux.nfs_escape (NFSEscapeModule)+"""+from __future__ import annotations++import asyncio+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.errors import HostUnreachable+from ares.core.noise import NoiseController+from ares.modules.linux.ld_preload import LDPreloadModule+from ares.modules.linux.nfs_escape import NFSEscapeModule+from ares.modules.linux.privesc import LinuxPrivescModule+from ares.modules.linux.service_hijack import ServiceHijackModule+++MODULE_CLASSES = [+ LinuxPrivescModule,+ ServiceHijackModule,+ LDPreloadModule,+ NFSEscapeModule,+]+++def _make_module(cls: type) -> tuple:+ settings = AresSettings(+ ares_secret_key="test-secret-key-32chars-minimum!!",+ ares_encryption_key="test-encryption-key-32chars-min!!",+ )+ campaign = Campaign(+ name="MOD-037-Test",+ scope=[ScopeEntry(cidr="10.0.0.0/8")],+ noise_profile=NoiseProfile("normal"),+ )+ noise = NoiseController(campaign)+ module = cls(settings=settings, campaign=campaign, noise=noise)+ return module, campaign++[email protected]("mod_cls", MODULE_CLASSES)+async def test_ssh_connection_closed_on_normal_execution(mod_cls):+ """Test: koneksi asyncssh ditutup setelah eksekusi normal selesai."""+ module, _ = _make_module(mod_cls)++ mock_conn = MagicMock()+ mock_conn.close = MagicMock()+ mock_conn.wait_closed = AsyncMock()++ mock_result = MagicMock()+ mock_result.stdout = ""+ mock_conn.run = AsyncMock(return_value=mock_result)++ with patch.dict("sys.modules", {"asyncssh": MagicMock(connect=AsyncMock(return_value=mock_conn))}):+ findings, raw = await module.run(+ host="10.0.0.5",+ ssh_user="testuser",+ ssh_pass="secret123",+ )++ assert mock_conn.close.called, f"{mod_cls.__name__} did not call conn.close() on normal completion"++[email protected]("mod_cls", MODULE_CLASSES)+async def test_ssh_connection_closed_on_mid_operation_exception(mod_cls):+ """Test: koneksi asyncssh ditutup kalau exception terjadi di tengah operasi."""+ module, _ = _make_module(mod_cls)++ mock_conn = MagicMock()+ mock_conn.close = MagicMock()+ mock_conn.wait_closed = AsyncMock()++ # Raise an exception when running commands over SSH+ mock_conn.run = AsyncMock(side_effect=RuntimeError("Simulated mid-operation network crash"))++ with patch.dict("sys.modules", {"asyncssh": MagicMock(connect=AsyncMock(return_value=mock_conn))}):+ try:+ await module.run(+ host="10.0.0.5",+ ssh_user="testuser",+ ssh_pass="secret123",+ )+ except Exception:+ pass # Some modules catch exceptions in gather, others re-raise++ assert mock_conn.close.called, f"{mod_cls.__name__} did not call conn.close() when exception occurred"++[email protected]("mod_cls", MODULE_CLASSES)+async def test_ssh_connection_closed_on_unreachable_target(mod_cls):+ """Test: kalau target unreachable (exception di connect sendiri), finally tetap aman."""+ module, _ = _make_module(mod_cls)++ mock_asyncssh = MagicMock()+ mock_asyncssh.connect = AsyncMock(side_effect=OSError("Connection refused to target"))++ with patch.dict("sys.modules", {"asyncssh": mock_asyncssh}):+ with pytest.raises(HostUnreachable):+ await module.run(+ host="10.0.0.5",+ ssh_user="testuser",+ ssh_pass="secret123",+ )