File size: 15,083 Bytes
0c1b2f9 209b1ed a9261e4 209b1ed 0c1b2f9 a9261e4 0c1b2f9 209b1ed 0c1b2f9 209b1ed 0c1b2f9 a9261e4 0c1b2f9 a9261e4 0c1b2f9 209b1ed 0c1b2f9 a9261e4 0c1b2f9 a9261e4 0c1b2f9 a9261e4 0c1b2f9 a9261e4 0c1b2f9 a9261e4 0c1b2f9 a9261e4 0c1b2f9 209b1ed 0c1b2f9 a9261e4 0c1b2f9 209b1ed 0c1b2f9 209b1ed 0c1b2f9 209b1ed 0c1b2f9 209b1ed 0c1b2f9 209b1ed 0c1b2f9 209b1ed 0c1b2f9 209b1ed a9261e4 209b1ed 0c1b2f9 209b1ed 0c1b2f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 | #!/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())
|