fix(appctl): eliminate eval injection and enforce manifest env key validation
Eliminates arbitrary shell command injection via workload manifest environment variables and strictly enforces POSIX identifier validation during schema parsing. Previously, `scripts/appctl` evaluated environment dictionaries from `app.yaml` using `eval "$(python3 ...)"`, allowing command substitution (e.g. `$(...)`, backticks) and unescaped quotes in manifest values to execute arbitrary commands with host privileges. Furthermore, `core_manifest.py` accepted unconstrained variable keys, risking environment corruption via platform-reserved identifiers. - Replace `eval` in `scripts/appctl` with a zero-evaluation NUL-delimited stream piped directly into `export "$k=$v"`, preserving environment values strictly as data. - Enforce POSIX variable naming regex (`^[a-zA-Z_][a-zA-Z0-9_]*$`) in `core_manifest.py` and reject reserved environment identifiers (`PATH`, `LD_PRELOAD`, `IFS`, etc.). - Add adversarial regression tests in `test_security_invariants.py` and unit tests in `test_core_manifest.py` verifying command substitution resilience. - Track Pre-P4 Security Gate tasks in `todo.txt`. Part of Pre-P4 Security Gate (Milestone P4 readiness).
This commit is contained in:
1 parent
bbbf58a27c
commit
667f8d19b9
5 files changed
+140
-7
No files matched your search
+13
-6
@@ -107,14 +107,21 @@ setup_app_env() {
|
|||||||
export DOMAIN="$RESOLVED_DOMAIN"
|
export DOMAIN="$RESOLVED_DOMAIN"
|
||||||
|
|
||||||
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
|
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
|
||||||
eval "$(python3 -c "
|
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
|
||||||
import json, sys
|
export "$k=$v"
|
||||||
|
done < <(python3 -c "
|
||||||
|
import json, re, sys
|
||||||
|
RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
|
||||||
d = json.loads(sys.argv[1])
|
d = json.loads(sys.argv[1])
|
||||||
env_dict = d.get('env', {})
|
env_dict = d.get('env', {})
|
||||||
for k, v in env_dict.items():
|
if isinstance(env_dict, dict):
|
||||||
if v != '' and v is not None:
|
for k, v in env_dict.items():
|
||||||
print(f'export {k}=\"{v}\"')
|
k_str = str(k).strip()
|
||||||
" "$resolved_json")"
|
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
|
||||||
|
continue
|
||||||
|
if v is not None and v != '':
|
||||||
|
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\0' + str(v).encode('utf-8') + b'\0')
|
||||||
|
" "$resolved_json")
|
||||||
|
|
||||||
# 4. Source local .env if present
|
# 4. Source local .env if present
|
||||||
if [ -f "$APP_DIR/.env" ]; then
|
if [ -f "$APP_DIR/.env" ]; then
|
||||||
|
|||||||
@@ -49,6 +49,11 @@ COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
|||||||
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
||||||
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
|
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
|
||||||
SCP_URL_RE = re.compile(r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$")
|
SCP_URL_RE = re.compile(r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$")
|
||||||
|
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||||
|
RESERVED_ENV_KEYS = {
|
||||||
|
"PATH", "LD_PRELOAD", "IFS", "SHELL", "USER",
|
||||||
|
"CORE_DIR", "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV"
|
||||||
|
}
|
||||||
|
|
||||||
ALLOWED_STRATEGIES = {"compose"}
|
ALLOWED_STRATEGIES = {"compose"}
|
||||||
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
||||||
@@ -313,7 +318,16 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
|||||||
|
|
||||||
# 7. Environment overrides
|
# 7. Environment overrides
|
||||||
env_raw = data.get("env", {})
|
env_raw = data.get("env", {})
|
||||||
env = dict(env_raw) if isinstance(env_raw, dict) else {}
|
env: dict[str, str] = {}
|
||||||
|
if isinstance(env_raw, dict):
|
||||||
|
for raw_k, raw_v in env_raw.items():
|
||||||
|
k_str = str(raw_k).strip()
|
||||||
|
if not ENV_KEY_RE.match(k_str) or k_str in RESERVED_ENV_KEYS:
|
||||||
|
raise ManifestValidationError(
|
||||||
|
f"Invalid or reserved environment variable key '{k_str}'. "
|
||||||
|
f"Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot be reserved."
|
||||||
|
)
|
||||||
|
env[k_str] = str(raw_v) if raw_v is not None else ""
|
||||||
|
|
||||||
# 8. Deployment Policy
|
# 8. Deployment Policy
|
||||||
deployment_raw = data.get("deployment")
|
deployment_raw = data.get("deployment")
|
||||||
|
|||||||
@@ -77,3 +77,68 @@ def test_portainer_is_deprecated_and_absent():
|
|||||||
|
|
||||||
volumes = compose.get("volumes", {}) or {}
|
volumes = compose.get("volumes", {}) or {}
|
||||||
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_eval_in_appctl_script():
|
||||||
|
"""Ensure scripts/appctl never uses eval on dynamic environment or manifest payloads."""
|
||||||
|
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
||||||
|
content = appctl_path.read_text(encoding="utf-8")
|
||||||
|
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
|
||||||
|
|
||||||
|
|
||||||
|
def test_appctl_env_injection_resilience(tmp_path: Path):
|
||||||
|
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution."""
|
||||||
|
canary = tmp_path / "pwned.txt"
|
||||||
|
payload = f"$(touch {canary})"
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
||||||
|
appctl_content = appctl_path.read_text(encoding="utf-8")
|
||||||
|
assert "eval " not in appctl_content
|
||||||
|
assert "while IFS= read -r -d '' k && IFS= read -r -d '' v; do" in appctl_content
|
||||||
|
|
||||||
|
resolved_json = json.dumps({
|
||||||
|
"name": "test-app",
|
||||||
|
"domain": "test.roadtotech.me",
|
||||||
|
"dir_path": str(tmp_path),
|
||||||
|
"env": {"INJECTION_TEST": payload, "NORMAL_VAR": "safe_value"},
|
||||||
|
})
|
||||||
|
|
||||||
|
bash_code = f"""
|
||||||
|
set -euo pipefail
|
||||||
|
resolved_json='{resolved_json}'
|
||||||
|
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
|
||||||
|
export "$k=$v"
|
||||||
|
done < <(python3 -c "
|
||||||
|
import json, re, sys
|
||||||
|
RESERVED = {{'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}}
|
||||||
|
d = json.loads(sys.argv[1])
|
||||||
|
env_dict = d.get('env', {{}})
|
||||||
|
if isinstance(env_dict, dict):
|
||||||
|
for k, v in env_dict.items():
|
||||||
|
k_str = str(k).strip()
|
||||||
|
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
|
||||||
|
continue
|
||||||
|
if v is not None and v != '':
|
||||||
|
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\\0' + str(v).encode('utf-8') + b'\\0')
|
||||||
|
" "$resolved_json")
|
||||||
|
|
||||||
|
echo "INJECTION_TEST=$INJECTION_TEST"
|
||||||
|
echo "NORMAL_VAR=$NORMAL_VAR"
|
||||||
|
"""
|
||||||
|
|
||||||
|
res = subprocess.run(
|
||||||
|
["bash", "-c", bash_code],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
assert not canary.exists(), "Command substitution was executed on the host during environment setup!"
|
||||||
|
assert res.returncode == 0, f"Extraction failed: {res.stderr}"
|
||||||
|
assert f"INJECTION_TEST={payload}" in res.stdout
|
||||||
|
assert "NORMAL_VAR=safe_value" in res.stdout
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -181,3 +181,39 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
|||||||
manifest = parse_manifest(manifest_file)
|
manifest = parse_manifest(manifest_file)
|
||||||
assert manifest.name == "file-app"
|
assert manifest.name == "file-app"
|
||||||
assert manifest.is_internal is True
|
assert manifest.is_internal is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("invalid_key", [
|
||||||
|
"123_BAD",
|
||||||
|
"INVALID-KEY",
|
||||||
|
"FOO;BAR",
|
||||||
|
"KEY WITH SPACE",
|
||||||
|
"PATH",
|
||||||
|
"LD_PRELOAD",
|
||||||
|
"IFS",
|
||||||
|
"CORE_DIR",
|
||||||
|
"SITES_DIR",
|
||||||
|
])
|
||||||
|
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||||
|
raw_yaml = f"""
|
||||||
|
name: "app"
|
||||||
|
env:
|
||||||
|
"{invalid_key}": "some_value"
|
||||||
|
"""
|
||||||
|
with pytest.raises(ManifestValidationError, match="Invalid or reserved environment variable key"):
|
||||||
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_manifest_accepts_valid_env_keys():
|
||||||
|
raw_yaml = """
|
||||||
|
name: "app"
|
||||||
|
env:
|
||||||
|
PROJECT_PATH: "/mnt/data"
|
||||||
|
CUSTOM_PORT_1: "8080"
|
||||||
|
_INTERNAL_FLAG: "true"
|
||||||
|
"""
|
||||||
|
manifest = parse_manifest(raw_yaml)
|
||||||
|
assert manifest.env["PROJECT_PATH"] == "/mnt/data"
|
||||||
|
assert manifest.env["CUSTOM_PORT_1"] == "8080"
|
||||||
|
assert manifest.env["_INTERNAL_FLAG"] == "true"
|
||||||
|
|
||||||
@@ -11,3 +11,14 @@ x 2026-10-13 (A) Close authorization design enforcing token-everywhere policy in
|
|||||||
x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, subprocesses, and filesystem roots in docs/plans/p4-readiness-plan.md +security @p4-gate
|
x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, subprocesses, and filesystem roots in docs/plans/p4-readiness-plan.md +security @p4-gate
|
||||||
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
|
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
|
||||||
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
|
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
|
||||||
|
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
|
||||||
|
(A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
|
||||||
|
(A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
|
||||||
|
(A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
|
||||||
|
(A) Scaffold asyncio daemon server supporting dual transports (Unix socket /run/homelab/appctl.sock and HTTP) in scripts/appctl_daemon.py +daemon @p4
|
||||||
|
(A) Implement unit and integration tests for dual-transport requests and error handling in tests/unit/test_appctl_daemon.py +test @p4
|
||||||
|
(B) Implement command-oriented operational router wiring domain actions to in-process appctl_engine.py methods and fixed subprocess executions +router @p4
|
||||||
|
(B) Implement token authentication middleware validating user-scoped Bearer tokens for mutating requests +auth @p4
|
||||||
|
(B) Implement append-only audit logger writing structured RFC JSONL records with fail-closed disk guard +audit @p4
|
||||||
|
(C) Re-implement scripts/appctl as a thin client dispatching JSON requests to the daemon Unix domain socket +cli @p4
|
||||||
|
(C) Create NixOS systemd unit module for homelab-appctl.service with strict sandboxing and socket management +nixos @p4
|
||||||
Reference in new issue
Block a user