Skip to content

Kube-bench Cheatsheet

- :material-content-copy: **[Copy to Clipboard](#copy-to-clipboard)** - :material-file-pdf-box: **[Download PDF](#download-pdf)**

Overview

Kube-bench is a security tool that checks whether Kubernetes is deployed securely by running the checks documented in the CIS Kubernetes Benchmark. It's an essential tool for ensuring Kubernetes cluster security compliance and identifying potential security misconfigurations.

Key Features

  • CIS Benchmark Compliance: Automated checks against CIS Kubernetes Benchmark
  • Multiple Kubernetes Distributions: Support for various K8s distributions and cloud providers
  • Comprehensive Reporting: Detailed reports with remediation guidance
  • CI/CD Integration: Easy integration into security pipelines
  • Custom Configurations: Support for custom benchmark configurations
  • Multiple Output Formats: JSON, YAML, and text output formats

Installation

Binary Installation

# Download latest release
curl -L https://github.com/aquasecurity/kube-bench/releases/latest/download/kube-bench_$(uname -s)_$(uname -m).tar.gz -o kube-bench.tar.gz
tar -xzf kube-bench.tar.gz
sudo mv kube-bench /usr/local/bin/

# Make executable
sudo chmod +x /usr/local/bin/kube-bench

# Verify installation
kube-bench version

Package Manager Installation

# Homebrew (macOS/Linux)
brew install kube-bench

# Snap (Linux)
sudo snap install kube-bench

# APT (Ubuntu/Debian)
curl -s https://aquasecurity.github.io/kube-bench/deb/public.key | sudo apt-key add -
echo "deb https://aquasecurity.github.io/kube-bench/deb $(lsb_release -sc) main" | sudo tee -a /etc/apt/sources.list.d/kube-bench.list
sudo apt-get update
sudo apt-get install kube-bench

Container Installation

# Pull Docker image
docker pull aquasec/kube-bench:latest

# Run as container
docker run --rm -v `pwd`:/host aquasec/kube-bench:latest install
./kube-bench

Kubernetes Job Installation

# kube-bench-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: kube-bench
spec:
  template:
    spec:
      hostPID: true
      nodeSelector:
        kubernetes.io/os: linux
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      containers:
      - name: kube-bench
        image: aquasec/kube-bench:latest
        command: ["kube-bench"]
        volumeMounts:
        - name: var-lib-etcd
          mountPath: /var/lib/etcd
          readOnly: true
        - name: var-lib-kubelet
          mountPath: /var/lib/kubelet
          readOnly: true
        - name: var-lib-kube-scheduler
          mountPath: /var/lib/kube-scheduler
          readOnly: true
        - name: var-lib-kube-controller-manager
          mountPath: /var/lib/kube-controller-manager
          readOnly: true
        - name: etc-systemd
          mountPath: /etc/systemd
          readOnly: true
        - name: lib-systemd
          mountPath: /lib/systemd/
          readOnly: true
        - name: srv-kubernetes
          mountPath: /srv/kubernetes/
          readOnly: true
        - name: etc-kubernetes
          mountPath: /etc/kubernetes
          readOnly: true
        - name: usr-bin
          mountPath: /usr/local/mount-from-host/bin
          readOnly: true
      restartPolicy: Never
      volumes:
      - name: var-lib-etcd
        hostPath:
          path: "/var/lib/etcd"
      - name: var-lib-kubelet
        hostPath:
          path: "/var/lib/kubelet"
      - name: var-lib-kube-scheduler
        hostPath:
          path: "/var/lib/kube-scheduler"
      - name: var-lib-kube-controller-manager
        hostPath:
          path: "/var/lib/kube-controller-manager"
      - name: etc-systemd
        hostPath:
          path: "/etc/systemd"
      - name: lib-systemd
        hostPath:
          path: "/lib/systemd"
      - name: srv-kubernetes
        hostPath:
          path: "/srv/kubernetes"
      - name: etc-kubernetes
        hostPath:
          path: "/etc/kubernetes"
      - name: usr-bin
        hostPath:
          path: "/usr/bin"

Basic Usage

Running Basic Scans

# Run default scan
kube-bench

# Run specific benchmark version
kube-bench --benchmark cis-1.6

# Run for specific Kubernetes version
kube-bench --version 1.21

# Run with specific configuration
kube-bench --config-dir /path/to/config

Target Specific Components

# Scan master components only
kube-bench master

# Scan node components only
kube-bench node

# Scan etcd
kube-bench etcd

# Scan control plane
kube-bench controlplane

# Scan managed services (EKS, GKE, AKS)
kube-bench --benchmark eks-1.0.1
kube-bench --benchmark gke-1.0
kube-bench --benchmark aks-1.0

Output Formats

# JSON output
kube-bench --json

# YAML output
kube-bench --outputfile results.yaml --format yaml

# JUnit format
kube-bench --junit

# ASFF format (AWS Security Finding Format)
kube-bench --asff

# Save to file
kube-bench --outputfile results.json --json

Cloud Provider Specific Usage

Amazon EKS

# Run EKS-specific benchmark
kube-bench --benchmark eks-1.0.1

# EKS with specific version
kube-bench --benchmark eks-1.0.1 --version eks-1.0.1

# Run as EKS job
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job-eks.yaml

# Check job results
kubectl logs job/kube-bench

Google GKE

# Run GKE-specific benchmark
kube-bench --benchmark gke-1.0

# GKE with custom configuration
kube-bench --benchmark gke-1.0 --config-dir /opt/kube-bench/cfg/

# Run as GKE job
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job-gke.yaml

Azure AKS

# Run AKS-specific benchmark
kube-bench --benchmark aks-1.0

# AKS with specific checks
kube-bench --benchmark aks-1.0 --check 1.1.1,1.1.2

# Run as AKS job
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job-aks.yaml

OpenShift

# Run OpenShift-specific benchmark
kube-bench --benchmark rh-0.7

# OpenShift with custom config
kube-bench --benchmark rh-0.7 --config-dir /opt/kube-bench/cfg/

Advanced Configuration

Custom Configuration Files

# config.yaml
---
controls:
  version: "cis-1.6"
  id: 1
  text: "Master Node Security Configuration"
  type: "master"
  groups:
  - id: 1.1
    text: "Master Node Configuration Files"
    checks:
    - id: 1.1.1
      text: "Ensure that the API server pod specification file permissions are set to 644 or more restrictive"
      audit: "stat -c %a /etc/kubernetes/manifests/kube-apiserver.yaml"
      tests:
        test_items:
        - flag: "644"
          compare:
            op: eq
            value: "644"
      remediation: |
        Run the below command (based on the file location on your system) on the master node.
        For example, chmod 644 /etc/kubernetes/manifests/kube-apiserver.yaml
      scored: true

Custom Benchmark Creation

# Create custom benchmark directory
mkdir -p /opt/kube-bench/cfg/custom

# Create custom configuration
cat > /opt/kube-bench/cfg/custom/config.yaml << 'EOF'
---
controls:
  version: "custom-1.0"
  id: 1
  text: "Custom Security Configuration"
  type: "master"
  groups:
  - id: 1.1
    text: "Custom Configuration Files"
    checks:
    - id: 1.1.1
      text: "Custom security check"
      audit: "custom-audit-command"
      tests:
        test_items:
        - flag: "expected-value"
          compare:
            op: eq
            value: "expected-value"
      remediation: "Custom remediation steps"
      scored: true
EOF

# Run with custom benchmark
kube-bench --config-dir /opt/kube-bench/cfg/custom --benchmark custom-1.0

CI/CD Integration

GitHub Actions

# .github/workflows/kube-bench.yml
name: Kube-bench Security Scan

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
  schedule:
    - cron: '0 2 * * *'  # Daily at 2 AM

jobs:
  kube-bench-scan:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout code
      uses: actions/checkout@v3

    - name: Set up kubectl
      uses: azure/setup-kubectl@v3
      with:
        version: 'latest'

    - name: Configure kubectl
      run: |
        echo "${{ secrets.KUBE_CONFIG }}" | base64 -d > kubeconfig
        export KUBECONFIG=kubeconfig

    - 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=300s
        kubectl logs job/kube-bench > kube-bench-results.txt

    - name: Parse results
      run: |
        # Extract summary
        grep -E "(PASS|FAIL|WARN)" kube-bench-results.txt > summary.txt

        # Count issues
        FAIL_COUNT=$(grep -c "FAIL" summary.txt || echo "0")
        WARN_COUNT=$(grep -c "WARN" summary.txt || echo "0")

        echo "FAIL_COUNT=$FAIL_COUNT" >> $GITHUB_ENV
        echo "WARN_COUNT=$WARN_COUNT" >> $GITHUB_ENV

    - name: Upload results
      uses: actions/upload-artifact@v3
      with:
        name: kube-bench-results
        path: |
          kube-bench-results.txt
          summary.txt

    - name: Comment PR
      if: github.event_name == 'pull_request'
      uses: actions/github-script@v6
      with:
        script: |
          const fs = require('fs');
          const summary = fs.readFileSync('summary.txt', 'utf8');
          const failCount = process.env.FAIL_COUNT;
          const warnCount = process.env.WARN_COUNT;

          const comment = `## Kube-bench Security Scan Results

          - **Failed checks:** ${failCount}
          - **Warning checks:** ${warnCount}

          <details>
          <summary>Detailed Results</summary>

          \`\`\`
          ${summary}
          \`\`\`

          </details>`;

          github.rest.issues.createComment({
            issue_number: context.issue.number,
            owner: context.repo.owner,
            repo: context.repo.repo,
            body: comment
          });

    - name: Fail on critical issues
      if: env.FAIL_COUNT > 0
      run: |
        echo "❌ Kube-bench found $FAIL_COUNT critical security issues"
        exit 1

GitLab CI

# .gitlab-ci.yml
stages:
  - security

kube-bench-scan:
  stage: security
  image: aquasec/kube-bench:latest
  script:
    - kube-bench --json > kube-bench-results.json
    - kube-bench --junit > kube-bench-junit.xml
  artifacts:
    reports:
      junit: kube-bench-junit.xml
    paths:
      - kube-bench-results.json
    expire_in: 1 week
  only:
    - main
    - merge_requests

kube-bench-k8s-job:
  stage: security
  image: bitnami/kubectl:latest
  script:
    - kubectl apply -f job.yaml
    - kubectl wait --for=condition=complete job/kube-bench --timeout=300s
    - kubectl logs job/kube-bench > kube-bench-k8s-results.txt
  artifacts:
    paths:
      - kube-bench-k8s-results.txt
    expire_in: 1 week
  only:
    - main

Jenkins Pipeline

// Jenkinsfile
pipeline {
    agent any

    environment {
        KUBECONFIG = credentials('kubeconfig')
    }

    stages {
        stage('Kube-bench Scan') {
            steps {
                script {
                    // Install kube-bench
                    sh '''
                        curl -L https://github.com/aquasecurity/kube-bench/releases/latest/download/kube-bench_Linux_x86_64.tar.gz -o kube-bench.tar.gz
                        tar -xzf kube-bench.tar.gz
                        chmod +x kube-bench
                    '''

                    // Run scan
                    sh '''
                        ./kube-bench --json > kube-bench-results.json
                        ./kube-bench --junit > kube-bench-junit.xml
                    '''

                    // Run as Kubernetes job
                    sh '''
                        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 > kube-bench-k8s-results.txt
                    '''
                }
            }
            post {
                always {
                    // Archive results
                    archiveArtifacts artifacts: 'kube-bench-*.json,kube-bench-*.xml,kube-bench-*.txt', fingerprint: true

                    // Publish JUnit results
                    junit 'kube-bench-junit.xml'

                    // Parse and report
                    script {
                        def results = readJSON file: 'kube-bench-results.json'
                        def failCount = 0
                        def warnCount = 0

                        results.Controls.each { control ->
                            control.Groups.each { group ->
                                group.Checks.each { check ->
                                    if (check.State == 'FAIL') failCount++
                                    if (check.State == 'WARN') warnCount++
                                }
                            }
                        }

                        echo "Kube-bench Results: ${failCount} failures, ${warnCount} warnings"

                        if (failCount > 0) {
                            currentBuild.result = 'UNSTABLE'
                            error("Kube-bench found ${failCount} critical security issues")
                        }
                    }
                }
            }
        }
    }
}

Automation Scripts

Comprehensive Scanning Script

#!/bin/bash
# comprehensive-kube-bench.sh

set -e

# Configuration
RESULTS_DIR="kube-bench-results"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
KUBECONFIG_PATH="${KUBECONFIG:-$HOME/.kube/config}"

# Create results directory
mkdir -p "$RESULTS_DIR"

echo "Starting comprehensive Kube-bench security scan..."

# Function to run scan and save results
run_scan() {
    local scan_type="$1"
    local benchmark="$2"
    local output_file="$3"

    echo "Running $scan_type scan with benchmark $benchmark..."

    if [ "$scan_type" = "job" ]; then
        # Run as Kubernetes 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 > "$output_file"
        kubectl delete job kube-bench
    else
        # Run locally
        kube-bench --benchmark "$benchmark" --json > "$output_file"
    fi
}

# Detect Kubernetes distribution
detect_k8s_distribution() {
    if kubectl get nodes -o jsonpath='{.items[0].status.nodeInfo.providerID}' | grep -q "aws"; then
        echo "eks"
    elif kubectl get nodes -o jsonpath='{.items[0].status.nodeInfo.providerID}' | grep -q "gce"; then
        echo "gke"
    elif kubectl get nodes -o jsonpath='{.items[0].status.nodeInfo.providerID}' | grep -q "azure"; then
        echo "aks"
    else
        echo "generic"
    fi
}

# Main scanning logic
main() {
    # Detect distribution
    DISTRIBUTION=$(detect_k8s_distribution)
    echo "Detected Kubernetes distribution: $DISTRIBUTION"

    # Set benchmark based on distribution
    case $DISTRIBUTION in
        "eks")
            BENCHMARK="eks-1.0.1"
            ;;
        "gke")
            BENCHMARK="gke-1.0"
            ;;
        "aks")
            BENCHMARK="aks-1.0"
            ;;
        *)
            BENCHMARK="cis-1.6"
            ;;
    esac

    # Run scans
    run_scan "local" "$BENCHMARK" "$RESULTS_DIR/local-scan-$TIMESTAMP.json"
    run_scan "job" "$BENCHMARK" "$RESULTS_DIR/job-scan-$TIMESTAMP.txt"

    # Generate summary report
    python3 << 'EOF'
import json
import sys
from datetime import datetime

def parse_json_results(file_path):
    try:
        with open(file_path, 'r') as f:
            data = json.load(f)
        return data
    except:
        return None

def generate_summary(data):
    if not data or 'Controls' not in data:
        return None

    summary = {
        'total_checks': 0,
        'pass': 0,
        'fail': 0,
        'warn': 0,
        'info': 0,
        'controls': []
    }

    for control in data['Controls']:
        control_summary = {
            'id': control.get('id', 'Unknown'),
            'text': control.get('text', 'Unknown'),
            'pass': 0,
            'fail': 0,
            'warn': 0,
            'info': 0
        }

        for group in control.get('Groups', []):
            for check in group.get('Checks', []):
                state = check.get('State', 'UNKNOWN')
                summary['total_checks'] += 1
                control_summary[state.lower()] += 1
                summary[state.lower()] += 1

        summary['controls'].append(control_summary)

    return summary

# Parse results
json_file = f"kube-bench-results/local-scan-{sys.argv[1]}.json"
data = parse_json_results(json_file)
summary = generate_summary(data)

if summary:
    print(f"\n=== Kube-bench Security Scan Summary ===")
    print(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Total Checks: {summary['total_checks']}")
    print(f"✅ Pass: {summary['pass']}")
    print(f"❌ Fail: {summary['fail']}")
    print(f"⚠️  Warn: {summary['warn']}")
    print(f"ℹ️  Info: {summary['info']}")
    print(f"\nControl Breakdown:")

    for control in summary['controls']:
        print(f"  {control['id']}: {control['text']}")
        print(f"    Pass: {control['pass']}, Fail: {control['fail']}, Warn: {control['warn']}, Info: {control['info']}")

    # Calculate score
    if summary['total_checks'] > 0:
        score = (summary['pass'] / summary['total_checks']) * 100
        print(f"\nSecurity Score: {score:.1f}%")

    # Exit with error if critical issues found
    if summary['fail'] > 0:
        print(f"\n❌ Found {summary['fail']} critical security issues!")
        sys.exit(1)
    else:
        print(f"\n✅ No critical security issues found!")

EOF

    echo "Scan completed. Results saved in $RESULTS_DIR/"
}

# Run main function
main "$TIMESTAMP"

Automated Remediation Script

#!/bin/bash
# kube-bench-remediation.sh

set -e

RESULTS_FILE="$1"
REMEDIATION_LOG="remediation-$(date +%Y%m%d_%H%M%S).log"

if [ -z "$RESULTS_FILE" ]; then
    echo "Usage: $0 <kube-bench-results.json>"
    exit 1
fi

echo "Starting automated remediation based on Kube-bench results..."
echo "Results file: $RESULTS_FILE"
echo "Remediation log: $REMEDIATION_LOG"

# Function to apply remediation
apply_remediation() {
    local check_id="$1"
    local remediation="$2"

    echo "Applying remediation for check $check_id..." | tee -a "$REMEDIATION_LOG"
    echo "Remediation: $remediation" | tee -a "$REMEDIATION_LOG"

    case "$check_id" in
        "1.1.1")
            # Fix API server pod specification file permissions
            echo "Fixing API server pod specification file permissions..." | tee -a "$REMEDIATION_LOG"
            sudo chmod 644 /etc/kubernetes/manifests/kube-apiserver.yaml 2>&1 | tee -a "$REMEDIATION_LOG"
            ;;
        "1.1.2")
            # Fix API server pod specification file ownership
            echo "Fixing API server pod specification file ownership..." | tee -a "$REMEDIATION_LOG"
            sudo chown root:root /etc/kubernetes/manifests/kube-apiserver.yaml 2>&1 | tee -a "$REMEDIATION_LOG"
            ;;
        "1.2.1")
            # Fix anonymous-auth setting
            echo "Fixing anonymous-auth setting..." | tee -a "$REMEDIATION_LOG"
            kubectl patch deployment kube-apiserver -n kube-system --type='merge' -p='{"spec":{"template":{"spec":{"containers":[{"name":"kube-apiserver","command":["kube-apiserver","--anonymous-auth=false"]}]}}}}' 2>&1 | tee -a "$REMEDIATION_LOG"
            ;;
        *)
            echo "No automated remediation available for check $check_id" | tee -a "$REMEDIATION_LOG"
            echo "Manual remediation required: $remediation" | tee -a "$REMEDIATION_LOG"
            ;;
    esac
}

# Parse JSON results and apply remediations
python3 << EOF
import json
import subprocess
import sys

def run_remediation(check_id, remediation):
    try:
        subprocess.run(['bash', '-c', f'apply_remediation "{check_id}" "{remediation}"'], check=True)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Failed to apply remediation for {check_id}: {e}")
        return False

# Load results
with open('$RESULTS_FILE', 'r') as f:
    data = json.load(f)

remediation_count = 0
success_count = 0

for control in data.get('Controls', []):
    for group in control.get('Groups', []):
        for check in group.get('Checks', []):
            if check.get('State') == 'FAIL' and check.get('Remediation'):
                check_id = check.get('ID', 'Unknown')
                remediation = check.get('Remediation', '')

                print(f"Attempting remediation for check {check_id}")
                remediation_count += 1

                if run_remediation(check_id, remediation):
                    success_count += 1

print(f"\nRemediation Summary:")
print(f"Total remediations attempted: {remediation_count}")
print(f"Successful remediations: {success_count}")
print(f"Failed remediations: {remediation_count - success_count}")

EOF

echo "Remediation completed. Check $REMEDIATION_LOG for details."

Monitoring and Alerting Script

#!/bin/bash
# kube-bench-monitor.sh

set -e

# Configuration
SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}"
EMAIL_RECIPIENTS="${EMAIL_RECIPIENTS:-}"
THRESHOLD_FAIL="${THRESHOLD_FAIL:-0}"
THRESHOLD_WARN="${THRESHOLD_WARN:-5}"

# Function to send Slack notification
send_slack_notification() {
    local message="$1"
    local color="$2"

    if [ -n "$SLACK_WEBHOOK_URL" ]; then
        curl -X POST -H 'Content-type: application/json' \
            --data "{
                \"attachments\": [{
                    \"color\": \"$color\",
                    \"title\": \"Kube-bench Security Scan Results\",
                    \"text\": \"$message\",
                    \"footer\": \"Kube-bench Monitor\",
                    \"ts\": $(date +%s)
                }]
            }" \
            "$SLACK_WEBHOOK_URL"
    fi
}

# Function to send email notification
send_email_notification() {
    local subject="$1"
    local body="$2"

    if [ -n "$EMAIL_RECIPIENTS" ]; then
        echo "$body" | mail -s "$subject" "$EMAIL_RECIPIENTS"
    fi
}

# Run kube-bench scan
echo "Running Kube-bench security scan..."
kube-bench --json > scan-results.json

# Parse results
python3 << 'EOF'
import json
import sys
import os

# Load results
with open('scan-results.json', 'r') as f:
    data = json.load(f)

# Count issues
fail_count = 0
warn_count = 0
pass_count = 0

for control in data.get('Controls', []):
    for group in control.get('Groups', []):
        for check in group.get('Checks', []):
            state = check.get('State', 'UNKNOWN')
            if state == 'FAIL':
                fail_count += 1
            elif state == 'WARN':
                warn_count += 1
            elif state == 'PASS':
                pass_count += 1

# Write summary to file
with open('scan-summary.txt', 'w') as f:
    f.write(f"FAIL_COUNT={fail_count}\n")
    f.write(f"WARN_COUNT={warn_count}\n")
    f.write(f"PASS_COUNT={pass_count}\n")

print(f"Scan completed: {fail_count} failures, {warn_count} warnings, {pass_count} passes")

EOF

# Load summary
source scan-summary.txt

# Determine alert level
if [ "$FAIL_COUNT" -gt "$THRESHOLD_FAIL" ]; then
    ALERT_LEVEL="critical"
    COLOR="danger"
elif [ "$WARN_COUNT" -gt "$THRESHOLD_WARN" ]; then
    ALERT_LEVEL="warning"
    COLOR="warning"
else
    ALERT_LEVEL="good"
    COLOR="good"
fi

# Create notification message
MESSAGE="Kube-bench Security Scan Results:
• Failed checks: $FAIL_COUNT
• Warning checks: $WARN_COUNT
• Passed checks: $PASS_COUNT
• Alert level: $ALERT_LEVEL"

# Send notifications
send_slack_notification "$MESSAGE" "$COLOR"
send_email_notification "Kube-bench Security Scan - $ALERT_LEVEL" "$MESSAGE"

# Exit with appropriate code
if [ "$FAIL_COUNT" -gt "$THRESHOLD_FAIL" ]; then
    echo "❌ Critical security issues found: $FAIL_COUNT failures"
    exit 1
elif [ "$WARN_COUNT" -gt "$THRESHOLD_WARN" ]; then
    echo "⚠️ Warning threshold exceeded: $WARN_COUNT warnings"
    exit 2
else
    echo "✅ Security scan passed"
    exit 0
fi

Troubleshooting

Common Issues

# Permission issues
sudo kube-bench

# Missing configuration files
kube-bench --config-dir /opt/kube-bench/cfg/

# Kubernetes API access issues
export KUBECONFIG=/path/to/kubeconfig
kube-bench

# Version compatibility issues
kube-bench --version 1.21 --benchmark cis-1.6

# Debug mode
kube-bench --verbose

Configuration Validation

# Validate configuration syntax
kube-bench --config-dir /path/to/config --dry-run

# Check available benchmarks
kube-bench --list

# Verify installation
kube-bench version
kube-bench --help

Performance Optimization

# Run specific checks only
kube-bench --check 1.1.1,1.1.2,1.2.1

# Skip time-consuming checks
kube-bench --skip 4.1.1,4.1.2

# Increase timeout
kube-bench --timeout 300s

Best Practices

Security Scanning Strategy

  1. Regular Scanning: Schedule daily or weekly scans
  2. CI/CD Integration: Include in deployment pipelines
  3. Baseline Establishment: Create security baselines
  4. Remediation Tracking: Track and monitor fixes
  5. Compliance Reporting: Generate compliance reports

Configuration Management

  1. Version Control: Store configurations in Git
  2. Environment Specific: Maintain configs per environment
  3. Custom Benchmarks: Create organization-specific benchmarks
  4. Documentation: Document custom configurations
  5. Testing: Test configurations before deployment

Automation Guidelines

  1. Automated Remediation: Implement safe auto-remediation
  2. Alert Thresholds: Set appropriate alert levels
  3. Monitoring Integration: Integrate with monitoring systems
  4. Reporting: Generate actionable reports
  5. Trend Analysis: Track security trends over time

This comprehensive Kube-bench cheatsheet provides everything needed for professional Kubernetes security compliance scanning, from basic usage to advanced automation and integration scenarios.