Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

fix(security): replace shell=True subprocess in ccache_hunt with shell=False and native Python IO (AUD-003)

Mafifrizida77cca11809
diff --git a/ares/modules/linux/ccache_hunt.py b/ares/modules/linux/ccache_hunt.py
index 2acbc71..a4f355f 100644
--- a/ares/modules/linux/ccache_hunt.py
+++ b/ares/modules/linux/ccache_hunt.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import os
+from pathlib import Path
import time
from typing import Any
@@ -307,22 +308,56 @@ class CcacheHuntModule(BaseModule[CcacheHuntParams, ModuleResult]):
"evidence_integrity": [e.record_hash for e in evidence_chain],
}
- def _execute_command(self, cmd: str, runner: Any = None) -> str:
- """Execute command locally or via remote command runner."""
+ @staticmethod
+ def _validate_key_id(key_id: Any) -> str:
+ """
+ Validate that key_id is a valid integer (decimal or hex) and non-negative.
+ Returns the sanitized string representation.
+ Raises ValueError if invalid or negative.
+ """
+ if isinstance(key_id, int):
+ if key_id < 0:
+ raise ValueError(f"key_id must be a non-negative integer, got: {key_id}")
+ return str(key_id)
+
+ s = str(key_id).strip()
+ if not s:
+ raise ValueError("key_id cannot be empty")
+
+ try:
+ val = int(s, 10)
+ except ValueError:
+ try:
+ val = int(s, 16)
+ except ValueError:
+ raise ValueError(f"key_id must be a valid integer, got: {key_id!r}")
+
+ if val < 0:
+ raise ValueError(f"key_id must be a non-negative integer, got: {key_id}")
+ return s
+
+ def _execute_command(self, cmd: list[str] | str, runner: Any = None) -> str:
+ """Execute command locally with shell=False or via remote command runner."""
if runner is not None:
+ cmd_str = cmd if isinstance(cmd, str) else " ".join(cmd)
if callable(runner):
- out = runner(cmd)
+ out = runner(cmd_str)
if isinstance(out, tuple):
return str(out[0])
return str(out)
if hasattr(runner, "run"):
- out = runner.run(cmd)
+ out = runner.run(cmd_str)
if isinstance(out, tuple):
return str(out[0])
return str(out)
import subprocess
try:
- res = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5)
+ if isinstance(cmd, str):
+ import shlex
+ args = shlex.split(cmd)
+ else:
+ args = [str(x) for x in cmd]
+ res = subprocess.run(args, shell=False, capture_output=True, text=True, timeout=5)
return res.stdout
except Exception:
return ""
@@ -372,10 +407,22 @@ class CcacheHuntModule(BaseModule[CcacheHuntParams, ModuleResult]):
if scan_keyring:
proc_keys_content = ""
permission_denied = False
- if os.path.exists("/proc/keys"):
+ proc_keys_path = Path("/proc/keys")
+ if os.path.exists("/proc/keys") or proc_keys_path.exists():
try:
- with open("/proc/keys", "r", errors="replace") as f:
- proc_keys_content = f.read()
+ # Native Python file read without spawning shell/subprocess
+ try:
+ with open(proc_keys_path, "r", errors="replace") as f:
+ raw_content = f.read()
+ except Exception as err:
+ if isinstance(err, PermissionError):
+ raise
+ raw_content = proc_keys_path.read_text(errors="replace")
+
+ proc_keys_content = "\n".join(
+ line for line in raw_content.splitlines()
+ if any(k in line for k in ("krb_ccache:", "krb5cc", "krb5"))
+ )
except PermissionError:
permission_denied = True
except OSError:
@@ -383,11 +430,14 @@ class CcacheHuntModule(BaseModule[CcacheHuntParams, ModuleResult]):
if not proc_keys_content and not permission_denied and runner:
try:
- raw_out = self._execute_command("cat /proc/keys | grep krb5", runner)
+ raw_out = self._execute_command(["cat", "/proc/keys"], runner)
if "permission denied" in raw_out.lower():
permission_denied = True
elif raw_out:
- proc_keys_content = raw_out
+ proc_keys_content = "\n".join(
+ line for line in raw_out.splitlines()
+ if any(k in line for k in ("krb_ccache:", "krb5cc", "krb5"))
+ )
except Exception:
pass
@@ -413,14 +463,18 @@ class CcacheHuntModule(BaseModule[CcacheHuntParams, ModuleResult]):
if "krb_ccache:" in line or "krb5cc" in line or "krb5" in line:
parts = line.strip().split()
if len(parts) >= 9:
- key_id = parts[0]
+ raw_key_id = parts[0]
desc = " ".join(parts[8:])
+ try:
+ key_id = self._validate_key_id(raw_key_id)
+ except (ValueError, TypeError):
+ continue
+
key_payload = ""
- if runner:
- try:
- key_payload = self._execute_command(f"keyctl print {key_id}", runner)
- except Exception:
- pass
+ try:
+ key_payload = self._execute_command(["keyctl", "print", str(key_id)], runner)
+ except Exception:
+ pass
has_real_key = bool(
key_payload
diff --git a/tests/unit/modules/test_ccache_hunt_security_aud003.py b/tests/unit/modules/test_ccache_hunt_security_aud003.py
new file mode 100644
index 0000000..e477aa4
--- /dev/null
+++ b/tests/unit/modules/test_ccache_hunt_security_aud003.py
@@ -0,0 +1,136 @@
+"""
+Security and regression tests for AUD-003:
+Elimination of shell=True, safe subprocess invocation, native Python IO for /proc/keys,
+and strict validation of key_id in linux.ccache_hunt.
+"""
+from pathlib import Path
+from unittest.mock import MagicMock, mock_open, 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.ccache_hunt import CcacheHuntModule
+
+
+def _make_module() -> CcacheHuntModule:
+ settings = AresSettings(
+ ares_secret_key="test-secret-key-32chars-minimum!!",
+ ares_encryption_key="test-encryption-key-32chars-min!!",
+ )
+ campaign = Campaign(
+ name="Ccache-AUD003-Test",
+ operator="test_operator",
+ scope=[ScopeEntry(cidr="10.0.0.0/24")],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+ noise = NoiseController(campaign)
+ return CcacheHuntModule(settings=settings, campaign=campaign, noise=noise)
+
+
+def test_key_id_validation_accepts_valid_integers_and_hex():
+ """Valid positive integers and hex strings must be accepted."""
+ assert CcacheHuntModule._validate_key_id(12345) == "12345"
+ assert CcacheHuntModule._validate_key_id("12345") == "12345"
+ assert CcacheHuntModule._validate_key_id("2e3a1f4b") == "2e3a1f4b"
+ assert CcacheHuntModule._validate_key_id("0x2e3a1f4b") == "0x2e3a1f4b"
+ assert CcacheHuntModule._validate_key_id(0) == "0"
+
+
+def test_key_id_validation_rejects_negative_and_malformed():
+ """Negative values and invalid inputs must raise ValueError."""
+ with pytest.raises(ValueError):
+ CcacheHuntModule._validate_key_id(-1)
+
+ with pytest.raises(ValueError):
+ CcacheHuntModule._validate_key_id("-50")
+
+ with pytest.raises(ValueError):
+ CcacheHuntModule._validate_key_id("")
+
+ with pytest.raises(ValueError):
+ CcacheHuntModule._validate_key_id(" ")
+
+
+def test_key_id_validation_rejects_shell_metacharacters():
+ """Key IDs containing shell injection metacharacters must be rejected."""
+ for bad_id in [
+ "123; rm -rf /",
+ "2e3a1f4b | whoami",
+ "123`id`",
+ "$(whoami)",
+ "123 && cat /etc/passwd",
+ "123\nid",
+ ]:
+ with pytest.raises(ValueError):
+ CcacheHuntModule._validate_key_id(bad_id)
+
+
+def test_execute_command_strictly_enforces_shell_false():
+ """Subprocess execution must use shell=False and pass arguments as a list."""
+ mod = _make_module()
+
+ with patch("subprocess.run") as mock_run:
+ mock_run.return_value = MagicMock(stdout="mocked_keyctl_output\n")
+
+ # Even if a command has metacharacters, it MUST be passed as literal argument array
+ # and shell=False MUST be used so the shell is never invoked
+ malicious_key_id = "12345; cat /etc/shadow"
+ out = mod._execute_command(["keyctl", "print", malicious_key_id])
+
+ assert mock_run.called
+ call_args, call_kwargs = mock_run.call_args
+ assert call_kwargs.get("shell") is False
+ assert call_args[0] == ["keyctl", "print", malicious_key_id]
+ assert out == "mocked_keyctl_output\n"
+
+
+async def test_proc_keys_permission_denied_handled_gracefully_native():
+ """When /proc/keys throws PermissionError on native read, module must handle gracefully."""
+ mod = _make_module()
+
+ with patch.object(Path, "exists", return_value=True), \
+ patch.object(Path, "read_text", side_effect=PermissionError("Permission denied")), \
+ patch.object(mod, "before_request"):
+
+ findings, raw = await mod.run(
+ target="10.0.0.50",
+ scan_kcm_socket=False,
+ search_dirs=[],
+ )
+
+ assert len(findings) == 1
+ assert "Inaccessible" in findings[0].title
+ assert findings[0].confidence == 0.35
+ assert raw["tickets"][0]["permission_denied"] is True
+ assert raw["tickets"][0]["file_path"] == "/proc/keys"
+
+
+async def test_proc_keys_filtered_in_python_native():
+ """Verification that native /proc/keys reading filters kerberos lines in Python."""
+ mod = _make_module()
+
+ fake_proc_keys = (
+ "00000001 2/2 1 1d 3f030000 1000 1000 user some_random_key:data\n"
+ "2e3a1f4b 2/2 1 1d 3f030000 1000 1000 user krb_ccache:[email protected]\n"
+ "00000002 2/2 1 1d 3f030000 1000 1000 user ssh_auth_socket:data\n"
+ )
+
+ with patch("os.path.exists", return_value=True), \
+ patch("builtins.open", mock_open(read_data=fake_proc_keys)), \
+ patch.object(mod, "_execute_command", return_value="TICKET_BYTES_HEX_TEST"), \
+ patch.object(mod, "before_request"):
+
+ findings, raw = await mod.run(
+ target="10.0.0.50",
+ scan_kcm_socket=False,
+ search_dirs=[],
+ )
+
+ # Only the krb_ccache key must be processed, ignoring ssh and random keys
+ assert len(raw["tickets"]) == 1
+ ticket = raw["tickets"][0]
+ assert "corpadmin" in ticket["client"]
+ assert ticket["keydata"] == "TICKET_BYTES_HEX_TEST"