container security

Securing Helm Chart Deployments

Secure Helm chart deployments by validating chart integrity, scanning templates for misconfigurations, and enforcing security contexts in Kubernetes releases.

chart-securityconfiguration-securitydeploymenthelmkubernetessupply-chain
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Helm is the Kubernetes package manager. Securing Helm deployments requires validating chart provenance, scanning templates for security misconfigurations, enforcing pod security contexts, managing secrets securely, and controlling RBAC for Helm operations.

When to Use

  • When deploying or configuring securing helm chart deployments capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Helm 3.12+ installed
  • kubectl with cluster access
  • GnuPG for chart signing/verification
  • kubesec or checkov for template scanning

Chart Provenance and Integrity

Sign a Helm Chart

# Generate GPG key for signing
gpg --full-generate-key
 
# Package and sign chart
helm package ./mychart --sign --key "helm-signing@example.com" --keyring ~/.gnupg/pubring.gpg
 
# Verify chart signature
helm verify mychart-0.1.0.tgz --keyring ~/.gnupg/pubring.gpg

Verify Chart Before Install

# Verify chart from repository
helm pull myrepo/mychart --verify --keyring /path/to/keyring.gpg
 
# Check chart provenance file
cat mychart-0.1.0.tgz.prov

Template Security Scanning

Render and Scan Templates

# Render templates without deploying
helm template myrelease ./mychart --values values-prod.yaml > rendered.yaml
 
# Scan with kubesec
kubesec scan rendered.yaml
 
# Scan with checkov
checkov -f rendered.yaml --framework kubernetes
 
# Scan with trivy
trivy config rendered.yaml
 
# Scan with kube-linter
kube-linter lint rendered.yaml

Helm Lint for Misconfigurations

# Lint chart
helm lint ./mychart --values values-prod.yaml --strict
 
# Lint with debug output
helm lint ./mychart --debug

Security Context Enforcement in values.yaml

# values.yaml - Security hardened defaults
securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  runAsGroup: 3000
  fsGroup: 2000
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false
  capabilities:
    drop:
      - ALL
 
podSecurityContext:
  seccompProfile:
    type: RuntimeDefault
 
resources:
  limits:
    cpu: 500m
    memory: 512Mi
  requests:
    cpu: 100m
    memory: 128Mi
 
networkPolicy:
  enabled: true
 
serviceAccount:
  create: true
  automountServiceAccountToken: false
 
image:
  pullPolicy: Always
  # Use digest instead of tag for immutability
  # tag: "1.0.0"
  # digest: "sha256:abc123..."

Template with Security Contexts

# templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "mychart.fullname" . }}
spec:
  template:
    spec:
      automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
      securityContext:
        {{- toYaml .Values.podSecurityContext | nindent 8 }}
      containers:
        - name: {{ .Chart.Name }}
          securityContext:
            {{- toYaml .Values.securityContext | nindent 12 }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          resources:
            {{- toYaml .Values.resources | nindent 12 }}

Secrets Management

Use External Secrets (Not Helm Values)

# templates/external-secret.yaml
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: {{ include "mychart.fullname" . }}-secrets
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: aws-secretsmanager
    kind: ClusterSecretStore
  target:
    name: {{ include "mychart.fullname" . }}-secrets
  data:
    - secretKey: db-password
      remoteRef:
        key: production/database
        property: password

helm-secrets Plugin

# Install helm-secrets plugin
helm plugin install https://github.com/jkroepke/helm-secrets
 
# Encrypt values file
helm secrets encrypt values-secrets.yaml
 
# Deploy with encrypted secrets
helm secrets install myrelease ./mychart -f values.yaml -f values-secrets.yaml
 
# Decrypt for editing
helm secrets edit values-secrets.yaml

RBAC for Helm Operations

# helm-deployer-role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: helm-deployer
  namespace: production
rules:
  - apiGroups: ["", "apps", "batch", "networking.k8s.io"]
    resources: ["deployments", "services", "configmaps", "secrets", "ingresses", "jobs"]
    verbs: ["get", "list", "create", "update", "patch", "delete"]
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list"]
 
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: helm-deployer-binding
  namespace: production
subjects:
  - kind: ServiceAccount
    name: helm-deployer
    namespace: production
roleRef:
  kind: Role
  name: helm-deployer
  apiGroup: rbac.authorization.k8s.io

CI/CD Helm Security Pipeline

# .github/workflows/helm-security.yaml
name: Helm Chart Security
on:
  pull_request:
    paths: ['charts/**']
 
jobs:
  lint-and-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
 
      - name: Helm lint
        run: helm lint ./charts/mychart --strict
 
      - name: Render templates
        run: helm template test ./charts/mychart -f charts/mychart/values.yaml > rendered.yaml
 
      - name: Scan with kube-linter
        uses: stackrox/kube-linter-action@v1
        with:
          directory: rendered.yaml
 
      - name: Scan with trivy
        uses: aquasecurity/trivy-action@master
        with:
          scan-type: config
          scan-ref: rendered.yaml
 
      - name: Scan with checkov
        uses: bridgecrewio/checkov-action@master
        with:
          file: rendered.yaml
          framework: kubernetes

Best Practices

  1. Sign charts with GPG and verify before installation
  2. Render and scan templates before deploying to catch misconfigurations
  3. Enforce security contexts in values.yaml defaults
  4. Never store secrets in Helm values - use external secrets or helm-secrets plugin
  5. Use image digests instead of tags for immutable references
  6. Restrict Helm RBAC to least privilege per namespace
  7. Pin chart versions in requirements - never use latest
  8. Lint strictly in CI with --strict flag
  9. Review third-party charts before deploying to production
  10. Use Helm test hooks to validate deployments post-install
Source materials

References and resources

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

References 3

api-reference.md1.9 KB

API Reference: Securing Helm Chart Deployments

Helm Security Commands

Command Description
helm lint ./chart --strict Lint chart with strict mode
helm template release ./chart Render templates locally
helm verify chart.tgz Verify chart signature
helm package ./chart --sign --key <key> Package and sign
helm pull repo/chart --verify Pull with verification

Security Context Fields

Field Recommended Description
runAsNonRoot true Prevent root execution
readOnlyRootFilesystem true Immutable filesystem
allowPrivilegeEscalation false Block privilege escalation
capabilities.drop [ALL] Drop all Linux capabilities
seccompProfile.type RuntimeDefault Syscall filtering

Security Checks

Check Severity Risk
Privileged container High Full host access
hostNetwork enabled High Network namespace escape
hostPID enabled High Process namespace escape
:latest image tag Medium Non-reproducible builds
Missing resource limits Medium Resource exhaustion DoS
Missing readOnlyRootFilesystem Medium Writable filesystem

Template Scanning Tools

Tool Command
kubesec kubesec scan rendered.yaml
checkov checkov -f rendered.yaml --framework kubernetes
trivy trivy config rendered.yaml
kube-linter kube-linter lint rendered.yaml

Python Libraries

Library Version Purpose
subprocess stdlib Execute helm/kubesec CLI
re stdlib Pattern matching in rendered YAML
yaml PyYAML >=6.0 Parse YAML content
json stdlib Report generation

References

standards.md1.3 KB

Standards and References - Securing Helm Chart Deployments

NIST SP 800-190

  • Section 4.1: Image vulnerabilities and configuration defects
  • Section 5.2: Registry security and chart provenance
  • Section 5.4: Secure deployment configuration

CIS Kubernetes Benchmark v1.8

  • 5.2.1-5.2.9: Pod Security Standards enforced via chart defaults
  • 5.7.3: Apply security context to pods and containers

SLSA (Supply chain Levels for Software Artifacts)

  • Level 1: Documented build process (Helm chart CI)
  • Level 2: Source version controlled, signed provenance
  • Level 3: Hardened build platform, signed artifacts
  • Level 4: Two-party review, hermetic builds

Helm Security Resources

Resource URL
Helm Security Best Practices https://helm.sh/docs/chart_best_practices/
Helm Provenance and Integrity https://helm.sh/docs/topics/provenance/
kube-linter https://github.com/stackrox/kube-linter
checkov Kubernetes checks https://www.checkov.io/5.Policy%20Index/kubernetes.html
helm-secrets plugin https://github.com/jkroepke/helm-secrets

Compliance Mappings

PCI DSS v4.0

  • Req 6.3.1: Security vulnerabilities identified and managed
  • Req 6.5.1: Changes controlled by change control processes

SOC 2

  • CC8.1: Change management - Controlled deployment processes
workflows.md1.1 KB

Workflow - Securing Helm Chart Deployments

Phase 1: Chart Development Security

  1. Set secure defaults in values.yaml (non-root, read-only fs, resource limits)
  2. Add network policy templates
  3. Use external secrets references
  4. Lint with helm lint --strict

Phase 2: CI Pipeline

  1. Render templates: helm template test ./chart -f values.yaml > rendered.yaml
  2. Lint: helm lint ./chart --strict
  3. Scan: kube-linter lint rendered.yaml
  4. Scan: checkov -f rendered.yaml --framework kubernetes
  5. Sign chart: helm package ./chart --sign

Phase 3: Deployment

  1. Verify chart signature: helm verify chart.tgz
  2. Deploy with production values: helm install release ./chart -f values-prod.yaml
  3. Verify deployment: helm test release

Phase 4: Post-Deployment

  1. Validate security contexts: kubectl get pods -o jsonpath='{.items[*].spec.securityContext}'
  2. Check network policies applied
  3. Verify secrets sourced from external store

Phase 5: Maintenance

  1. Update chart versions in lockfile
  2. Rescan after dependency updates
  3. Rotate signing keys annually

Scripts 2

agent.py6.6 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for securing Helm chart deployments.

Validates chart provenance, renders and scans templates for
security misconfigurations, checks security contexts, and
enforces Helm deployment security baselines.
"""

import json
import subprocess
import sys
import re
from pathlib import Path
from datetime import datetime

try:
    import yaml
except ImportError:
    yaml = None


class HelmSecurityAgent:
    """Audits Helm chart deployments for security issues."""

    def __init__(self, chart_path, output_dir="./helm_audit"):
        self.chart_path = Path(chart_path)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.findings = []

    def _run(self, cmd, timeout=60):
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
            return result.stdout, result.stderr, result.returncode
        except (FileNotFoundError, subprocess.TimeoutExpired) as e:
            return "", str(e), -1

    def lint_chart(self, values_file=None):
        """Run helm lint with strict mode."""
        cmd = ["helm", "lint", str(self.chart_path), "--strict"]
        if values_file:
            cmd.extend(["--values", values_file])
        stdout, stderr, rc = self._run(cmd)
        if rc != 0:
            self.findings.append({
                "severity": "medium",
                "type": "Lint Failure",
                "detail": stderr.strip() or stdout.strip(),
            })
        return {"returncode": rc, "output": stdout.strip(), "errors": stderr.strip()}

    def render_templates(self, values_file=None, release_name="audit"):
        """Render Helm templates without deploying."""
        cmd = ["helm", "template", release_name, str(self.chart_path)]
        if values_file:
            cmd.extend(["--values", values_file])
        stdout, stderr, rc = self._run(cmd)
        if rc == 0:
            rendered_path = self.output_dir / "rendered.yaml"
            rendered_path.write_text(stdout)
            return str(rendered_path)
        return None

    def check_security_contexts(self, rendered_path):
        """Check rendered manifests for security context issues."""
        issues = []
        content = Path(rendered_path).read_text()

        checks = [
            (r"privileged:\s*true", "high", "Privileged container detected"),
            (r"hostNetwork:\s*true", "high", "Host network access enabled"),
            (r"hostPID:\s*true", "high", "Host PID namespace shared"),
            (r"allowPrivilegeEscalation:\s*true", "medium", "Privilege escalation allowed"),
            (r"runAsUser:\s*0\b", "medium", "Running as root (UID 0)"),
        ]

        positive_checks = [
            (r"readOnlyRootFilesystem:\s*true", "readOnlyRootFilesystem"),
            (r"runAsNonRoot:\s*true", "runAsNonRoot"),
            (r"drop:\s*\n\s*-\s*ALL", "drop ALL capabilities"),
        ]

        for pattern, severity, msg in checks:
            if re.search(pattern, content):
                issues.append({"severity": severity, "issue": msg})
                self.findings.append({"severity": severity, "type": "Security Context", "detail": msg})

        for pattern, name in positive_checks:
            if not re.search(pattern, content):
                issues.append({"severity": "medium", "issue": f"Missing: {name}"})
                self.findings.append({"severity": "medium", "type": "Missing Hardening", "detail": f"Missing: {name}"})

        if "resources:" not in content:
            issues.append({"severity": "medium", "issue": "No resource limits defined"})
            self.findings.append({"severity": "medium", "type": "Missing Resources", "detail": "No CPU/memory limits"})

        return issues

    def verify_chart_signature(self, keyring=None):
        """Verify Helm chart provenance signature."""
        tgz = list(self.chart_path.parent.glob(f"{self.chart_path.name}-*.tgz"))
        if not tgz:
            return {"verified": False, "reason": "No packaged chart found"}
        cmd = ["helm", "verify", str(tgz[0])]
        if keyring:
            cmd.extend(["--keyring", keyring])
        stdout, stderr, rc = self._run(cmd)
        if rc != 0:
            self.findings.append({"severity": "medium", "type": "Unsigned Chart", "detail": "Chart signature not verified"})
        return {"verified": rc == 0, "output": stdout.strip() or stderr.strip()}

    def check_image_references(self, rendered_path):
        """Check if image references use digests or tags."""
        content = Path(rendered_path).read_text()
        issues = []
        for m in re.finditer(r'image:\s*["\']?([^"\'\s]+)["\']?', content):
            image = m.group(1)
            if ":latest" in image:
                issues.append({"image": image, "issue": "Uses :latest tag"})
                self.findings.append({"severity": "medium", "type": "Image Tag", "detail": f"latest tag: {image}"})
            elif "@sha256:" not in image and ":" not in image:
                issues.append({"image": image, "issue": "No tag or digest specified"})
        return issues

    def scan_with_kubesec(self, rendered_path):
        """Scan rendered templates with kubesec if available."""
        stdout, stderr, rc = self._run(["kubesec", "scan", rendered_path])
        if rc < 0:
            return {"available": False}
        try:
            return json.loads(stdout)
        except json.JSONDecodeError:
            return {"error": "Parse failed"}

    def generate_report(self, values_file=None):
        lint = self.lint_chart(values_file)
        rendered = self.render_templates(values_file)
        sec_ctx = []
        images = []
        if rendered:
            sec_ctx = self.check_security_contexts(rendered)
            images = self.check_image_references(rendered)

        report = {
            "report_date": datetime.utcnow().isoformat(),
            "chart": str(self.chart_path),
            "lint_result": lint,
            "security_context_issues": sec_ctx,
            "image_issues": images,
            "findings": self.findings,
            "total_findings": len(self.findings),
        }
        out = self.output_dir / "helm_security_report.json"
        with open(out, "w") as f:
            json.dump(report, f, indent=2)
        print(json.dumps(report, indent=2))
        return report


def main():
    if len(sys.argv) < 2:
        print("Usage: agent.py <chart_path> [--values values.yaml]")
        sys.exit(1)
    chart = sys.argv[1]
    values = None
    if "--values" in sys.argv:
        values = sys.argv[sys.argv.index("--values") + 1]
    agent = HelmSecurityAgent(chart)
    agent.generate_report(values)


if __name__ == "__main__":
    main()
process.py6.2 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Helm Chart Security Scanner - Render Helm templates and scan
for security misconfigurations in Kubernetes manifests.
"""

import json
import subprocess
import sys
import argparse
import re
from pathlib import Path


SECURITY_CHECKS = [
    {
        "id": "HELM-001",
        "name": "Container runs as root",
        "severity": "HIGH",
        "pattern": r"runAsNonRoot:\s*false|runAsUser:\s*0",
        "remediation": "Set securityContext.runAsNonRoot: true and runAsUser to non-zero",
    },
    {
        "id": "HELM-002",
        "name": "Privileged container",
        "severity": "CRITICAL",
        "pattern": r"privileged:\s*true",
        "remediation": "Set securityContext.privileged: false",
    },
    {
        "id": "HELM-003",
        "name": "Allow privilege escalation",
        "severity": "HIGH",
        "pattern": r"allowPrivilegeEscalation:\s*true",
        "remediation": "Set securityContext.allowPrivilegeEscalation: false",
    },
    {
        "id": "HELM-004",
        "name": "No resource limits",
        "severity": "MEDIUM",
        "pattern": r"resources:\s*\{\}|resources:\s*null",
        "remediation": "Set resources.limits.cpu and resources.limits.memory",
    },
    {
        "id": "HELM-005",
        "name": "Uses latest image tag",
        "severity": "MEDIUM",
        "pattern": r"image:.*:latest|image:\s*[^:]+\s*$",
        "remediation": "Use specific image tag or digest instead of :latest",
    },
    {
        "id": "HELM-006",
        "name": "HostPath volume mount",
        "severity": "HIGH",
        "pattern": r"hostPath:",
        "remediation": "Avoid hostPath volumes; use PersistentVolumeClaim instead",
    },
    {
        "id": "HELM-007",
        "name": "Host network enabled",
        "severity": "HIGH",
        "pattern": r"hostNetwork:\s*true",
        "remediation": "Set hostNetwork: false",
    },
    {
        "id": "HELM-008",
        "name": "Host PID namespace",
        "severity": "HIGH",
        "pattern": r"hostPID:\s*true",
        "remediation": "Set hostPID: false",
    },
    {
        "id": "HELM-009",
        "name": "Service account token auto-mounted",
        "severity": "MEDIUM",
        "pattern": r"automountServiceAccountToken:\s*true",
        "remediation": "Set automountServiceAccountToken: false unless needed",
    },
    {
        "id": "HELM-010",
        "name": "Writable root filesystem",
        "severity": "MEDIUM",
        "pattern": r"readOnlyRootFilesystem:\s*false",
        "remediation": "Set securityContext.readOnlyRootFilesystem: true",
    },
]


def render_chart(chart_path: str, values_file: str = None, release_name: str = "scan") -> str:
    """Render Helm chart templates."""
    cmd = ["helm", "template", release_name, chart_path]
    if values_file:
        cmd.extend(["-f", values_file])
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"Helm template error: {result.stderr}", file=sys.stderr)
        sys.exit(1)
    return result.stdout


def scan_rendered(content: str) -> list:
    """Scan rendered YAML for security issues."""
    findings = []
    lines = content.split("\n")
    for check in SECURITY_CHECKS:
        for i, line in enumerate(lines, 1):
            if re.search(check["pattern"], line):
                findings.append({
                    "id": check["id"],
                    "name": check["name"],
                    "severity": check["severity"],
                    "line": i,
                    "content": line.strip(),
                    "remediation": check["remediation"],
                })
    return findings


def lint_chart(chart_path: str) -> dict:
    """Run helm lint on chart."""
    result = subprocess.run(
        ["helm", "lint", chart_path, "--strict"],
        capture_output=True, text=True,
    )
    return {
        "passed": result.returncode == 0,
        "output": result.stdout + result.stderr,
    }


def generate_report(findings: list, chart_path: str) -> str:
    """Generate security scan report."""
    severity_counts = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0}
    for f in findings:
        severity_counts[f["severity"]] = severity_counts.get(f["severity"], 0) + 1

    report = f"""# Helm Chart Security Scan Report

**Chart:** `{chart_path}`
**Findings:** {len(findings)}

## Summary

| Severity | Count |
|----------|-------|
| CRITICAL | {severity_counts['CRITICAL']} |
| HIGH | {severity_counts['HIGH']} |
| MEDIUM | {severity_counts['MEDIUM']} |
| LOW | {severity_counts['LOW']} |

## Findings

| ID | Severity | Finding | Line | Remediation |
|----|----------|---------|------|-------------|
"""
    for f in sorted(findings, key=lambda x: {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}[x["severity"]]):
        report += f"| {f['id']} | {f['severity']} | {f['name']} | {f['line']} | {f['remediation']} |\n"

    return report


def main():
    parser = argparse.ArgumentParser(description="Helm Chart Security Scanner")
    parser.add_argument("chart", help="Path to Helm chart")
    parser.add_argument("--values", "-f", help="Values file path")
    parser.add_argument("--report", "-r", help="Output report file")
    parser.add_argument("--lint", action="store_true", help="Run helm lint")
    parser.add_argument("--fail-on", choices=["critical", "high", "medium"],
                       default="high", help="Fail threshold")

    args = parser.parse_args()

    if args.lint:
        lint_result = lint_chart(args.chart)
        print(lint_result["output"])
        if not lint_result["passed"]:
            print("Lint FAILED")
            sys.exit(1)

    rendered = render_chart(args.chart, args.values)
    findings = scan_rendered(rendered)
    report = generate_report(findings, args.chart)

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

    threshold = {"critical": ["CRITICAL"], "high": ["CRITICAL", "HIGH"],
                 "medium": ["CRITICAL", "HIGH", "MEDIUM"]}
    blocking = [f for f in findings if f["severity"] in threshold[args.fail_on]]
    if blocking:
        print(f"\nFAILED: {len(blocking)} findings at or above {args.fail_on} severity")
        sys.exit(1)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.0 KB
Keep exploring