SSZcreate/Pentab_server / .agents/skills/cybersecurity/skills/implementing-gcp-binary-authorization
implementing-gcp-binary-authorization
VerifiedImplements GCP Binary Authorization end to end, including creating KMS-backed attestors, Container Analysis notes, deploy-time policies, and signing image attestations, so that only trusted, verified images deploy to GKE and Cloud Run. Use when enforcing container supply-chain integrity or deploy-time attestation checks on GCP.
| File | Kind | Size |
|---|---|---|
| LICENSE | other | 11.0 KB |
| SKILL.md | skill md | 7.7 KB |
| assets/template.md | markdown | 690 B |
| references/api-reference.md | markdown | 1.8 KB |
| references/standards.md | markdown | 473 B |
| references/workflows.md | markdown | 653 B |
| scripts/agent.py | script | 7.8 KB |
| scripts/process.py | script | 6.0 KB |
scripts/agent.py
View on GitHub#!/usr/bin/env python3
"""Agent for auditing and managing GCP Binary Authorization policies."""
import json
import argparse
import subprocess
from datetime import datetime
def run_gcloud(args_list):
"""Run a gcloud command and return parsed JSON output."""
cmd = ["gcloud"] + args_list + ["--format=json"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return {"error": result.stderr.strip()}
try:
return json.loads(result.stdout) if result.stdout.strip() else {}
except json.JSONDecodeError:
return {"raw": result.stdout.strip()}
def get_binauthz_policy(project):
"""Retrieve the Binary Authorization policy for a project."""
return run_gcloud(["container", "binauthz", "policy", "export",
"--project", project])
def list_attestors(project):
"""List all attestors in the project."""
return run_gcloud(["container", "binauthz", "attestors", "list",
"--project", project])
def list_attestations(project, attestor):
"""List attestations for a given attestor."""
return run_gcloud(["container", "binauthz", "attestations", "list",
"--attestor", attestor, "--attestor-project", project])
def verify_image_attested(project, attestor, image_url):
"""Check if a container image has a valid attestation."""
result = run_gcloud(["container", "binauthz", "attestations", "list",
"--attestor", attestor, "--attestor-project", project,
"--artifact-url", image_url])
if isinstance(result, list) and len(result) > 0:
return {"image": image_url, "attested": True, "attestation_count": len(result)}
return {"image": image_url, "attested": False, "attestation_count": 0}
def audit_policy(policy):
"""Audit a Binary Authorization policy for security issues."""
findings = []
if isinstance(policy, dict) and "error" in policy:
return [{"issue": "Cannot retrieve policy", "severity": "CRITICAL",
"detail": policy["error"]}]
default_rule = policy.get("defaultAdmissionRule", {})
eval_mode = default_rule.get("evaluationMode", "")
enforce_mode = default_rule.get("enforcementMode", "")
if eval_mode == "ALWAYS_ALLOW":
findings.append({"issue": "Default rule allows all images",
"severity": "CRITICAL",
"recommendation": "Set evaluationMode to REQUIRE_ATTESTATION"})
if enforce_mode == "DRYRUN_AUDIT_LOG_ONLY":
findings.append({"issue": "Default rule is dry-run only",
"severity": "HIGH",
"recommendation": "Set enforcementMode to ENFORCED_BLOCK_AND_AUDIT_LOG"})
attestors = default_rule.get("requireAttestationsBy", [])
if eval_mode == "REQUIRE_ATTESTATION" and not attestors:
findings.append({"issue": "Attestation required but no attestors configured",
"severity": "CRITICAL"})
global_eval = policy.get("globalPolicyEvaluationMode", "")
if global_eval != "ENABLE":
findings.append({"issue": "Global policy evaluation not enabled",
"severity": "MEDIUM",
"recommendation": "Set globalPolicyEvaluationMode to ENABLE"})
whitelist = policy.get("admissionWhitelistPatterns", [])
for pattern in whitelist:
name = pattern.get("namePattern", "")
if name.endswith("/**") or name.endswith("/*"):
if not any(safe in name for safe in ["gcr.io/google", "k8s.gcr.io", "gke.gcr.io"]):
findings.append({"issue": f"Broad whitelist pattern: {name}",
"severity": "HIGH",
"recommendation": "Restrict whitelist to specific images"})
cluster_rules = policy.get("clusterAdmissionRules", {})
for cluster, rule in cluster_rules.items():
if rule.get("evaluationMode") == "ALWAYS_ALLOW":
findings.append({"issue": f"Cluster {cluster} allows all images",
"severity": "HIGH"})
if not findings:
findings.append({"issue": "No issues found", "severity": "INFO"})
return findings
def generate_policy(project, attestors, allowed_patterns=None):
"""Generate a Binary Authorization policy YAML."""
whitelist = allowed_patterns or [
"gcr.io/google_containers/*", "gcr.io/google-containers/*",
"k8s.gcr.io/**", "gke.gcr.io/**", "gcr.io/stackdriver-agents/*",
]
policy = {
"admissionWhitelistPatterns": [{"namePattern": p} for p in whitelist],
"defaultAdmissionRule": {
"evaluationMode": "REQUIRE_ATTESTATION",
"enforcementMode": "ENFORCED_BLOCK_AND_AUDIT_LOG",
"requireAttestationsBy": [
f"projects/{project}/attestors/{a}" for a in attestors
],
},
"globalPolicyEvaluationMode": "ENABLE",
}
return policy
def check_cv_status(project, cluster, zone):
"""Check continuous validation status on a GKE cluster."""
result = run_gcloud(["container", "clusters", "describe", cluster,
"--zone", zone, "--project", project])
if isinstance(result, dict):
binauthz = result.get("binaryAuthorization", {})
return {
"cluster": cluster,
"enabled": binauthz.get("enabled", False),
"evaluation_mode": binauthz.get("evaluationMode", ""),
}
return {"cluster": cluster, "error": "Cannot retrieve cluster info"}
def main():
parser = argparse.ArgumentParser(description="GCP Binary Authorization Agent")
parser.add_argument("--project", required=True, help="GCP project ID")
parser.add_argument("--action", choices=["audit", "list-attestors", "verify",
"generate", "cv-status"],
default="audit")
parser.add_argument("--attestor", help="Attestor name")
parser.add_argument("--image", help="Container image URL for verification")
parser.add_argument("--cluster", help="GKE cluster name")
parser.add_argument("--zone", default="us-central1-a")
parser.add_argument("--output", default="binauthz_report.json")
args = parser.parse_args()
report = {"generated_at": datetime.utcnow().isoformat(), "project": args.project,
"results": {}}
if args.action == "audit":
policy = get_binauthz_policy(args.project)
findings = audit_policy(policy)
report["results"]["policy"] = policy
report["results"]["findings"] = findings
for f in findings:
print(f"[{f['severity']}] {f['issue']}")
elif args.action == "list-attestors":
attestors = list_attestors(args.project)
report["results"]["attestors"] = attestors
print(f"[+] Found {len(attestors) if isinstance(attestors, list) else 0} attestors")
elif args.action == "verify" and args.attestor and args.image:
result = verify_image_attested(args.project, args.attestor, args.image)
report["results"]["verification"] = result
status = "ATTESTED" if result["attested"] else "NOT ATTESTED"
print(f"[+] {args.image}: {status}")
elif args.action == "generate":
attestors = [args.attestor] if args.attestor else ["prod-build-attestor"]
policy = generate_policy(args.project, attestors)
report["results"]["generated_policy"] = policy
print("[+] Policy generated")
elif args.action == "cv-status" and args.cluster:
status = check_cv_status(args.project, args.cluster, args.zone)
report["results"]["cv_status"] = status
print(f"[+] CV enabled: {status.get('enabled', False)}")
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 318k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 117k | Updated | Claude CodeCodex | Verified | Install |