Allszn's picture
Resolve CidrIp parameter refs instead of string-matching them
a9261e4 verified
Raw History Blame Contribute Delete
15.1 kB
#!/usr/bin/env python3
"""Static validation for the AWS Steam GPU Launch Kit.
Deliberately requires NO AWS credentials, so it can run in CI, before a deploy,
or inside an ephemeral Hugging Face Job. It answers three questions:
1. Does the template parse and contain the resources this design depends on?
2. Are the security invariants actually true (no 3389, encryption on, IMDSv2)?
3. Has a secret ever been committed to this repo?
Emits a single-line JSON report with an "ok" flag, mirroring the shape of
scripts/diagnose.ps1 so the same tooling can read both.
Exit code 0 = all checks passed, 1 = at least one check failed, 2 = tooling error.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
try:
import yaml
except ImportError: # pragma: no cover
print(json.dumps({"ok": False, "error": "pyyaml missing: pip install pyyaml"}))
sys.exit(2)
# ----------------------------------------------------------- CFN YAML loader
class CfnLoader(yaml.SafeLoader):
"""SafeLoader that understands CloudFormation short-form intrinsics.
Plain safe_load fails outright on `!Ref`, `!Sub`, `!GetAtt` and friends,
which would make every downstream structural check meaningless. We map them
onto their long form so the document is inspectable as ordinary data.
"""
def _cfn_multi_constructor(loader: yaml.Loader, tag_suffix: str, node: yaml.Node):
if isinstance(node, yaml.ScalarNode):
value = loader.construct_scalar(node)
elif isinstance(node, yaml.SequenceNode):
value = loader.construct_sequence(node, deep=True)
else:
value = loader.construct_mapping(node, deep=True)
if tag_suffix == "Ref":
return {"Ref": value}
return {f"Fn::{tag_suffix}": value}
CfnLoader.add_multi_constructor("!", _cfn_multi_constructor)
# ---------------------------------------------------------------- invariants
REQUIRED_RESOURCES = [
"InstanceRole",
"InstanceProfile",
"GamingSecurityGroup",
"GameVolume",
"GamingInstance",
"ElasticIp",
"InstanceStatusAlarm",
]
REQUIRED_MANAGED_POLICIES = {
"AmazonSSMManagedInstanceCore",
"CloudWatchAgentServerPolicy",
}
REQUIRED_INGRESS = {("tcp", 8443), ("udp", 8443)}
FORBIDDEN_INGRESS_PORTS = {3389, 22, 5900}
REQUIRED_JSON_FILES = [
"iam/instance-role-inline-policy.json",
"iam/operator-role-policy.json",
"ssm/SteamGpu-Diagnose.json",
]
SECRET_PATTERNS = {
"aws_access_key_id": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
"aws_secret_access_key": re.compile(
r"(?i)aws_secret_access_key\s*[:=]\s*['\"]?[A-Za-z0-9/+=]{40}"
),
"private_key_block": re.compile(
r"-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----"
),
"steam_password": re.compile(r"(?i)steam[_ ]?password\s*[:=]\s*\S+"),
"bearer_token": re.compile(r"(?i)\bbearer\s+[A-Za-z0-9\-._~+/]{20,}"),
"hf_token": re.compile(r"\bhf_[A-Za-z0-9]{30,}\b"),
}
TEXT_SUFFIXES = {".yaml", ".yml", ".json", ".ps1", ".sh", ".py", ".md", ".txt", ""}
class Report:
def __init__(self) -> None:
self.checks: list[dict] = []
def add(self, name: str, ok: bool, detail: str = "") -> bool:
self.checks.append({"check": name, "ok": bool(ok), "detail": detail})
return bool(ok)
@property
def ok(self) -> bool:
return all(c["ok"] for c in self.checks)
def failures(self) -> list[str]:
return [c["check"] for c in self.checks if not c["ok"]]
# ------------------------------------------------------------ CIDR reasoning
def _param_for(node, params: dict):
"""If `node` is `!Ref SomeParam`, return (name, spec). Otherwise (None, None)."""
if isinstance(node, dict) and set(node.keys()) == {"Ref"}:
name = node["Ref"]
if isinstance(name, str) and name in params:
return name, params[name]
return None, None
def _cidr_is_host_scoped(value, params: dict) -> tuple[bool, str]:
"""A rule is acceptable only if it resolves to a single host, never 0.0.0.0/0."""
name, spec = _param_for(value, params)
if name is not None:
pattern = str(spec.get("AllowedPattern", ""))
default = str(spec.get("Default", ""))
if not pattern:
return False, f"{name}: no AllowedPattern to constrain the CIDR"
if "/32" not in pattern and "/128" not in pattern:
return False, f"{name}: AllowedPattern does not force a single host"
if default.startswith("0.0.0.0") or default.startswith("::/0"):
return False, f"{name}: defaults to an open CIDR"
return True, f"{name}: constrained to a single host by AllowedPattern"
if isinstance(value, dict):
return False, f"unresolved intrinsic {sorted(value.keys())}"
text = str(value)
if text.startswith("0.0.0.0") or text.startswith("::/0"):
return False, "0.0.0.0/0 is not permitted"
if text.endswith("/32") or text.endswith("/128"):
return True, f"literal {text}"
return False, f"literal {text} is wider than a single host"
# ---------------------------------------------------------------- CFN checks
def check_cloudformation(path: Path, rep: Report) -> list[str]:
iam_actions: list[str] = []
if not path.exists():
rep.add("cfn.exists", False, f"missing {path}")
return iam_actions
rep.add("cfn.exists", True, str(path))
try:
doc = yaml.load(path.read_text(), Loader=CfnLoader)
except yaml.YAMLError as exc:
rep.add("cfn.parses", False, str(exc).splitlines()[0])
return iam_actions
rep.add("cfn.parses", True, "valid YAML including !Ref/!Sub/!GetAtt intrinsics")
if not isinstance(doc, dict):
rep.add("cfn.mapping", False, "template is not a mapping")
return iam_actions
rep.add("cfn.mapping", True, "top level is a mapping")
rep.add(
"cfn.header",
"AWSTemplateFormatVersion" in doc and "Description" in doc,
"AWSTemplateFormatVersion and Description present",
)
params = doc.get("Parameters") or {}
resources = doc.get("Resources") or {}
missing = [r for r in REQUIRED_RESOURCES if r not in resources]
rep.add(
"cfn.required_resources",
not missing,
f"missing: {missing}" if missing else f"all {len(REQUIRED_RESOURCES)} present",
)
# --- security group: 8443 open to a single host, nothing else ---
sg = resources.get("GamingSecurityGroup", {}).get("Properties", {})
ingress = sg.get("SecurityGroupIngress") or []
opened, offenders = set(), []
for rule in ingress:
proto = str(rule.get("IpProtocol", "")).lower()
try:
frm, to = int(rule.get("FromPort", -1)), int(rule.get("ToPort", -1))
except (TypeError, ValueError):
continue
opened.add((proto, frm))
if frm in FORBIDDEN_INGRESS_PORTS or to in FORBIDDEN_INGRESS_PORTS:
offenders.append(f"{proto}/{frm}-{to}")
rep.add(
"sg.exposes_8443",
REQUIRED_INGRESS.issubset(opened),
f"opened: {sorted(opened)}",
)
rep.add(
"sg.no_rdp_or_ssh",
not offenders,
f"forbidden rules: {offenders}" if offenders else "no 3389/22/5900 ingress",
)
scoped = [
_cidr_is_host_scoped(r["CidrIp"], params)
for r in ingress
if "CidrIp" in r
]
rep.add(
"sg.cidr_is_host_scoped",
bool(scoped) and all(ok for ok, _ in scoped),
"; ".join(detail for _, detail in scoped) or "no CidrIp rules found",
)
# --- instance hardening ---
inst = resources.get("GamingInstance", {}).get("Properties", {})
meta = inst.get("MetadataOptions", {})
rep.add(
"instance.imdsv2_required",
str(meta.get("HttpTokens", "")).lower() == "required",
f"HttpTokens={meta.get('HttpTokens')!r}",
)
root_device = (inst.get("BlockDeviceMappings") or [{}])[0].get("Ebs", {})
rep.add(
"instance.root_volume_encrypted",
root_device.get("Encrypted") is True,
f"Encrypted={root_device.get('Encrypted')!r}",
)
# --- game volume ---
vol = resources.get("GameVolume", {}).get("Properties", {})
rep.add(
"volume.encrypted",
vol.get("Encrypted") is True,
f"Encrypted={vol.get('Encrypted')!r}",
)
rep.add(
"volume.gp3",
str(vol.get("VolumeType", "")) == "gp3",
f"VolumeType={vol.get('VolumeType')!r}",
)
# --- the alarm must not look healthy by silence ---
alarm = resources.get("InstanceStatusAlarm", {}).get("Properties", {})
rep.add(
"alarm.treat_missing_data",
"TreatMissingData" in alarm,
f"TreatMissingData={alarm.get('TreatMissingData')!r}",
)
# --- IAM surface ---
role = resources.get("InstanceRole", {}).get("Properties", {})
managed = {str(a).rsplit("/", 1)[-1] for a in (role.get("ManagedPolicyArns") or [])}
rep.add(
"iam.required_managed_policies",
REQUIRED_MANAGED_POLICIES.issubset(managed),
f"missing: {sorted(REQUIRED_MANAGED_POLICIES - managed)}"
if not REQUIRED_MANAGED_POLICIES.issubset(managed)
else "SSM core + CloudWatch agent present",
)
for policy in role.get("Policies") or []:
stmts = (policy.get("PolicyDocument") or {}).get("Statement") or []
for stmt in stmts:
acts = stmt.get("Action")
if isinstance(acts, str):
acts = [acts]
for act in acts or []:
iam_actions.append(f"{policy.get('PolicyName')}: {act}")
escalation = [
a for a in iam_actions if re.search(r"iam:(?:Create|Put|Attach|PassRole|\*)", a)
]
rep.add(
"iam.no_self_escalation",
not escalation,
f"privilege-escalation verbs: {escalation}"
if escalation
else "instance role cannot widen its own access",
)
rep.add(
"iam.instance_cannot_terminate",
not any(("ec2:Terminate" in a or "ec2:Delete" in a) for a in iam_actions),
"no destructive EC2 verbs on the instance role",
)
return iam_actions
# ---------------------------------------------------------------- JSON checks
def check_json_files(root: Path, rep: Report) -> list[str]:
actions: list[str] = []
def walk(node) -> None:
if isinstance(node, dict):
for key, value in node.items():
if key == "Action" and isinstance(value, str):
actions.append(value)
walk(value)
elif isinstance(node, list):
for item in node:
walk(item)
for rel in REQUIRED_JSON_FILES:
path = root / rel
if not path.exists():
rep.add(f"json.{rel}", False, "file missing")
continue
try:
doc = json.loads(path.read_text())
except json.JSONDecodeError as exc:
rep.add(f"json.{rel}", False, f"invalid JSON: {exc}")
continue
well_formed = isinstance(doc, dict) and ("Statement" in doc or "schemaVersion" in doc)
rep.add(f"json.{rel}", well_formed, "parsed and well formed")
walk(doc)
return actions
# --------------------------------------------------------------- secret scan
def scan_secrets(root: Path, rep: Report) -> list[str]:
hits: list[str] = []
for path in sorted(root.rglob("*")):
if not path.is_file():
continue
if any(part in {".git", "__pycache__", ".cache"} for part in path.parts):
continue
if path.suffix.lower() not in TEXT_SUFFIXES:
continue
try:
text = path.read_text(errors="ignore")
except OSError:
continue
for name, pattern in SECRET_PATTERNS.items():
if pattern.search(text):
hits.append(f"{path.relative_to(root)}:{name}")
rep.add(
"secrets.none_committed",
not hits,
f"POSSIBLE SECRETS: {hits}"
if hits
else "no AWS keys, private keys, tokens or Steam passwords found",
)
return hits
# ------------------------------------------------------------------- scripts
def check_script_invariants(root: Path, rep: Report) -> None:
launch = root / "launch.sh"
if launch.exists():
text = launch.read_text()
rep.add("launch.strict_mode", "set -euo pipefail" in text, "bash strict mode enabled")
rep.add(
"launch.delegates_ingress",
"SecurityGroupIngress" not in text,
"launch script does not create its own ingress rules",
)
bootstrap = root / "scripts" / "bootstrap.ps1"
if bootstrap.exists():
text = bootstrap.read_text()
rep.add(
"bootstrap.driver_registration",
"vGamingMarketplace" in text and "GridSwCert" in text,
"vGaming registry value and licensing cert handled",
)
rep.add(
"bootstrap.power_settings",
"standby-timeout-ac 0" in text,
"host will not sleep mid-stream",
)
diagnose = root / "scripts" / "diagnose.ps1"
if diagnose.exists():
text = diagnose.read_text()
rep.add(
"diagnose.emit_json_verdict",
"ok =" in text or '"ok"' in text,
"emits an ok flag for CloudWatch metric filters",
)
# ---------------------------------------------------------------------- main
def main() -> int:
ap = argparse.ArgumentParser(description="Validate the AWS Steam GPU Launch Kit")
ap.add_argument("--root", default=".", help="repo root (default: cwd)")
ap.add_argument("--pretty", action="store_true", help="human-readable output")
args = ap.parse_args()
root = Path(args.root).resolve()
rep = Report()
cfn_actions = check_cloudformation(root / "cloudformation" / "steam-gpu-host.yaml", rep)
json_actions = check_json_files(root, rep)
check_script_invariants(root, rep)
scan_secrets(root, rep)
actions = sorted(set(cfn_actions) | set(json_actions))
report = {
"tool": "validate.py",
"root": str(root),
"ok": rep.ok,
"failed_checks": rep.failures(),
"checks": rep.checks,
"iam_action_surface": actions,
}
if args.pretty:
passed = len(rep.checks) - len(rep.failures())
print(f"\n {len(rep.checks)} checks, {passed} passed, {len(rep.failures())} failed\n")
for c in rep.checks:
mark = "PASS" if c["ok"] else "FAIL"
print(f" [{mark}] {c['check']:<38} {c['detail']}")
print(f"\n IAM actions granted to the instance role ({len(actions)}):")
for a in actions:
print(f" - {a}")
print()
print(json.dumps({"ok": report["ok"], "failed_checks": report["failed_checks"]}))
else:
print(json.dumps(report, separators=(",", ":")))
return 0 if rep.ok else 1
if __name__ == "__main__":
sys.exit(main())