mirror of
https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
synced 2026-07-16 04:35:18 +03:00
Initial commit - 611 cybersecurity skills across all subdomains
This commit is contained in:
@@ -0,0 +1,268 @@
|
||||
---
|
||||
name: securing-helm-chart-deployments
|
||||
description: Secure Helm chart deployments by validating chart integrity, scanning templates for misconfigurations, and enforcing security contexts in Kubernetes releases.
|
||||
domain: cybersecurity
|
||||
subdomain: container-security
|
||||
tags: [helm, kubernetes, chart-security, supply-chain, configuration-security, deployment]
|
||||
version: "1.0"
|
||||
author: mahipal
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# Securing Helm Chart Deployments
|
||||
|
||||
## 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.
|
||||
|
||||
## 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
|
||||
|
||||
```bash
|
||||
# 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
|
||||
|
||||
```bash
|
||||
# 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
|
||||
|
||||
```bash
|
||||
# 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
|
||||
|
||||
```bash
|
||||
# Lint chart
|
||||
helm lint ./mychart --values values-prod.yaml --strict
|
||||
|
||||
# Lint with debug output
|
||||
helm lint ./mychart --debug
|
||||
```
|
||||
|
||||
## Security Context Enforcement in values.yaml
|
||||
|
||||
```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
|
||||
|
||||
```yaml
|
||||
# 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)
|
||||
|
||||
```yaml
|
||||
# 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
|
||||
|
||||
```bash
|
||||
# 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
|
||||
|
||||
```yaml
|
||||
# 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
|
||||
|
||||
```yaml
|
||||
# .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
|
||||
@@ -0,0 +1,40 @@
|
||||
# Helm Chart Security Review Checklist
|
||||
|
||||
## Chart Metadata
|
||||
- [ ] Chart.yaml has accurate appVersion and version
|
||||
- [ ] No deprecated API versions in templates
|
||||
- [ ] Chart signed with GPG key
|
||||
|
||||
## Security Context Defaults
|
||||
- [ ] runAsNonRoot: true
|
||||
- [ ] readOnlyRootFilesystem: true
|
||||
- [ ] allowPrivilegeEscalation: false
|
||||
- [ ] capabilities.drop: ALL
|
||||
- [ ] seccompProfile: RuntimeDefault
|
||||
|
||||
## Resource Management
|
||||
- [ ] CPU limits set
|
||||
- [ ] Memory limits set
|
||||
- [ ] CPU requests set
|
||||
- [ ] Memory requests set
|
||||
|
||||
## Image Security
|
||||
- [ ] Image uses digest or pinned tag (not :latest)
|
||||
- [ ] imagePullPolicy: Always
|
||||
- [ ] Images from trusted registries only
|
||||
|
||||
## Secrets Handling
|
||||
- [ ] No secrets in values.yaml
|
||||
- [ ] External secrets integration configured
|
||||
- [ ] ServiceAccount token auto-mount disabled
|
||||
|
||||
## Network
|
||||
- [ ] NetworkPolicy template included
|
||||
- [ ] hostNetwork: false
|
||||
- [ ] hostPID: false
|
||||
- [ ] hostIPC: false
|
||||
|
||||
## RBAC
|
||||
- [ ] ServiceAccount created per release
|
||||
- [ ] Minimal RBAC permissions
|
||||
- [ ] No cluster-admin bindings
|
||||
@@ -0,0 +1,35 @@
|
||||
# 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
|
||||
@@ -0,0 +1,29 @@
|
||||
# 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
|
||||
@@ -0,0 +1,199 @@
|
||||
#!/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()
|
||||
Reference in New Issue
Block a user