container security

Performing Kubernetes CIS Benchmark with kube-bench

Audit Kubernetes cluster security posture against CIS benchmarks using kube-bench with automated checks for control plane, worker nodes, and RBAC.

aquasecuritycis-benchmarkcompliancehardeningkube-benchkubernetes
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

kube-bench is an open-source Go tool by Aqua Security that runs the CIS Kubernetes Benchmark checks. It verifies control plane, etcd, worker node, and policy configurations against security best practices, producing actionable pass/fail/warn reports.

When to Use

  • When conducting security assessments that involve performing kubernetes cis benchmark with kube bench
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Kubernetes cluster (v1.24+)
  • kubectl with cluster-admin access
  • Node access for direct runs or privileged pod access

Installation

# Binary installation
curl -L https://github.com/aquasecurity/kube-bench/releases/download/v0.7.3/kube-bench_0.7.3_linux_amd64.tar.gz | tar xz
sudo mv kube-bench /usr/local/bin/
 
# Run as Kubernetes Job
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
kubectl logs job/kube-bench
 
# Run as a pod with host access
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job-master.yaml
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job-node.yaml

Running Benchmarks

Full Benchmark

# Run all checks (auto-detects node type)
kube-bench run
 
# Run with JSON output
kube-bench run --json > kube-bench-results.json
 
# Run with JUnit output for CI
kube-bench run --junit > kube-bench-results.xml

Component-Specific Checks

# Control plane (master) checks
kube-bench run --targets master
 
# Worker node checks
kube-bench run --targets node
 
# etcd checks
kube-bench run --targets etcd
 
# Policies checks
kube-bench run --targets policies
 
# Control plane + etcd
kube-bench run --targets master,etcd

Managed Kubernetes

# Amazon EKS
kube-bench run --benchmark eks-1.2.0
 
# Google GKE
kube-bench run --benchmark gke-1.4.0
 
# Azure AKS
kube-bench run --benchmark aks-1.0
 
# Red Hat OpenShift
kube-bench run --benchmark rh-1.0

Filtering Results

# Show only failures
kube-bench run --targets master | grep "\[FAIL\]"
 
# Run specific check
kube-bench run --check 1.2.1
 
# Run check group
kube-bench run --group 1.2

CIS Benchmark Sections

Section Component Key Checks
1.1 Control Plane - API Server Anonymous auth, RBAC, audit logging
1.2 Control Plane - API Server Admission controllers, encryption
1.3 Control Plane - Controller Manager Service account tokens, bind address
1.4 Control Plane - Scheduler Profiling, bind address
2.1 etcd Client cert auth, peer encryption
3.1 Control Plane - Authentication OIDC, client certs
4.1 Worker - kubelet Anonymous auth, authorization
4.2 Worker - kubelet TLS, read-only port
5.1 Policies - RBAC Cluster-admin usage, service accounts
5.2 Policies - Pod Security Privileged, host namespaces
5.3 Policies - Network Network policies per namespace
5.7 Policies - General Secrets, security context

Output Example

[INFO] 1 Control Plane Security Configuration
[INFO] 1.1 Control Plane Node Configuration Files
[PASS] 1.1.1 Ensure that the API server pod specification file permissions are set to 600
[PASS] 1.1.2 Ensure that the API server pod specification file ownership is set to root:root
[FAIL] 1.1.3 Ensure that the controller manager pod specification file permissions are set to 600
[WARN] 1.1.4 Ensure that the scheduler pod specification file permissions are set to 600
 
== Summary ==
45 checks PASS
12 checks FAIL
8 checks WARN
0 checks INFO

CI/CD Integration

GitHub Actions

name: CIS Benchmark
on:
  schedule:
    - cron: '0 6 * * 1'
 
jobs:
  kube-bench:
    runs-on: ubuntu-latest
    steps:
      - name: Configure kubectl
        uses: azure/setup-kubectl@v3
 
      - name: Run kube-bench
        run: |
          kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
          kubectl wait --for=condition=complete job/kube-bench --timeout=120s
          kubectl logs job/kube-bench > kube-bench-report.txt
 
      - name: Check for failures
        run: |
          FAILS=$(grep -c "\[FAIL\]" kube-bench-report.txt || true)
          echo "Failed checks: $FAILS"
          if [ "$FAILS" -gt 0 ]; then
            echo "::warning::$FAILS CIS benchmark checks failed"
          fi
 
      - name: Upload report
        uses: actions/upload-artifact@v4
        with:
          name: kube-bench-report
          path: kube-bench-report.txt

Remediation Examples

1.2.1 - Ensure --anonymous-auth is set to false

# /etc/kubernetes/manifests/kube-apiserver.yaml
spec:
  containers:
  - command:
    - kube-apiserver
    - --anonymous-auth=false

4.2.1 - Ensure --anonymous-auth is set to false on kubelet

# /var/lib/kubelet/config.yaml
authentication:
  anonymous:
    enabled: false
  webhook:
    enabled: true

5.2.1 - Minimize wildcard RBAC

# Find roles with wildcard permissions
kubectl get clusterroles -o json | jq '.items[] | select(.rules[].resources[] == "*") | .metadata.name'

Best Practices

  1. Run kube-bench before and after cluster provisioning
  2. Schedule weekly scans via CronJob for drift detection
  3. Export JSON for SIEM/compliance reporting
  4. Fix FAIL items first, then address WARN items
  5. Use benchmark profiles matching your Kubernetes distribution
  6. Track score over time to measure security posture improvement
  7. Combine with admission controllers to prevent drift
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.7 KB

API Reference — Performing Kubernetes CIS Benchmark with kube-bench

Libraries Used

  • subprocess: Execute kube-bench, kubectl commands
  • json: Parse kube-bench JSON output and kubectl resource data

CLI Interface

python agent.py bench [--target master|node|etcd|policies] [--benchmark cis-1.8]
python agent.py pods [--namespace default]
python agent.py rbac
python agent.py netpol [--namespace default]

Core Functions

run_kube_bench(target, benchmark) — Execute CIS benchmark scan

Runs kube-bench with JSON output. Returns pass/fail/warn/info summary and compliance percentage. Targets: master, controlplane, node, etcd, policies.

check_pod_security(namespace) — Audit pod security contexts

Checks for: privileged containers, root user, writable root filesystem, dangerous capabilities (SYS_ADMIN, NET_ADMIN, ALL), privilege escalation.

check_rbac_config() — Audit cluster RBAC

Detects wildcard permissions (* verbs on * resources), pod creation rights, and cluster-admin bindings to service accounts/users.

check_network_policies(namespace) — Verify network segmentation

Flags namespaces with no NetworkPolicy. Lists policy coverage details.

Pod Security Issues Detected

Issue Description
PRIVILEGED_CONTAINER Container runs in privileged mode
RUNS_AS_ROOT No runAsNonRoot constraint
WRITABLE_ROOT_FS readOnlyRootFilesystem not set
DANGEROUS_CAPABILITIES SYS_ADMIN/NET_ADMIN/ALL added
PRIVILEGE_ESCALATION_ALLOWED allowPrivilegeEscalation not false

Dependencies

System: kube-bench (Aqua Security), kubectl with cluster access No Python packages required.

standards.md1.4 KB

Standards and References - Kubernetes CIS Benchmark with kube-bench

CIS Kubernetes Benchmark Versions

Benchmark Version Kubernetes Versions Released
CIS 1.8 1.27+ 2023
CIS 1.7 1.25-1.26 2022
CIS 1.6 1.20-1.24 2021
EKS 1.2.0 EKS 1.23+ 2023
GKE 1.4.0 GKE 1.25+ 2023
AKS 1.0 AKS 1.24+ 2023

NIST SP 800-53 Rev 5 Mappings

CIS Check NIST Control Description
1.2.1 Anonymous auth AC-14 Permitted Actions without Authentication
1.2.6 RBAC AC-3 Access Enforcement
1.2.22 Audit logging AU-2, AU-3 Audit Events, Content of Audit Records
2.1 etcd encryption SC-28 Protection of Information at Rest
4.2.1 kubelet auth IA-2 Identification and Authentication
5.1 RBAC policies AC-6 Least Privilege
5.2 Pod security CM-7 Least Functionality
5.3 Network policies SC-7 Boundary Protection

NSA/CISA Kubernetes Hardening Guide v1.2

  • Section 1: Kubernetes Pod Security
  • Section 2: Network Separation and Hardening
  • Section 3: Authentication and Authorization
  • Section 4: Audit Logging and Threat Detection

Compliance Frameworks

PCI DSS v4.0

  • Req 2.2: Develop configuration standards for all system components
  • Req 6.3.2: Develop software securely

SOC 2

  • CC6.1: Logical access security for system components
  • CC8.1: Change management controls
workflows.md2.0 KB

Workflow - Kubernetes CIS Benchmark with kube-bench

Phase 1: Initial Assessment

# Deploy kube-bench as Job
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
kubectl wait --for=condition=complete job/kube-bench --timeout=300s
kubectl logs job/kube-bench > baseline-report.txt
kubectl delete job kube-bench

Phase 2: Analyze Results

# Count results by status
PASS=$(grep -c "\[PASS\]" baseline-report.txt)
FAIL=$(grep -c "\[FAIL\]" baseline-report.txt)
WARN=$(grep -c "\[WARN\]" baseline-report.txt)
echo "PASS: $PASS | FAIL: $FAIL | WARN: $WARN"
 
# Extract failed checks with remediation
grep -A 2 "\[FAIL\]" baseline-report.txt

Phase 3: Remediate Failures

Priority order:

  1. Control plane authentication (Section 1.2)
  2. etcd security (Section 2)
  3. Worker node kubelet (Section 4)
  4. RBAC and policies (Section 5)

Apply each remediation, then re-run affected section:

kube-bench run --targets master --check 1.2.1

Phase 4: Continuous Monitoring

# kube-bench-cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: kube-bench-scan
  namespace: security
spec:
  schedule: "0 6 * * 1"
  jobTemplate:
    spec:
      template:
        spec:
          hostPID: true
          containers:
          - name: kube-bench
            image: aquasec/kube-bench:v0.7.3
            command: ["kube-bench", "run", "--json"]
            volumeMounts:
            - name: var-lib-kubelet
              mountPath: /var/lib/kubelet
              readOnly: true
            - name: etc-kubernetes
              mountPath: /etc/kubernetes
              readOnly: true
          volumes:
          - name: var-lib-kubelet
            hostPath:
              path: /var/lib/kubelet
          - name: etc-kubernetes
            hostPath:
              path: /etc/kubernetes
          restartPolicy: Never

Phase 5: Track Improvement

Compare PASS/FAIL/WARN counts across scans to measure security posture improvement over time.

Scripts 2

agent.py7.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for performing Kubernetes CIS benchmark assessment with kube-bench."""

import json
import argparse
import subprocess
from datetime import datetime


def run_kube_bench(target="node", benchmark=None):
    """Execute kube-bench CIS benchmark scan."""
    cmd = ["kube-bench", "run", "--json"]
    if target in ("master", "controlplane"):
        cmd += ["--targets", "master"]
    elif target == "node":
        cmd += ["--targets", "node"]
    elif target == "etcd":
        cmd += ["--targets", "etcd"]
    elif target == "policies":
        cmd += ["--targets", "policies"]
    if benchmark:
        cmd += ["--benchmark", benchmark]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
        data = json.loads(result.stdout)
        tests = data.get("Tests", data.get("tests", []))
        summary = {"pass": 0, "fail": 0, "warn": 0, "info": 0}
        failures = []
        for section in tests:
            for test in section.get("results", section.get("Results", [])):
                status = test.get("status", "").lower()
                summary[status] = summary.get(status, 0) + 1
                if status == "fail":
                    failures.append({
                        "id": test.get("test_number", test.get("TestNumber", "")),
                        "desc": test.get("test_desc", test.get("TestDesc", ""))[:200],
                        "remediation": test.get("remediation", test.get("Remediation", ""))[:300],
                        "scored": test.get("scored", test.get("IsScored", True)),
                    })
        return {
            "target": target, "timestamp": datetime.utcnow().isoformat(),
            "summary": summary, "total_checks": sum(summary.values()),
            "compliance_pct": round(summary["pass"] / max(sum(summary.values()), 1) * 100, 1),
            "failures": failures,
        }
    except FileNotFoundError:
        return {"error": "kube-bench not found — install from github.com/aquasecurity/kube-bench"}
    except json.JSONDecodeError:
        return {"error": "Failed to parse kube-bench output", "raw": result.stdout[:500]}
    except Exception as e:
        return {"error": str(e)}


def check_pod_security(namespace="default"):
    """Check pod security settings via kubectl."""
    cmd = ["kubectl", "get", "pods", "-n", namespace, "-o", "json"]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        data = json.loads(result.stdout)
        pods = data.get("items", [])
        findings = []
        for pod in pods:
            name = pod.get("metadata", {}).get("name", "")
            for container in pod.get("spec", {}).get("containers", []):
                sc = container.get("securityContext", {})
                issues = []
                if sc.get("privileged"):
                    issues.append("PRIVILEGED_CONTAINER")
                if sc.get("runAsUser") == 0 or not sc.get("runAsNonRoot"):
                    issues.append("RUNS_AS_ROOT")
                if not sc.get("readOnlyRootFilesystem"):
                    issues.append("WRITABLE_ROOT_FS")
                caps = sc.get("capabilities", {})
                if caps.get("add") and any(c in caps["add"] for c in ["SYS_ADMIN", "NET_ADMIN", "ALL"]):
                    issues.append("DANGEROUS_CAPABILITIES")
                if not sc.get("allowPrivilegeEscalation") is False:
                    issues.append("PRIVILEGE_ESCALATION_ALLOWED")
                if issues:
                    findings.append({"pod": name, "container": container.get("name"), "issues": issues})
        return {
            "namespace": namespace, "total_pods": len(pods),
            "pods_with_issues": len(findings), "findings": findings,
        }
    except FileNotFoundError:
        return {"error": "kubectl not found"}
    except Exception as e:
        return {"error": str(e)}


def check_rbac_config():
    """Audit RBAC configuration for overly permissive roles."""
    findings = []
    for resource in ["clusterroles", "clusterrolebindings"]:
        cmd = ["kubectl", "get", resource, "-o", "json"]
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            data = json.loads(result.stdout)
            for item in data.get("items", []):
                name = item.get("metadata", {}).get("name", "")
                if resource == "clusterroles":
                    for rule in item.get("rules", []):
                        verbs = rule.get("verbs", [])
                        resources = rule.get("resources", [])
                        if "*" in verbs and "*" in resources:
                            findings.append({"type": "clusterrole", "name": name, "issue": "WILDCARD_ALL_PERMISSIONS"})
                        elif "create" in verbs and "pods" in resources:
                            findings.append({"type": "clusterrole", "name": name, "issue": "CAN_CREATE_PODS"})
                elif resource == "clusterrolebindings":
                    subjects = item.get("subjects", [])
                    role_ref = item.get("roleRef", {}).get("name", "")
                    if role_ref == "cluster-admin":
                        for subj in subjects:
                            findings.append({
                                "type": "clusterrolebinding", "name": name,
                                "issue": f"CLUSTER_ADMIN_BOUND_TO_{subj.get('kind', '')}:{subj.get('name', '')}",
                            })
        except Exception as e:
            findings.append({"type": resource, "error": str(e)})
    return {"total_findings": len(findings), "findings": findings}


def check_network_policies(namespace="default"):
    """Verify network policies exist and cover pods."""
    cmd = ["kubectl", "get", "networkpolicies", "-n", namespace, "-o", "json"]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        data = json.loads(result.stdout)
        policies = data.get("items", [])
        if not policies:
            return {"namespace": namespace, "finding": "NO_NETWORK_POLICIES", "severity": "HIGH",
                    "recommendation": "Implement default-deny NetworkPolicy"}
        return {
            "namespace": namespace, "policy_count": len(policies),
            "policies": [{"name": p["metadata"]["name"],
                          "pod_selector": p.get("spec", {}).get("podSelector", {}),
                          "ingress_rules": len(p.get("spec", {}).get("ingress", [])),
                          "egress_rules": len(p.get("spec", {}).get("egress", []))}
                         for p in policies],
        }
    except Exception as e:
        return {"error": str(e)}


def main():
    parser = argparse.ArgumentParser(description="Kubernetes CIS Benchmark Agent (kube-bench)")
    sub = parser.add_subparsers(dest="command")
    b = sub.add_parser("bench", help="Run kube-bench CIS scan")
    b.add_argument("--target", default="node", choices=["master", "controlplane", "node", "etcd", "policies"])
    b.add_argument("--benchmark", help="CIS benchmark version")
    p = sub.add_parser("pods", help="Check pod security settings")
    p.add_argument("--namespace", default="default")
    sub.add_parser("rbac", help="Audit RBAC configuration")
    n = sub.add_parser("netpol", help="Check network policies")
    n.add_argument("--namespace", default="default")
    args = parser.parse_args()
    if args.command == "bench":
        result = run_kube_bench(args.target, args.benchmark)
    elif args.command == "pods":
        result = check_pod_security(args.namespace)
    elif args.command == "rbac":
        result = check_rbac_config()
    elif args.command == "netpol":
        result = check_network_policies(args.namespace)
    else:
        parser.print_help()
        return
    print(json.dumps(result, indent=2, default=str))


if __name__ == "__main__":
    main()
process.py6.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
kube-bench CIS Benchmark Reporter - Parse kube-bench JSON output
and generate compliance reports with trend tracking.
"""

import json
import sys
import argparse
from pathlib import Path
from datetime import datetime
from collections import Counter


def parse_kube_bench_json(filepath: str) -> dict:
    """Parse kube-bench JSON output file."""
    path = Path(filepath)
    if not path.exists():
        print(f"File not found: {filepath}", file=sys.stderr)
        sys.exit(1)
    return json.loads(path.read_text())


def extract_checks(data: dict) -> list:
    """Extract all individual checks from kube-bench results."""
    checks = []
    for control in data.get("Controls", []):
        section = control.get("id", "")
        section_text = control.get("text", "")
        for group in control.get("tests", []):
            group_id = group.get("section", "")
            for result in group.get("results", []):
                checks.append({
                    "section": section,
                    "section_text": section_text,
                    "group": group_id,
                    "id": result.get("test_number", ""),
                    "description": result.get("test_desc", ""),
                    "status": result.get("status", ""),
                    "scored": result.get("scored", False),
                    "remediation": result.get("remediation", ""),
                    "reason": result.get("reason", ""),
                })
    return checks


def generate_summary(checks: list) -> dict:
    """Generate summary statistics."""
    status_counts = Counter(c["status"] for c in checks)
    section_counts = {}
    for c in checks:
        sec = c["section"]
        if sec not in section_counts:
            section_counts[sec] = {"section_text": c["section_text"], "PASS": 0, "FAIL": 0, "WARN": 0, "INFO": 0}
        status = c["status"]
        if status in section_counts[sec]:
            section_counts[sec][status] += 1

    total = len(checks)
    passed = status_counts.get("PASS", 0)
    score = (passed / total * 100) if total > 0 else 0

    return {
        "total_checks": total,
        "pass": status_counts.get("PASS", 0),
        "fail": status_counts.get("FAIL", 0),
        "warn": status_counts.get("WARN", 0),
        "info": status_counts.get("INFO", 0),
        "score_percent": round(score, 1),
        "by_section": section_counts,
    }


def generate_report(data: dict, output_path: str = None) -> str:
    """Generate markdown CIS benchmark report."""
    checks = extract_checks(data)
    summary = generate_summary(checks)
    timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")

    report = f"""# CIS Kubernetes Benchmark Report

**Date:** {timestamp}
**Total Checks:** {summary['total_checks']}
**Score:** {summary['score_percent']}%

## Summary

| Status | Count |
|--------|-------|
| PASS | {summary['pass']} |
| FAIL | {summary['fail']} |
| WARN | {summary['warn']} |
| INFO | {summary['info']} |

## Results by Section

| Section | Description | Pass | Fail | Warn |
|---------|-------------|------|------|------|
"""
    for sec_id, sec in sorted(summary["by_section"].items()):
        report += f"| {sec_id} | {sec['section_text']} | {sec['PASS']} | {sec['FAIL']} | {sec['WARN']} |\n"

    failed = [c for c in checks if c["status"] == "FAIL"]
    if failed:
        report += "\n## Failed Checks (Requires Remediation)\n\n"
        for c in failed:
            report += f"### {c['id']} - {c['description']}\n"
            report += f"- **Status:** FAIL\n"
            report += f"- **Scored:** {c['scored']}\n"
            if c['remediation']:
                report += f"- **Remediation:** {c['remediation']}\n"
            report += "\n"

    if output_path:
        Path(output_path).write_text(report)
        print(f"Report written to {output_path}")

    return report


def compare_scans(current_file: str, previous_file: str):
    """Compare two kube-bench scan results."""
    current = extract_checks(parse_kube_bench_json(current_file))
    previous = extract_checks(parse_kube_bench_json(previous_file))

    curr_summary = generate_summary(current)
    prev_summary = generate_summary(previous)

    print("\n=== CIS Benchmark Comparison ===\n")
    print(f"{'Metric':<20} {'Previous':<12} {'Current':<12} {'Change'}")
    print("-" * 55)

    for metric in ["pass", "fail", "warn"]:
        prev_val = prev_summary[metric]
        curr_val = curr_summary[metric]
        change = curr_val - prev_val
        sign = "+" if change > 0 else ""
        print(f"{metric.upper():<20} {prev_val:<12} {curr_val:<12} {sign}{change}")

    print(f"{'SCORE':<20} {prev_summary['score_percent']}%{'':<7} {curr_summary['score_percent']}%")


def main():
    parser = argparse.ArgumentParser(description="kube-bench CIS Benchmark Reporter")
    subparsers = parser.add_subparsers(dest="command")

    report_cmd = subparsers.add_parser("report", help="Generate report from kube-bench JSON")
    report_cmd.add_argument("input", help="kube-bench JSON output file")
    report_cmd.add_argument("--output", "-o", help="Output markdown report path")

    compare_cmd = subparsers.add_parser("compare", help="Compare two scan results")
    compare_cmd.add_argument("current", help="Current scan JSON")
    compare_cmd.add_argument("previous", help="Previous scan JSON")

    summary_cmd = subparsers.add_parser("summary", help="Print summary from JSON")
    summary_cmd.add_argument("input", help="kube-bench JSON output file")

    args = parser.parse_args()

    if args.command == "report":
        data = parse_kube_bench_json(args.input)
        report = generate_report(data, args.output)
        if not args.output:
            print(report)

    elif args.command == "compare":
        compare_scans(args.current, args.previous)

    elif args.command == "summary":
        data = parse_kube_bench_json(args.input)
        checks = extract_checks(data)
        summary = generate_summary(checks)
        print(json.dumps(summary, indent=2))

    else:
        parser.print_help()


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.0 KB
Keep exploring