Scanning Kubernetes Manifests for Security Issues

Scanning Kubernetes Manifests for Security Issues

Begin by scanning Kubernetes manifests before deployment to catch security misconfigurations early:

# Scan Kubernetes manifests with Trivy
trivy config ./k8s-manifests/

# Scan specific manifest file
trivy config deployment.yaml

# Detailed output with remediation advice
trivy config --severity HIGH,CRITICAL ./k8s-manifests/

# Example problematic deployment.yaml
cat << EOF > vulnerable-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: vulnerable-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: vulnerable-app
  template:
    metadata:
      labels:
        app: vulnerable-app
    spec:
      containers:
      - name: app
        image: vulnerable-app:latest
        securityContext:
          runAsUser: 0  # Running as root
          privileged: true  # Privileged container
        resources: {}  # No resource limits
        ports:
        - containerPort: 8080
          hostPort: 8080  # Host port binding
EOF

# Scan and see security issues
trivy config vulnerable-deployment.yaml

Using Snyk for Infrastructure as Code scanning:

# Scan Kubernetes manifests with Snyk
snyk iac test ./k8s-manifests/

# Scan with specific severity threshold
snyk iac test deployment.yaml --severity-threshold=high

# Generate detailed report
snyk iac test ./k8s-manifests/ --json > k8s-security-report.json

# Example Snyk output for misconfigurations
Testing deployment.yaml...

Infrastructure as Code Issues:
  ✗ Container is running as root [High Severity]
    Info: https://snyk.io/security-rules/SNYK-CC-K8S-1
    Path: spec.template.spec.containers[0].securityContext.runAsUser
    Remediation: Set runAsUser to non-zero value

  ✗ Container is running in privileged mode [High Severity]
    Info: https://snyk.io/security-rules/SNYK-CC-K8S-2
    Path: spec.template.spec.containers[0].securityContext.privileged
    Remediation: Remove privileged: true or set to false

  ✗ Container has no resource limits [Medium Severity]
    Info: https://snyk.io/security-rules/SNYK-CC-K8S-5
    Path: spec.template.spec.containers[0].resources
    Remediation: Set memory and CPU limits