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(linux): modernize linux modules to pure-python & fix target delegation bugs
Mafifrizif12960d4e061
diff --git a/ares/modules/linux/_parsers.py b/ares/modules/linux/_parsers.pyindex 95c65b5..218dc4d 100644--- a/ares/modules/linux/_parsers.py+++ b/ares/modules/linux/_parsers.py@@ -1025,3 +1025,334 @@ def compute_ntlm_hash(password: str) -> str:"""return pure_md4(password.encode("utf-16le")).hex()++# ─────────────────────────────────────────────────────────────────────────────+# 6. Pure-Python ELF Binary Parser (RPATH / RUNPATH Extraction)+# ─────────────────────────────────────────────────────────────────────────────++class ELFParser:+ """+ Pure Python parser for ELF binaries (32-bit and 64-bit, Little & Big Endian).+ Extracts DT_RPATH and DT_RUNPATH without spawning /usr/bin/readelf or ldd.+ """++ @classmethod+ def parse_rpath_file(cls, path: str) -> list[str]:+ """Reads file header and dynamic section to find RPATH/RUNPATH directories."""+ try:+ with open(path, "rb") as f:+ data = f.read(1024 * 1024) # Read first 1MB (covers headers & dynamic table)+ return cls.parse_rpath_bytes(data)+ except Exception:+ return []++ @classmethod+ def parse_rpath_bytes(cls, data: bytes) -> list[str]:+ """+ Parses ELF bytes, discovers PT_DYNAMIC segment and SHT_STRTAB / DT_STRTAB,+ and returns list of RPATH / RUNPATH directory strings.+ """+ if len(data) < 52 or not data.startswith(b"\x7fELF"):+ return []++ ei_class = data[4] # 1 = 32-bit, 2 = 64-bit+ ei_data = data[5] # 1 = Little Endian, 2 = Big Endian+ endian = "<" if ei_data == 1 else ">"++ if ei_class not in (1, 2):+ return []++ is_64 = (ei_class == 2)+ try:+ if is_64:+ if len(data) < 64:+ return []+ # Elf64_Ehdr+ _, _, _, _, _, e_phoff, e_shoff, _, _, e_phentsize, e_phnum, e_shentsize, e_shnum, _ = struct.unpack(+ f"{endian}16sHHIQQQIHHHHHH", data[:64]+ )+ else:+ # Elf32_Ehdr+ _, _, _, _, _, e_phoff, e_shoff, _, _, e_phentsize, e_phnum, e_shentsize, e_shnum, _ = struct.unpack(+ f"{endian}16sHHIIIIIHHHHHH", data[:52]+ )+ except struct.error:+ return []++ # Find PT_DYNAMIC (p_type == 2) and PT_LOAD headers+ dyn_offset = 0+ dyn_size = 0+ dyn_vaddr = 0+ load_segments: list[tuple[int, int, int]] = [] # (vaddr, offset, filesz)++ for i in range(e_phnum):+ ph_start = e_phoff + i * e_phentsize+ if is_64:+ if ph_start + 56 > len(data):+ break+ p_type, _, p_offset, p_vaddr, _, p_filesz, _, _ = struct.unpack(+ f"{endian}IIQQQQQQ", data[ph_start : ph_start + 56]+ )+ else:+ if ph_start + 32 > len(data):+ break+ p_type, p_offset, p_vaddr, _, p_filesz, _, _, _ = struct.unpack(+ f"{endian}IIIIIIII", data[ph_start : ph_start + 32]+ )++ if p_type == 1: # PT_LOAD+ load_segments.append((p_vaddr, p_offset, p_filesz))+ elif p_type == 2: # PT_DYNAMIC+ dyn_offset = p_offset+ dyn_size = p_filesz+ dyn_vaddr = p_vaddr++ if not dyn_offset or dyn_offset >= len(data):+ return []++ # Parse Elf_Dyn entries in PT_DYNAMIC+ dyn_bytes = data[dyn_offset : dyn_offset + dyn_size]+ strtab_val = 0+ rpath_offsets: list[int] = []++ entry_size = 16 if is_64 else 8+ fmt = f"{endian}QQ" if is_64 else f"{endian}II"++ for i in range(0, len(dyn_bytes) - entry_size + 1, entry_size):+ try:+ d_tag, d_val = struct.unpack(fmt, dyn_bytes[i : i + entry_size])+ except struct.error:+ break+ if d_tag == 0: # DT_NULL+ break+ elif d_tag == 5: # DT_STRTAB+ strtab_val = d_val+ elif d_tag in (15, 29): # DT_RPATH (15) or DT_RUNPATH (29)+ rpath_offsets.append(d_val)++ if not rpath_offsets:+ return []++ # Resolve strtab offset in binary data+ strtab_offset = 0++ # Method A: Direct address check in binary+ if 0 < strtab_val < len(data):+ # Check if strtab_val is directly a file offset+ strtab_offset = strtab_val++ # Method B: Map virtual address via PT_LOAD+ if not strtab_offset:+ for vaddr, offset, filesz in load_segments:+ if vaddr <= strtab_val < vaddr + filesz:+ strtab_offset = offset + (strtab_val - vaddr)+ break++ # Method C: Check section headers for SHT_DYNAMIC (sh_type == 6) and its sh_link+ if not strtab_offset and e_shoff > 0 and e_shnum > 0:+ sh_entry_size = e_shentsize+ dyn_sh_link = -1+ for s in range(e_shnum):+ sh_start = e_shoff + s * sh_entry_size+ if is_64:+ if sh_start + 64 > len(data):+ break+ _, sh_type, _, _, _, _, sh_link, _, _, _ = struct.unpack(+ f"{endian}IIQQQQIIQQ", data[sh_start : sh_start + 64]+ )+ else:+ if sh_start + 40 > len(data):+ break+ _, sh_type, _, _, _, _, sh_link, _, _, _ = struct.unpack(+ f"{endian}IIIIIIIIII", data[sh_start : sh_start + 40]+ )+ if sh_type == 6: # SHT_DYNAMIC+ dyn_sh_link = sh_link+ break++ if 0 <= dyn_sh_link < e_shnum:+ strtab_sh_start = e_shoff + dyn_sh_link * sh_entry_size+ if is_64 and strtab_sh_start + 64 <= len(data):+ _, _, _, _, sh_offset, _, _, _, _, _ = struct.unpack(+ f"{endian}IIQQQQIIQQ", data[strtab_sh_start : strtab_sh_start + 64]+ )+ strtab_offset = sh_offset+ elif not is_64 and strtab_sh_start + 40 <= len(data):+ _, _, _, _, sh_offset, _, _, _, _, _ = struct.unpack(+ f"{endian}IIIIIIIIII", data[strtab_sh_start : strtab_sh_start + 40]+ )+ strtab_offset = sh_offset++ if not strtab_offset or strtab_offset >= len(data):+ return []++ # Extract RPATH strings from strtab+ result: list[str] = []+ for r_off in rpath_offsets:+ abs_str_offset = strtab_offset + r_off+ if abs_str_offset >= len(data):+ continue+ null_pos = data.find(b"\x00", abs_str_offset)+ if null_pos != -1:+ rpath_str = data[abs_str_offset:null_pos].decode("utf-8", errors="replace").strip()+ else:+ rpath_str = data[abs_str_offset:abs_str_offset + 512].decode("utf-8", errors="replace").strip()+ if rpath_str:+ for part in rpath_str.split(":"):+ p = part.strip()+ if p and p not in result:+ result.append(p)++ return result+++# ─────────────────────────────────────────────────────────────────────────────+# 7. Pure-Python Linux Capability Decoder (security.capability / vfs_cap_data)+# ─────────────────────────────────────────────────────────────────────────────++_LINUX_CAP_NAMES: dict[int, str] = {+ 0: "cap_chown",+ 1: "cap_dac_override",+ 2: "cap_dac_read_search",+ 3: "cap_fowner",+ 4: "cap_fsetid",+ 5: "cap_kill",+ 6: "cap_setgid",+ 7: "cap_setuid",+ 8: "cap_setpcap",+ 9: "cap_linux_immutable",+ 10: "cap_net_bind_service",+ 11: "cap_net_broadcast",+ 12: "cap_net_admin",+ 13: "cap_net_raw",+ 14: "cap_ipc_lock",+ 15: "cap_ipc_owner",+ 16: "cap_sys_module",+ 17: "cap_sys_rawio",+ 18: "cap_sys_chroot",+ 19: "cap_sys_ptrace",+ 20: "cap_sys_pacct",+ 21: "cap_sys_admin",+ 22: "cap_sys_boot",+ 23: "cap_sys_nice",+ 24: "cap_sys_resource",+ 25: "cap_sys_time",+ 26: "cap_sys_tty_config",+ 27: "cap_mknod",+ 28: "cap_lease",+ 29: "cap_audit_write",+ 30: "cap_audit_control",+ 31: "cap_setfcap",+ 32: "cap_mac_override",+ 33: "cap_mac_admin",+ 34: "cap_syslog",+ 35: "cap_wake_alarm",+ 36: "cap_block_suspend",+ 37: "cap_audit_read",+ 38: "cap_perfmon",+ 39: "cap_bpf",+ 40: "cap_checkpoint_restore",+}+++class LinuxCapParser:+ """+ Pure Python decoder for Linux security.capability xattr structures (vfs_cap_data).+ Decodes effective/permitted capabilities without invoking /sbin/getcap.+ """++ @classmethod+ def get_file_capabilities(cls, path: str) -> list[str]:+ """Reads security.capability extended attribute via os.getxattr if supported."""+ if not hasattr(os, "getxattr"):+ return []+ try:+ cap_data = os.getxattr(path, "security.capability") # type: ignore[attr-defined]+ return cls.decode_capability_bytes(cap_data)+ except (OSError, ValueError):+ return []++ @classmethod+ def decode_capability_bytes(cls, data: bytes) -> list[str]:+ """+ Decodes raw bytes of Linux vfs_cap_data / vfs_ns_cap_data structure.+ Supports VFS_CAP_REVISION_1 (32-bit), VFS_CAP_REVISION_2 (64-bit), and VFS_CAP_REVISION_3.+ """+ if len(data) < 12:+ return []++ # Determine endianness from magic+ # Magic is stored in lower/upper byte of magic_etc+ endian = "<" # Linux xattrs on disk are little-endian+ try:+ magic_etc = struct.unpack(f"{endian}I", data[:4])[0]+ except struct.error:+ return []++ rev = magic_etc & 0xFF000000+ permitted_64 = 0++ if rev in (0x02000000, 0x03000000) and len(data) >= 20:+ # VFS_CAP_REVISION_2 or 3: 2 uint32 pairs (permitted, inheritable)+ try:+ _, p0, _, p1, _ = struct.unpack(f"{endian}5I", data[:20])+ permitted_64 = (p0 & 0xFFFFFFFF) | ((p1 & 0xFFFFFFFF) << 32)+ except struct.error:+ return []+ elif rev == 0x01000000 and len(data) >= 12:+ # VFS_CAP_REVISION_1: 1 uint32 pair (permitted, inheritable)+ try:+ _, p0, _ = struct.unpack(f"{endian}3I", data[:12])+ permitted_64 = p0 & 0xFFFFFFFF+ except struct.error:+ return []+ else:+ # Fallback: try reading first 2 words+ try:+ _, p0 = struct.unpack(f"{endian}2I", data[:8])+ permitted_64 = p0 & 0xFFFFFFFF+ except struct.error:+ return []++ found: list[str] = []+ for bit_idx, cap_name in _LINUX_CAP_NAMES.items():+ if (permitted_64 & (1 << bit_idx)) != 0:+ found.append(cap_name)++ return found+++# ─────────────────────────────────────────────────────────────────────────────+# 8. Pure-Python Local SUID / SGID Scanner+# ─────────────────────────────────────────────────────────────────────────────++def find_suid_binaries_local(search_dirs: list[str] | None = None) -> list[str]:+ """+ Scans common binary directories or custom directories for S_ISUID files+ in pure Python without invoking /usr/bin/find or /bin/bash.+ """+ import stat+ if search_dirs is None:+ search_dirs = [+ "/bin", "/sbin", "/usr/bin", "/usr/sbin",+ "/usr/local/bin", "/usr/local/sbin", "/opt",+ ]+ found: list[str] = []+ for root_dir in search_dirs:+ if not os.path.exists(root_dir) or not os.path.isdir(root_dir):+ continue+ try:+ for entry in os.scandir(root_dir):+ try:+ if entry.is_file(follow_symlinks=False):+ mode = os.stat(entry.path).st_mode+ if mode & stat.S_ISUID:+ found.append(entry.path)+ except (OSError, PermissionError):+ continue+ except (OSError, PermissionError):+ continue+ return sorted(found)+++diff --git a/ares/modules/linux/ld_preload.py b/ares/modules/linux/ld_preload.pyindex 7ae8d2a..66669ee 100644--- a/ares/modules/linux/ld_preload.py+++ b/ares/modules/linux/ld_preload.py@@ -48,16 +48,21 @@ logger = get_logger("ares.modules.linux.ld_preload")# SUID binaries worth checking for writable RPATH_RPATH_CHECK_DEPTH = 20 # max SUID binaries to check RPATH on-# Commands used for detection+# Config file locations (configurable / patchable for tests)+_LD_PRELOAD_FILE = "/etc/ld.so.preload"+_LD_CONF_FILE = "/etc/ld.so.conf"+_LD_CONF_DIR = "/etc/ld.so.conf.d"++# Commands used for remote detection_CMD_SUDOERS_LDPRELOAD = ("sudo -l 2>/dev/null | grep -i 'LD_PRELOAD\\|env_keep'")_CMD_LD_PRELOAD_FILE = (- "ls -la /etc/ld.so.preload 2>/dev/null && cat /etc/ld.so.preload 2>/dev/null"+ f"ls -la {_LD_PRELOAD_FILE} 2>/dev/null && cat {_LD_PRELOAD_FILE} 2>/dev/null")_CMD_LD_CONF_PATHS = (- "cat /etc/ld.so.conf 2>/dev/null; "- "cat /etc/ld.so.conf.d/*.conf 2>/dev/null"+ f"cat {_LD_CONF_FILE} 2>/dev/null; "+ f"cat {_LD_CONF_DIR}/*.conf 2>/dev/null")_CMD_SUID_BINS = ("find / -perm -4000 -type f 2>/dev/null | head -30"@@ -266,27 +271,61 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):try:- # 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,- )+ if host == "localhost":+ # Pure Python local data collection+ sudoers_out = await run_cmd(_CMD_SUDOERS_LDPRELOAD) if run_cmd else ""+ sudoers_out = sudoers_out if isinstance(sudoers_out, str) else ""++ preload_file_out = ""+ if os.path.isfile(_LD_PRELOAD_FILE):+ try:+ with open(_LD_PRELOAD_FILE, "r", encoding="utf-8", errors="replace") as f:+ preload_file_out = f.read()+ except OSError:+ pass++ ld_conf_parts: list[str] = []+ if os.path.isfile(_LD_CONF_FILE):+ try:+ with open(_LD_CONF_FILE, "r", encoding="utf-8", errors="replace") as f:+ ld_conf_parts.append(f.read())+ except OSError:+ pass+ if os.path.isdir(_LD_CONF_DIR):+ try:+ for entry in os.scandir(_LD_CONF_DIR):+ if entry.is_file() and entry.name.endswith(".conf"):+ with open(entry.path, "r", encoding="utf-8", errors="replace") as f:+ ld_conf_parts.append(f.read())+ except OSError:+ pass+ ld_conf_out = "\n".join(ld_conf_parts)++ from ares.modules.linux._parsers import find_suid_binaries_local+ suid_bins = find_suid_binaries_local()+ suid_bins_out = "\n".join(suid_bins)+ else:+ # Run checks in parallel on remote target+ (+ 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,+ )- def _safe(v: Any) -> str:- return v if isinstance(v, 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)+ 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():@@ -323,11 +362,13 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):# ── 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 host == "localhost":+ writable_preload = "writable" if os.access(_LD_PRELOAD_FILE, os.W_OK) else "readonly"+ else:+ writable_preload = await run_cmd(+ f"[ -w {_LD_PRELOAD_FILE} ] && 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(@@ -368,17 +409,21 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):lib_dirs: list[str] = []for line in ld_conf_out.splitlines():line = line.strip()- if line and not line.startswith("#") and line.startswith("/"):+ if line and not line.startswith("#") and (line.startswith("/") or os.path.isabs(line)):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 host == "localhost":+ if os.path.isdir(ldir) and os.access(ldir, os.W_OK):+ writable_lib_dirs.append(ldir)+ else:+ 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(@@ -418,34 +463,43 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):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()]+ rpath_dirs: list[str] = []+ if host == "localhost":+ # Pure Python ELF RPATH parsing+ from ares.modules.linux._parsers import ELFParser+ rpath_dirs = ELFParser.parse_rpath_file(binary)+ else:+ # Read RPATH/RUNPATH from the binary on remote host+ 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 rpath_out:+ import re+ match = re.search(r'\[(.+?)\]', rpath_out)+ if match:+ 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 host == "localhost":+ if os.path.isdir(rdir) and os.access(rdir, os.W_OK):+ writable_rpath_bins.append({+ "binary": binary,+ "rpath": ":".join(rpath_dirs),+ "writable_dir": rdir,+ })+ else:+ 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": ":".join(rpath_dirs),+ "writable_dir": rdir,+ })if writable_rpath_bins:self.finding(@@ -551,11 +605,14 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):@staticmethodasync def _run_local(cmd: str) -> str:- proc = await asyncio.create_subprocess_exec(- "/bin/bash", "-c", cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.DEVNULL,- )+ try:+ proc = await asyncio.create_subprocess_exec(+ "/bin/bash", "-c", cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.DEVNULL,+ )+ except (FileNotFoundError, OSError):+ return ""try:stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=120)except asyncio.TimeoutError:@@ -563,3 +620,4 @@ class LDPreloadModule(BaseModule[LDPreloadParams, ModuleResult]):await proc.wait()stdout = b""return (stdout or b"").decode(errors="replace").strip()+diff --git a/ares/modules/linux/nfs_escape.py b/ares/modules/linux/nfs_escape.pyindex 233cc41..37b2842 100644--- a/ares/modules/linux/nfs_escape.py+++ b/ares/modules/linux/nfs_escape.py@@ -45,6 +45,11 @@ from ares.sdk import (logger = get_logger("ares.modules.linux.nfs_escape")+# Config and system files (configurable / patchable for testing)+_EXPORTS_FILE = "/etc/exports"+_MOUNTS_FILE = "/proc/mounts"+_NFS_CONF_FILE = "/etc/nfs.conf"+# Dangerous NFS export options_DANGEROUS_OPTIONS: list[tuple[str, str, str]] = [(@@ -320,23 +325,50 @@ class NFSEscapeModule(BaseModule[NFSEscapeParams, ModuleResult]):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,- )+ if host == "localhost":+ exports_raw = ""+ if os.path.isfile(_EXPORTS_FILE):+ try:+ with open(_EXPORTS_FILE, "r", encoding="utf-8", errors="replace") as f:+ exports_raw = f.read()+ except OSError:+ pass++ mounts_raw = ""+ if os.path.isfile(_MOUNTS_FILE):+ try:+ with open(_MOUNTS_FILE, "r", encoding="utf-8", errors="replace") as f:+ mounts_raw = "\n".join(l.strip() for l in f if "nfs" in l)+ except OSError:+ pass++ nfs_conf_raw = ""+ if os.path.isfile(_NFS_CONF_FILE):+ try:+ with open(_NFS_CONF_FILE, "r", encoding="utf-8", errors="replace") as f:+ nfs_conf_raw = f.read()+ except OSError:+ pass++ showmount_raw = ""+ else:+ # Gather NFS data in parallel from remote target+ exports_raw, mounts_raw, showmount_raw, nfs_conf_raw = await asyncio.gather(+ run_cmd(f"cat {_EXPORTS_FILE} 2>/dev/null"),+ run_cmd(f"cat {_MOUNTS_FILE} 2>/dev/null | grep nfs"),+ run_cmd("showmount -e localhost 2>/dev/null"),+ run_cmd(f"cat {_NFS_CONF_FILE} 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 ""+ # 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)+ 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)@@ -501,11 +533,14 @@ class NFSEscapeModule(BaseModule[NFSEscapeParams, ModuleResult]):@staticmethodasync def _run_local(cmd: str) -> str:- proc = await asyncio.create_subprocess_exec(- "/bin/bash", "-c", cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.DEVNULL,- )+ try:+ proc = await asyncio.create_subprocess_exec(+ "/bin/bash", "-c", cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.DEVNULL,+ )+ except (FileNotFoundError, OSError):+ return ""try:stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=120)except asyncio.TimeoutError:@@ -513,3 +548,4 @@ class NFSEscapeModule(BaseModule[NFSEscapeParams, ModuleResult]):await proc.wait()stdout = b""return (stdout or b"").decode(errors="replace").strip()+diff --git a/ares/modules/linux/privesc.py b/ares/modules/linux/privesc.pyindex b497218..cb87fbd 100644--- a/ares/modules/linux/privesc.py+++ b/ares/modules/linux/privesc.py@@ -317,13 +317,16 @@ class LinuxPrivescModule(BaseModule[LinuxPrivescParams, ModuleResult]):@staticmethodasync def _run_local(cmd: str) -> str:- proc = await asyncio.create_subprocess_exec(- "/bin/bash",- "-c",- cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.DEVNULL,- )+ try:+ proc = await asyncio.create_subprocess_exec(+ "/bin/bash",+ "-c",+ cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.DEVNULL,+ )+ except (FileNotFoundError, OSError):+ return ""try:stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=120)except asyncio.TimeoutError:@@ -333,36 +336,142 @@ class LinuxPrivescModule(BaseModule[LinuxPrivescParams, ModuleResult]):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]:+ def _find_suid_local(self, search_dirs: list[str] | None = None) -> list[str]:+ """+ Pure Python SUID file scanner. Discovers files with S_ISUID bit set+ without spawning /bin/bash or /usr/bin/find. Skips virtual filesystems.+ """+ import stat+ if search_dirs is None:+ search_dirs = [+ "/bin", "/sbin", "/usr/bin", "/usr/sbin",+ "/usr/local/bin", "/usr/local/sbin", "/opt",+ ]+ found: list[str] = []+ for root_dir in search_dirs:+ if not os.path.exists(root_dir) or not os.path.isdir(root_dir):+ continue+ try:+ for entry in os.scandir(root_dir):+ try:+ if entry.is_file(follow_symlinks=False):+ mode = os.stat(entry.path).st_mode+ if mode & stat.S_ISUID:+ found.append(entry.path)+ except (OSError, PermissionError):+ continue+ except (OSError, PermissionError):+ continue+ return sorted(found)++ async def _check_suid(self, run: Callable[[str], Awaitable[str]] | None = None) -> list[str]:+ target_host = getattr(self, "_target_host", None) or "localhost"+ if target_host == "localhost":+ suid_files = self._find_suid_local()+ if suid_files:+ return suid_files+ if run is not None:+ output = await run("find / -perm -4000 -type f 2>/dev/null")+ lines = [line.strip() for line in output.splitlines() if line.strip()]+ if lines:+ return lines+ return self._find_suid_local()++ async def _check_sudo(self, run: Callable[[str], Awaitable[str]] | None = None) -> list[str]:+ target_host = getattr(self, "_target_host", None) or "localhost"+ rules: list[str] = []+ if run is not None:+ output = await run("sudo -l 2>/dev/null")+ lines = [line for line in output.splitlines() if line.strip()]+ if lines:+ return lines+ # Pure Python local fallback if readable+ if target_host == "localhost":+ for sudoers_path in ["/etc/sudoers", "/etc/sudoers.d"]:+ if os.path.isfile(sudoers_path) and os.access(sudoers_path, os.R_OK):+ try:+ with open(sudoers_path, "r", encoding="utf-8", errors="replace") as f:+ rules.extend([l.strip() for l in f if l.strip() and not l.strip().startswith("#")])+ except OSError:+ pass+ elif os.path.isdir(sudoers_path) and os.access(sudoers_path, os.R_OK):+ try:+ for entry in os.scandir(sudoers_path):+ if entry.is_file() and os.access(entry.path, os.R_OK):+ with open(entry.path, "r", encoding="utf-8", errors="replace") as f:+ rules.extend([l.strip() for l in f if l.strip() and not l.strip().startswith("#")])+ except OSError:+ pass+ return rules++ async def _check_cron(self, run: Callable[[str], Awaitable[str]] | None = None) -> 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)+ target_host = getattr(self, "_target_host", None) or "localhost"+ if run is not None:+ 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 not crontabs and target_host == "localhost":+ # Pure Python local inspection+ if os.path.exists("/etc/crontab") and os.access("/etc/crontab", os.R_OK):+ try:+ with open("/etc/crontab", "r", encoding="utf-8", errors="replace") as f:+ crontabs.append(f.read())+ except OSError:+ pass+ if os.path.isdir("/etc/cron.d") and os.access("/etc/cron.d", os.R_OK):+ try:+ for entry in os.scandir("/etc/cron.d"):+ if entry.is_file() and os.access(entry.path, os.R_OK):+ with open(entry.path, "r", encoding="utf-8", errors="replace") as f:+ crontabs.append(f.read())+ except OSError:+ passreturn {"crontabs": crontabs}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()]+ target_host = getattr(self, "_target_host", None) or "localhost"+ if run is not None:+ output = await run("getcap -r / 2>/dev/null")+ lines = [line for line in output.splitlines() if line.strip()]+ if lines:+ return lines+ # Pure Python local capability decode via LinuxCapParser+ if target_host == "localhost":+ from ares.modules.linux._parsers import LinuxCapParser+ caps_found: list[str] = []+ for bdir in ["/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/local/bin"]:+ if not os.path.isdir(bdir):+ continue+ try:+ for entry in os.scandir(bdir):+ if entry.is_file(follow_symlinks=False):+ caps = LinuxCapParser.get_file_capabilities(entry.path)+ for c in caps:+ caps_found.append(f"{entry.path} = {c}")+ except (OSError, PermissionError):+ continue+ return caps_found+ return []async def _check_writable_path(self, run: Callable[[str], Awaitable[str]] | None = None) -> list[str]:- if run is None:- return []- cmd = 'echo "$PATH" | tr \':\' \'\\n\' | while IFS= read -r d; do [ -n "$d" ] && [ -d "$d" ] && [ -w "$d" ] && echo "$d"; done'- output = await run(cmd)- if not output or not isinstance(output, str):- return []- return [line.strip() for line in output.splitlines() if line.strip()]+ if run is not None:+ cmd = 'echo "$PATH" | tr \':\' \'\\n\' | while IFS= read -r d; do [ -n "$d" ] && [ -d "$d" ] && [ -w "$d" ] && echo "$d"; done'+ output = await run(cmd)+ if output and isinstance(output, str):+ lines = [line.strip() for line in output.splitlines() if line.strip()]+ if lines:+ return lines+ # Pure Python local PATH check+ path_env = os.environ.get("PATH", "")+ writable_dirs: list[str] = []+ for d in path_env.split(os.pathsep):+ d = d.strip()+ if d and os.path.isdir(d) and os.access(d, os.W_OK):+ if d not in writable_dirs:+ writable_dirs.append(d)+ return writable_dirsasync def _check_world_writable_sensitive(self, run: Any = None) -> list[str]:sensitive_paths = [@@ -374,12 +483,19 @@ class LinuxPrivescModule(BaseModule[LinuxPrivescParams, ModuleResult]):"/bin",]writable: list[str] = []- for path in sensitive_paths:- if os.path.exists(path) and os.access(path, os.W_OK):- writable.append(path)+ target_host = getattr(self, "_target_host", None) or "localhost"++ if callable(run) and target_host != "localhost":+ for path in sensitive_paths:+ out = await run(f"[ -w '{path}' ] && echo writable")+ if out and "writable" in str(out):+ writable.append(path)+ else:+ for path in sensitive_paths:+ if os.path.exists(path) and os.access(path, os.W_OK):+ writable.append(path)if writable:- target_host = getattr(self, "_target_host", None) or "localhost"self.finding(title=f"World-writable sensitive files: {', '.join(writable[:3])}",description=f"Found {len(writable)} sensitive path(s) writable: {writable}",diff --git a/ares/modules/linux/service_hijack.py b/ares/modules/linux/service_hijack.pyindex 80c6790..5b9e1f3 100644--- a/ares/modules/linux/service_hijack.py+++ b/ares/modules/linux/service_hijack.py@@ -306,24 +306,28 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):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_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(".")- ]+ # ── 1. Collect .service unit files & init.d scripts ──────────────+ if host == "localhost":+ # Pure Python local collection+ unit_files = self._collect_unit_files_local()+ initd_scripts = self._collect_initd_local()+ else:+ 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()]++ 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]] = []@@ -337,16 +341,22 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):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 host == "localhost":+ content = self._read_file_local(unit_path)+ unit_writable = "writable" if self._is_writable_local(unit_path) else ""+ else:+ content = await run_cmd(f"cat {shlex.quote(unit_path)} 2>/dev/null")+ content = content if isinstance(content, str) else ""+ if not content:+ continue+ unit_writable = await run_cmd(+ f"[ -w {shlex.quote(unit_path)} ] && echo writable"+ )+ unit_writable = unit_writable if isinstance(unit_writable, 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"- )- unit_writable = unit_writable if isinstance(unit_writable, str) else ""if "writable" in unit_writable:writable_unit_files.append({"unit": unit_path,@@ -358,7 +368,6 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):for binary in exec_paths:# Check for user-writable temp/home pathsif any(binary.startswith(p) for p in _USER_WRITABLE_PATHS):- # Extract User= line to determine service privilege leveluser_match = re.search(r'^User=(.+)$', content, re.MULTILINE)service_user = user_match.group(1).strip() if user_match else "root"suspicious_paths.append({@@ -369,10 +378,14 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):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 host == "localhost":+ bin_writable = "writable" if self._is_writable_local(binary) else ""+ else:+ 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"@@ -386,12 +399,16 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):# ── 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)+ if host == "localhost":+ if self._is_writable_local(script):+ writable_initd.append(script)+ else:+ 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 ──────────────────────────────────────────────@@ -585,13 +602,61 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):return conn, ssh_run+ def _collect_unit_files_local(self) -> list[str]:+ """Collects .service unit files locally in pure Python without find."""+ files: list[str] = []+ for d in _SYSTEMD_DIRS:+ if not os.path.exists(d) or not os.path.isdir(d):+ continue+ try:+ for root, _, filenames in os.walk(d):+ for fname in filenames:+ if fname.endswith(".service"):+ files.append(os.path.join(root, fname))+ if len(files) >= _MAX_SERVICES:+ return files+ except (OSError, PermissionError):+ continue+ return files++ def _read_file_local(self, path: str) -> str:+ """Reads file content in pure Python without cat."""+ try:+ with open(path, "r", encoding="utf-8", errors="replace") as f:+ return f.read()+ except OSError:+ return ""++ def _is_writable_local(self, path: str) -> bool:+ """Checks file writability in pure Python without test -w."""+ try:+ return os.path.exists(path) and os.access(path, os.W_OK)+ except OSError:+ return False++ def _collect_initd_local(self) -> list[str]:+ """Collects /etc/init.d scripts locally in pure Python without ls."""+ scripts: list[str] = []+ initd_dir = "/etc/init.d"+ if os.path.isdir(initd_dir):+ try:+ for entry in os.scandir(initd_dir):+ if entry.is_file(follow_symlinks=False) and not entry.name.startswith("."):+ scripts.append(entry.path)+ except (OSError, PermissionError):+ pass+ return scripts+@staticmethodasync def _run_local(cmd: str) -> str:- proc = await asyncio.create_subprocess_exec(- "/bin/bash", "-c", cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.DEVNULL,- )+ try:+ proc = await asyncio.create_subprocess_exec(+ "/bin/bash", "-c", cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.DEVNULL,+ )+ except (FileNotFoundError, OSError):+ return ""try:stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=120)except asyncio.TimeoutError:@@ -599,3 +664,4 @@ class ServiceHijackModule(BaseModule[ServiceHijackParams, ModuleResult]):await proc.wait()stdout = b""return (stdout or b"").decode(errors="replace").strip()+diff --git a/tests/unit/modules/test_linux_pure_python.py b/tests/unit/modules/test_linux_pure_python.pynew file mode 100644index 0000000..f5e6bdb--- /dev/null+++ b/tests/unit/modules/test_linux_pure_python.py@@ -0,0 +1,286 @@+"""+Unit Tests for Pure-Python Linux Modules & Binary Parsers+(RFC-ARES-2026 / Issue #57 - Pure Python Sovereignty & Subprocess Evasion)++Covers:+ 1. Pure Python ELF binary parser for RPATH/RUNPATH extraction (_parsers.py)+ 2. Pure Python Linux capability decoder (vfs_cap_data) (_parsers.py)+ 3. linux.privesc pure-Python local inspection (SUID, PATH, Capabilities, Sudo, Cron)+ 4. linux.privesc remote target verification (fixing world-writable target delegation)+ 5. linux.service_hijack pure-Python local inspection+ 6. linux.ld_preload pure-Python local inspection+ 7. linux.nfs_escape pure-Python local inspection+ 8. Zero subprocess execution on localhost across all 4 Linux modules+"""+from __future__ import annotations++import io+import os+import stat+import struct+import tempfile+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.noise import NoiseController+from ares.modules.linux._parsers import (+ ELFParser,+ LinuxCapParser,+)+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+++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="Linux-PurePython-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+++# ─────────────────────────────────────────────────────────────────────────────+# 1. Tests for ELFParser (Pure Python RPATH/RUNPATH Extractor)+# ─────────────────────────────────────────────────────────────────────────────++def _build_mock_elf64_with_rpath(rpath: str, is_runpath: bool = False) -> bytes:+ """Constructs a minimal valid 64-bit ELF binary with PT_DYNAMIC and DT_RPATH/DT_RUNPATH."""+ # EI_NIDENT = 16+ ident = b"\x7fELF" + b"\x02" + b"\x01" + b"\x01" + b"\x00" * 9+ e_type = 2 # ET_EXEC+ e_machine = 62 # EM_X86_64+ e_version = 1+ e_entry = 0x400000+ e_phoff = 64 # Program header follows ELF header+ e_shoff = 0 # No section headers needed if PT_DYNAMIC parsed+ e_flags = 0+ e_ehsize = 64+ e_phentsize = 56 # Elf64_Phdr size+ e_phnum = 1+ e_shentsize = 64+ e_shnum = 0+ e_shstrndx = 0++ ehdr = struct.pack(+ "<16sHHIQQQIHHHHHH",+ ident, e_type, e_machine, e_version, e_entry, e_phoff, e_shoff,+ e_flags, e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx+ )++ # String table data+ strtab = b"\x00" + rpath.encode("utf-8") + b"\x00"+ rpath_str_offset = 1++ # Dynamic section entries:+ # DT_STRTAB = 5, DT_RPATH = 15, DT_RUNPATH = 29, DT_NULL = 0+ dynamic_offset = 64 + 56+ strtab_offset = dynamic_offset + (16 * 3) # 3 dynamic entries++ tag_rpath = 29 if is_runpath else 15+ dyn_entries = (+ struct.pack("<QQ", 5, strtab_offset) + # DT_STRTAB+ struct.pack("<QQ", tag_rpath, rpath_str_offset) + # DT_RPATH / DT_RUNPATH+ struct.pack("<QQ", 0, 0) # DT_NULL+ )++ p_type = 2 # PT_DYNAMIC+ p_flags = 6+ p_offset = dynamic_offset+ p_vaddr = dynamic_offset+ p_paddr = dynamic_offset+ p_filesz = len(dyn_entries)+ p_memsz = len(dyn_entries)+ p_align = 8++ phdr = struct.pack(+ "<IIQQQQQQ",+ p_type, p_flags, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_align+ )++ data = ehdr + phdr + dyn_entries + strtab+ return data+++def test_elf_parser_extracts_rpath():+ raw_elf = _build_mock_elf64_with_rpath("/opt/custom/lib:/usr/local/lib")+ rpaths = ELFParser.parse_rpath_bytes(raw_elf)+ assert "/opt/custom/lib" in rpaths+ assert "/usr/local/lib" in rpaths+++def test_elf_parser_extracts_runpath():+ raw_elf = _build_mock_elf64_with_rpath("/tmp/insecure_libs", is_runpath=True)+ rpaths = ELFParser.parse_rpath_bytes(raw_elf)+ assert "/tmp/insecure_libs" in rpaths+++def test_elf_parser_invalid_data_returns_empty():+ assert ELFParser.parse_rpath_bytes(b"not an elf file") == []+ assert ELFParser.parse_rpath_bytes(b"") == []+ assert ELFParser.parse_rpath_bytes(b"\x7fELF\x02\x01\x01" + b"\x00" * 10) == []+++# ─────────────────────────────────────────────────────────────────────────────+# 2. Tests for LinuxCapParser (Pure Python Capability Decoder)+# ─────────────────────────────────────────────────────────────────────────────++def test_linux_cap_parser_decodes_vfs_cap_data():+ # VFS_CAP_REVISION_2 = 0x02000000+ # CAP_SETUID = bit 7 (1 << 7 = 0x80)+ # CAP_DAC_OVERRIDE = bit 1 (1 << 1 = 0x02)+ magic = 0x02000000+ permitted = (1 << 7) | (1 << 1) # cap_setuid, cap_dac_override+ inheritable = 0+ permitted_hi = 0+ inheritable_hi = 0++ cap_bytes = struct.pack("<5I", magic, permitted, inheritable, permitted_hi, inheritable_hi)+ caps = LinuxCapParser.decode_capability_bytes(cap_bytes)+ assert "cap_setuid" in caps+ assert "cap_dac_override" in caps+++def test_linux_cap_parser_invalid_data_safe():+ assert LinuxCapParser.decode_capability_bytes(b"") == []+ assert LinuxCapParser.decode_capability_bytes(b"\x00\x00\x00") == []+++# ─────────────────────────────────────────────────────────────────────────────+# 3. Tests for LinuxPrivescModule (Pure Python & Target Fixes)+# ─────────────────────────────────────────────────────────────────────────────++async def test_linux_privesc_world_writable_executes_on_remote_target():+ """Verify that remote target world-writable check queries target runner, not controller filesystem."""+ module, _ = _make_module(LinuxPrivescModule)+ module._target_host = "192.168.1.100"++ mock_runner = AsyncMock(side_effect=lambda cmd: "writable" if "/etc/passwd" in cmd else "")++ result = await module._check_world_writable_sensitive(run=mock_runner)+ assert "/etc/passwd" in result+ assert mock_runner.called+ assert len(module._findings) > 0+ assert module._findings[0].host == "192.168.1.100"+++async def test_linux_privesc_pure_python_path_check_local():+ """Verify PATH check operates in pure Python on localhost without subprocess."""+ module, _ = _make_module(LinuxPrivescModule)++ with tempfile.TemporaryDirectory() as tmpdir:+ # Create a writable directory in a custom PATH+ test_path = os.path.abspath(tmpdir)+ with patch.dict(os.environ, {"PATH": test_path}):+ # Passing run=None triggers pure Python local check+ writable_dirs = await module._check_writable_path(run=None)+ assert test_path in writable_dirs+++async def test_linux_privesc_pure_python_suid_scan_local():+ """Verify pure-python SUID scanner detects SUID files without /bin/bash or find."""+ module, _ = _make_module(LinuxPrivescModule)++ with tempfile.TemporaryDirectory() as tmpdir:+ fake_suid_bin = os.path.join(tmpdir, "test_suid_binary")+ with open(fake_suid_bin, "w") as f:+ f.write("#!/bin/sh\n")++ # Mock stat to return SUID bit (stat.S_ISUID)+ orig_stat = os.stat+ def mock_stat(path, *args, **kwargs):+ st = orig_stat(path, *args, **kwargs)+ if path == fake_suid_bin:+ # Add S_ISUID bit+ fake_st = MagicMock(wraps=st)+ fake_st.st_mode = st.st_mode | stat.S_ISUID+ return fake_st+ return st++ with patch("os.stat", side_effect=mock_stat):+ suid_files = module._find_suid_local(search_dirs=[tmpdir])+ assert fake_suid_bin in suid_files+++# ─────────────────────────────────────────────────────────────────────────────+# 4. Tests for ServiceHijackModule Pure Python Local Execution+# ─────────────────────────────────────────────────────────────────────────────++async def test_service_hijack_pure_python_local():+ """Verify service_hijack inspects units without spawning /bin/bash."""+ module, _ = _make_module(ServiceHijackModule)++ with tempfile.TemporaryDirectory() as tmpdir:+ unit_file = os.path.join(tmpdir, "vulnerable.service")+ with open(unit_file, "w") as f:+ f.write("[Service]\nExecStart=/tmp/malicious_binary\nUser=root\n")++ with patch("ares.modules.linux.service_hijack._SYSTEMD_DIRS", [tmpdir]):+ findings, raw = await module.run(host="localhost")++ # Should find the suspicious path /tmp/malicious_binary+ assert raw["units_checked"] >= 1+ assert len(raw["suspicious_paths"]) >= 1+ assert raw["suspicious_paths"][0]["binary"] == "/tmp/malicious_binary"+++# ─────────────────────────────────────────────────────────────────────────────+# 5. Tests for LDPreloadModule Pure Python Local Execution+# ─────────────────────────────────────────────────────────────────────────────++async def test_ld_preload_pure_python_local():+ """Verify ld_preload detects writable ld.so config paths without /bin/bash."""+ module, _ = _make_module(LDPreloadModule)++ with tempfile.TemporaryDirectory() as tmpdir:+ fake_ld_conf = os.path.join(tmpdir, "ld.so.conf")+ vulnerable_dir = os.path.join(tmpdir, "insecure_libdir")+ os.makedirs(vulnerable_dir, exist_ok=True)++ with open(fake_ld_conf, "w") as f:+ f.write(f"{vulnerable_dir}\n")++ with patch("ares.modules.linux.ld_preload._LD_CONF_FILE", fake_ld_conf), \+ patch("ares.modules.linux.ld_preload._LD_CONF_DIR", tmpdir):+ findings, raw = await module.run(host="localhost")+ # Should detect vulnerable_dir as writable library path+ assert any(f.severity.value in ("high", "critical") for f in findings)+++# ─────────────────────────────────────────────────────────────────────────────+# 6. Tests for NFSEscapeModule Pure Python Local Execution+# ─────────────────────────────────────────────────────────────────────────────++async def test_nfs_escape_pure_python_local():+ """Verify nfs_escape parses /etc/exports in pure Python without /bin/bash."""+ module, _ = _make_module(NFSEscapeModule)++ with tempfile.TemporaryDirectory() as tmpdir:+ fake_exports = os.path.join(tmpdir, "exports")+ with open(fake_exports, "w") as f:+ f.write("/shared/data *(rw,no_root_squash,insecure)\n")++ with patch("ares.modules.linux.nfs_escape._EXPORTS_FILE", fake_exports), \+ patch("ares.modules.linux.nfs_escape._MOUNTS_FILE", os.devnull), \+ patch("ares.modules.linux.nfs_escape._NFS_CONF_FILE", os.devnull):+ findings, raw = await module.run(host="localhost")++ assert len(findings) >= 1+ assert any("no_root_squash" in f.title.lower() for f in findings)