kubernetes-hardening
Harden Kubernetes clusters and workloads - Pod Security Admission, securityContext, service-account tokens, default-deny NetworkPolicy that keeps DNS, least-privilege RBAC, admission policy (ValidatingAdmissionPolicy/Kyverno), image digests and signature verification, secrets encryption, audit logging, CIS scanning and runtime detection. Use for a K8s security review or before exposing a cluster to production; use operating-kubernetes for day-to-day workload operations.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- kubernetes-hardening
- risk
- critical
- source
- https://github.com/BagelHole/DevOps-Security-Agent-Skills
- license
- MIT
- category
- security
- metadata
- { "author": "devops-skills", "version": "1.1" }
- date_added
- 2026-09-20
- description
- Harden Kubernetes clusters and workloads - Pod Security Admission, securityContext, service-account tokens, default-deny NetworkPolicy that keeps DNS, least-privilege RBAC, admission policy (ValidatingAdmissionPolicy/Kyverno), image digests and signature verification, secrets encryption, audit logging, CIS scanning and runtime detection. Use for a K8s security review or before exposing a cluster to production; use operating-kubernetes for day-to-day workload operations.
- source_repo
- BagelHole/DevOps-Security-Agent-Skills
- source_type
- community
- compatibility
- Requires kubectl access with permission to read cluster configuration; changing admission, audit or encryption settings requires control-plane access (self-managed) or the cloud provider's equivalent settings (EKS/GKE/AKS).
- license_source
- https://github.com/BagelHole/DevOps-Security-Agent-Skills/blob/main/LICENSE
03 SKILL.md 正文
Kubernetes Hardening
Work in layers; verify each. Apply changes in non-production cluster first. enforce modes and default-deny policies break workloads relying on the gap.
0. Inventory first (read-only)
kubectl version
kubectl get ns --show-labels # current Pod Security labels
kubectl get networkpolicy -A
kubectl get clusterrolebindings -o wide | grep -E 'cluster-admin|system:anonymous|system:unauthenticated'
kubectl auth can-i --list --as=system:serviceaccount:<ns>:default -n <ns>
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\t"}{.spec.containers[*].image}{"\n"}{end}' | grep -v '@sha256'
Then run section 9 scanners for baseline.
1. Pod Security Admission
Label every workload namespace. Roll out warn/audit first, then enforce.
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
env: production # selected by the admission policy binding in section 6
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: latest
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
# Preview which existing pods would violate "restricted"
kubectl label --dry-run=server --overwrite ns production pod-security.kubernetes.io/enforce=restricted
Use baseline only for namespaces that need it (for example some CNI or monitoring agents). Keep privileged for system namespaces.
2. Workload securityContext
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
template:
spec:
automountServiceAccountToken: false # only mount when the pod calls the API server
serviceAccountName: api
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: api
image: registry.example.com/api@sha256:<digest> # digest, not a mutable tag
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
requests: { cpu: 100m, memory: 128Mi }
limits: { memory: 256Mi }
volumeMounts:
- { name: tmp, mountPath: /tmp }
volumes:
- name: tmp
emptyDir: {}
Avoid hostNetwork, hostPID, hostIPC, hostPath volumes and privileged: true. PSA restricted rejects most of these.
3. Service accounts
- One service account per workload; never grant permissions to
default. - Set
automountServiceAccountToken: falseon ServiceAccount or pod unless pod calls the API. When it does, projected token is short-lived and audience-bound. Do not create legacy long-lived token Secrets. - For cloud APIs, use workload identity (EKS Pod Identity/IRSA, GKE Workload Identity, AKS Workload ID), not static keys in Secrets.
4. NetworkPolicy: default deny that keeps DNS
NetworkPolicies take effect only if CNI enforces them (Calico, Cilium, cloud-native policy engines). Check before relying on them.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: production
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
namespace: production
spec:
podSelector: {}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector:
matchLabels:
k8s-app: kube-dns # check your DNS pods' labels
ports:
- { protocol: UDP, port: 53 }
- { protocol: TCP, port: 53 }
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: web-from-frontend
namespace: production
spec:
podSelector:
matchLabels: { app: web }
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchLabels: { app: frontend }
ports:
- { protocol: TCP, port: 8080 }
Without DNS rule, default-deny egress policy breaks every name lookup. Add explicit egress rules for databases, external APIs and API server where needed.
5. RBAC least privilege
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: { name: app-reader, namespace: production }
rules:
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["app-config"]
verbs: ["get", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: { name: app-reader, namespace: production }
subjects:
- kind: ServiceAccount
name: api
namespace: production
roleRef:
kind: Role
name: app-reader
apiGroup: rbac.authorization.k8s.io
Treat these as privilege-escalation paths. Grant only to cluster administrators:
| Grant | Why dangerous |
|---|---|
* verbs or resources |
Includes everything, now and in future API versions |
escalate, bind on roles |
Subject can grant itself more permissions |
impersonate |
Act as any user, group or service account |
create on pods / workloads |
Can mount any service account token or hostPath in that namespace |
get/list on secrets |
Reads every credential in scope |
create on serviceaccounts/token |
Mints tokens for other identities |
nodes/proxy, pods/exec, pods/attach |
Code execution on nodes or in pods |
Audit with kubectl auth can-i --list --as=<subject> plus a tool such as rbac-tool or kubectl-who-can if installed.
6. Admission policy
PSA covers pod-level controls only. Add policy for registries, digests, labels and resource limits.
Built-in ValidatingAdmissionPolicy (CEL; GA in recent Kubernetes versions, check yours):
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata: { name: require-image-digest }
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments"]
validations:
- expression: >-
object.spec.template.spec.containers.all(c, c.image.contains('@sha256:')) &&
(!has(object.spec.template.spec.initContainers) ||
object.spec.template.spec.initContainers.all(c, c.image.contains('@sha256:')))
message: "images (including init containers) must be pinned by digest"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata: { name: require-image-digest }
spec:
policyName: require-image-digest
validationActions: ["Deny"]
matchResources:
namespaceSelector:
matchLabels: { env: production } # the Namespace in section 1 carries this label
Example matches Deployments only. Add StatefulSets, DaemonSets, Jobs and CronJobs (CronJob pods live under spec.jobTemplate.spec.template), or match pods directly to cover every workload kind.
Kyverno or OPA Gatekeeper add mutation, generation and image-signature checks. Start in audit mode (validationActions: ["Audit"], Kyverno Audit). Switch to deny after reviewing reports.
7. Supply chain: digests and signatures
- Deploy by digest. Resolve digest in CI from the image you built and tested.
- Sign images in CI (for example
cosign sign --yes <image>@<digest>with keyless OIDC). Verify at admission (KyvernoverifyImages, Sigstore policy-controller, or Connaisseur). - Verify manually:
cosign verify <image>@<digest> --certificate-identity-regexp '<repo workflow>' --certificate-oidc-issuer https://token.actions.githubusercontent.com. - Scan images in CI and continuously in-cluster (see
dockerfile-optimiserulesec-scan-images).
8. Secrets
- Enable encryption at rest for Secrets:
EncryptionConfigurationwith KMS provider (self-managed), or provider's envelope-encryption option (EKS/GKE/AKS). Re-encrypt existing Secrets after enabling. - Prefer external store synced in at runtime (External Secrets Operator, Secrets Store CSI Driver, Vault Agent; see
hashicorp-vault) over Secrets committed to Git. If they must be in Git, encrypt them (Sealed Secrets, SOPS). - Restrict
get/list/watchonsecretsto workloads that need specific names (resourceNames).
9. Audit logging, scanning and runtime detection
- Audit policy (self-managed API server:
--audit-policy-file,--audit-log-path; managed clusters: enable control-plane audit logs in provider). Minimal policy:
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: ["RequestReceived"]
rules:
- level: Metadata # never log Secret bodies
resources: [{ group: "", resources: ["secrets", "configmaps"] }]
- level: RequestResponse
resources: [{ group: "rbac.authorization.k8s.io" }]
- level: Metadata
verbs: ["create", "update", "patch", "delete"]
- level: None
- CIS benchmark:
kube-bench(run as Job on nodes; use managed-service profile on EKS/GKE/AKS). - Posture scan:
KS_SKIP_UPDATE_CHECK=true kubescape scan(NSA/CISA and MITRE frameworks) orTRIVY_DISABLE_TELEMETRY=true TRIVY_SKIP_VERSION_CHECK=true trivy k8s --report summary. Both send usage/cluster data (version, node count, install or cluster ID) home by default; keep these opt-outs wherever they run, CI too. - Runtime detection: Falco (or Tetragon) for shells in containers, unexpected outbound connections, writes below
/etc, and token reads. Route alerts to on-call. - Control plane and nodes: keep cluster on supported minor version. Restrict API server access (private endpoint or authorized networks). Disable anonymous auth. Restrict kubelet (
--anonymous-auth=false, webhook authorization). Keep etcd unreachable from workloads with client TLS.
Done when
- Every workload namespace enforces PSA
restricted(or has a documentedbaselineexception). - Each namespace has default-deny ingress and egress plus explicit allows. DNS still resolves (
kubectl exec <pod> -- getent hosts kubernetes.default). - No non-admin subject holds escalation grants above. Workloads use dedicated service accounts with tokens mounted only where needed.
- Production admission rejects unpinned or unsigned images (test with deliberately bad Deployment).
- Secrets encrypted at rest. Audit logs flowing. kube-bench/kubescape findings triaged with owners.
Related skills
operating-kubernetes- resources, scheduling, autoscaling and troubleshooting.security-hardening- host, container runtime and cloud account hardening.implementing-gitops- delivering these policies declaratively.hashicorp-vault- external secrets source.
Adapted from BagelHole/DevOps-Security-Agent-Skills (MIT) and substantially expanded.
04 同仓库更多 Skills
wiki-builder
Create and maintain a local Markdown research wiki (sources with provenance, compiled concept/source pages, index, maintenance log) driven by a per-wiki config. Use when the user wants to start a wiki or knowledge base, ingest sources into one, or query and update it; use wiki-page-writer for a single code deep-dive page.
refactoring-guru
Diagnose a named code smell and apply the smallest behavior-preserving refactoring, with verification before and after and an explicit stop condition. Use for structural refactors (extract, move, consolidate, change ownership), not for feature or bug work; for readability cleanup of recent changes use code-simplification.
legacy-seams
When changing untested legacy code, pin the observed results with characterization tests and open the smallest seam that substitutes only the blocking dependency, separate from any later logic change. Use when a clock, random source, I/O, global, or hidden constructor blocks a test or a safe edit. Use test-driven-development for a new behavior or a bug, refactoring-guru for one named structural refactor after the seam exists, and code-refactoring-tech-debt to choose which legacy to replace.
idea-refine
Refine a raw idea into a one-page brief (problem statement, recommended direction, assumptions to validate, MVP scope, not-doing list) through divergent then convergent thinking. Use when an idea is still vague or you want options and a stress test before committing; use interview-me when the goal itself is unclear and spec-driven-development once the direction is chosen.
code-review-and-quality
Review rubric and approval standard for any change before merge, including code written by you, another agent, or a human: five axes (correctness, readability, architecture, security, performance), change sizing, structural remedies, severity labels, and feedback technique. Use to judge whether a change is fit to merge; use code-review to run a PR or diff review end to end.
code-perfection
Smell and style gate for code you write or change. Bans known code smells (long method, large class, primitive obsession, long parameter list, data clumps, duplicate code, dead code, feature envy, shotgun surgery, flag arguments, message chains) and enforces behavior-preserving structure. On Scala files, enforces worxbend style. Use while implementing, reviewing a diff for smells, or when a smell or style violation is suspected. Routine construction stays with code-complete. SOLID and DRY stay with clean-code-guard. One named structural refactor stays with refactoring-guru.