## Intro StatefulSets are the Kubernetes workload of choice for applications that need stable identities, persistent storage, and ordered deployment. Databases, message queues, and distributed systems rely on these guarantees. However, StatefulSets also inherit every security challenge of pods plus additional risks from persistent data and stable network identities. A compromised StatefulSet can leak sensitive data, allow lateral movement, or disrupt critical services. This guide provides practical security hardening for StatefulSets. We will cover access control, secrets management, pod security, network policies, storage protection, and operational verification. Each section includes concrete commands and configuration examples you can apply to your cluster. The focus is on actionable steps that reduce attack surface without breaking application functionality. Security is not a one-time task but a continuous practice. This guide helps you build a hardening checklist suitable for production environments. By following these steps, you can protect stateful workloads against common threats and meet compliance requirements. The examples use Kubernetes 1.28+ and assume a basic understanding of StatefulSets. ## Version and Environment Inventory Before hardening, document your Kubernetes version, storage classes, and StatefulSet configurations. Knowing the exact environment helps you choose the right security features and avoid compatibility issues. ### Cluster baseline Run the following commands to gather version and node information: ```bash kubectl version --short kubectl get nodes -o wide kubectl get storageclass ``` Expected output resembles: ```text Client Version: v1.28.3 Server Version: v1.28.3 NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME node-1 Ready control-plane 10d v1.28.3 192.168.1.10 Ubuntu 22.04.3 LTS 5.15.0-91-generic containerd://1.7.2 node-2 Ready 10d v1.28.3 192.168.1.11 Ubuntu 22.04.3 LTS 5.15.0-91-generic containerd://1.7.2 NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE standard (default) rancher.io/local-path Delete WaitForFirstConsumer false 10d ``` Note the storage class reclaim policy. For stateful data, consider using a storage class with `Retain` policy to prevent accidental data loss. ### Existing StatefulSet review List existing StatefulSets and inspect their security-relevant fields: ```bash kubectl get statefulsets --all-namespaces kubectl describe statefulset -n ``` Pay attention to: - `serviceAccountName`: which service account the pods use - `securityContext`: pod and container level settings - `volumeClaimTemplates`: PVCs and storage classes - `podManagementPolicy`: OrderedReady (default) or Parallel Also check the Kubernetes version for enabled admission controllers and feature gates. Pod Security Admission (PSA) and NodeRestriction are important for hardening. To see enabled admission plugins (if you have access to the API server), use: ```bash kubectl get --raw /metrics | grep apiserver_admission_controller_admission_duration_seconds | head ``` For managed clusters, check the provider documentation. ## Safe Configuration Path Implement hardening in small, reviewable steps. Start with the least disruptive changes: service accounts, security contexts, and secrets. Then apply network policies and pod security standards. Each step includes a verification command. ### Step 1: Dedicated service account with least privilege Each StatefulSet should use its own service account rather than the default. Create a service account and assign only the roles it needs via RBAC. Create a service account: ```bash kubectl create serviceaccount myapp-sa -n mynamespace ``` If your application does not need Kubernetes API access, do not mount the default token. In the StatefulSet pod spec, set `automountServiceAccountToken: false`: ```yaml apiVersion: apps/v1 kind: StatefulSet metadata: name: myapp namespace: mynamespace spec: serviceName: myapp replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: serviceAccountName: myapp-sa automountServiceAccountToken: false containers: - name: app image: myapp:1.0 ``` Apply and confirm: ```bash kubectl apply -f statefulset.yaml kubectl get pod -n mynamespace -l app=myapp -o jsonpath='{.items[0].spec.serviceAccountName}{"\n"}' ``` Expected output: `myapp-sa` If your application needs API access, grant specific permissions using Roles and RoleBindings. For example, read-only access to ConfigMaps in the same namespace: ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: mynamespace name: configmap-reader rules: - apiGroups: [""] resources: ["configmaps"] verbs: ["get", "list", "watch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: namespace: mynamespace name: read-configmaps subjects: - kind: ServiceAccount name: myapp-sa namespace: mynamespace roleRef: kind: Role name: configmap-reader apiGroup: rbac.authorization.k8s.io ``` Apply the RBAC files: ```bash kubectl apply -f role.yaml -f rolebinding.yaml ``` ### Step 2: Pod and container security contexts Set security contexts to enforce least privilege at runtime. Key settings: - `runAsNonRoot: true` - `runAsUser: ` - `allowPrivilegeEscalation: false` - `capabilities: drop: ["ALL"]` - `seccompProfile: RuntimeDefault` Example pod spec snippet: ```yaml spec: securityContext: runAsNonRoot: true runAsUser: 1000 runAsGroup: 2000 fsGroup: 2000 seccompProfile: type: RuntimeDefault containers: - name: app image: myapp:1.0 securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true ``` Note: `readOnlyRootFilesystem` may require writable volumes for temporary files. Add `emptyDir` volumes if needed. Apply and verify: ```bash kubectl apply -f statefulset.yaml kubectl get pod -n mynamespace -l app=myapp -o jsonpath='{.items[0].spec.containers[0].securityContext}{"\n"}' ``` Expected output: ```json {"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]},"readOnlyRootFilesystem":true} ``` ### Step 3: Secret management Avoid environment variables for secrets; prefer mounted volumes from Kubernetes Secrets. Enable encryption at rest for Secrets in etcd (requires cluster admin). Use tools like Sealed Secrets or External Secrets Operator for GitOps workflows. Create a secret: ```bash kubectl create secret generic db-credentials -n mynamespace --from-literal=username=appuser --from-literal=password='S3cureP@ss' ``` Mount the secret as a volume in the StatefulSet: ```yaml spec: template: spec: containers: - name: app image: myapp:1.0 volumeMounts: - name: db-secret mountPath: /etc/secrets/db readOnly: true volumes: - name: db-secret secret: secretName: db-credentials ``` Verify the secret is mounted: ```bash kubectl exec -n mynamespace myapp-0 -- ls /etc/secrets/db ``` Expected output: ```text password username ``` ### Step 4: Network policies StatefulSets often need stable network identities. Use NetworkPolicies to restrict traffic to only necessary sources and ports. The following policy allows ingress to pods with label `app: myapp` from pods with label `access: allowed` on TCP 5432 (PostgreSQL example). ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: myapp-network-policy namespace: mynamespace spec: podSelector: matchLabels: app: myapp policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: access: allowed ports: - protocol: TCP port: 5432 ``` Apply: ```bash kubectl apply -f networkpolicy.yaml ``` Test connectivity from an allowed pod and a denied pod. Allowed pod should succeed, denied pod should timeout. ### Step 5: Pod Security Standards Enforce baseline or restricted Pod Security Standards at namespace level. For new clusters, use PSA labels. Example label for baseline: ```bash kubectl label namespace mynamespace pod-security.kubernetes.io/enforce=baseline ``` For existing StatefulSets, ensure they comply. If not, adjust security contexts as needed. You can also use a validating webhook like Kyverno or OPA Gatekeeper for more granular policies. Apply label and check warnings: ```bash kubectl label namespace mynamespace pod-security.kubernetes.io/enforce=baseline --overwrite kubectl get events -n mynamespace --field-selector type=Warning ``` No warnings indicate compliance. ### Step 6: Storage hardening Persistent volume claims should be protected. Ensure PVCs use ReadWriteOnce (default) unless shared storage is required. Use storage classes with `volumeBindingMode: WaitForFirstConsumer` to avoid premature node binding. Set reclaim policy to `Retain` for critical data to prevent deletion on PVC deletion. Example PVC template inside StatefulSet: ```yaml volumeClaimTemplates: - metadata: name: data spec: accessModes: [ "ReadWriteOnce" ] storageClassName: standard resources: requests: storage: 10Gi ``` Check existing PVCs: ```bash kubectl get pvc -n mynamespace ``` Expected output: ```text NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE data-myapp-0 Bound pvc-1234abcd-5678-efgh-ijkl-1234567890ab 10Gi RWO standard 5d data-myapp-1 Bound pvc-5678efgh-... 10Gi RWO standard 5d ``` ### Step 7: Enable audit logging Kubernetes audit logs record API requests. Configure audit policy to log events for StatefulSet resources. This helps detect unauthorized access. For managed clusters, enable audit logs in the cloud provider console. For self-managed, set `--audit-policy-file` and `--audit-log-path` on the API server. Example audit policy rule to log StatefulSet changes: ```yaml apiVersion: audit.k8s.io/v1 kind: Policy rules: - level: Metadata resources: - group: apps resources: ["statefulsets"] ``` Then restart API server with the policy file. Verify logs are written to the specified path. ## Verification and Diagnostics After applying hardening configurations, verify that everything works as expected. Use the following checks. ### Check pod security context ```bash kubectl get pod -n mynamespace -l app=myapp -o json | jq '.items[0].spec | {serviceAccountName, securityContext: .securityContext, automountServiceAccountToken}' ``` Expected output: ```json { "serviceAccountName": "myapp-sa", "securityContext": { "runAsNonRoot": true, "runAsUser": 1000, "runAsGroup": 2000, "fsGroup": 2000, "seccompProfile": { "type": "RuntimeDefault" } }, "automountServiceAccountToken": false } ``` If `automountServiceAccountToken` is false, the token should not be mounted. Verify: ```bash kubectl exec -n mynamespace myapp-0 -- ls /var/run/secrets/kubernetes.io/serviceaccount ``` Expected output: error or no such directory. ### Check network policy enforcement Test connectivity from a pod that should be allowed and one that should be denied. Create a temporary pod with label `access: allowed`: ```bash kubectl run test-allowed --image=busybox -n mynamespace --labels=access=allowed -- sleep 3600 ``` From that pod, try to connect to the StatefulSet service on port 5432: ```bash kubectl exec -n mynamespace test-allowed -- nc -zv myapp-0.myapp.mynamespace.svc.cluster.local 5432 ``` Expected output: `Connection to myapp-0.myapp.mynamespace.svc.cluster.local 5432 port [tcp/postgresql] succeeded!` Create a pod without the label: ```bash kubectl run test-denied --image=busybox -n mynamespace -- sleep 3600 ``` Test: ```bash kubectl exec -n mynamespace test-denied -- nc -zv myapp-0.myapp.mynamespace.svc.cluster.local 5432 ``` Expected output: timeout (no connection) Clean up test pods: ```bash kubectl delete pod test-allowed test-denied -n mynamespace ``` ### Check PSA enforcement If PSA baseline is enforced, attempting to run a privileged pod should be rejected. Try: ```bash kubectl run privileged-test --image=busybox -n mynamespace --overrides='{"spec":{"containers":[{"name":"privileged-test","image":"busybox","securityContext":{"privileged":true}}]}}' ``` Expected output: error message from admission webhook denying the pod. ### Audit log inspection If audit logging is enabled, look for StatefulSet-related events. Use your log aggregation tool or grep on the audit log file: ```bash grep "statefulsets" /var/log/kubernetes/audit/audit.log | tail ``` Expected output: lines containing `"resource":"statefulsets"` with metadata. ## Common Pitfalls and How to Avoid Them Even experienced teams encounter issues when hardening StatefulSets. Here are the most frequent mistakes, why they happen, and how to prevent or recover from them. ### Pitfall 1: Overly restrictive security contexts break applications **Why it happens**: Setting `runAsNonRoot: true` or `readOnlyRootFilesystem: true` without testing can cause the container to fail to start or crash because the application expects to run as root or write to its root filesystem. **How to avoid**: Test security contexts in a staging environment with the same container image. Check the image's Dockerfile or entrypoint to determine the intended user and filesystem writes. Use `kubectl logs` to diagnose failures. **Recovery**: Temporarily remove the restrictive field, fix the application or add writable volume mounts, then reapply. ### Pitfall 2: Network policies block required traffic **Why it happens**: A NetworkPolicy with a narrow `podSelector` or missing egress rules can block legitimate traffic, such as DNS lookups or connections to other services. **How to avoid**: Start with a policy that allows necessary egress (e.g., DNS on port 53) and then tighten ingress rules incrementally. Test connectivity from all relevant pods. **Recovery**: Delete or update the NetworkPolicy to add the missing selectors or ports. Reapply and verify. ### Pitfall 3: Using default service account with escalated permissions **Why it happens**: Teams often leave the default service account, which may have broader permissions than needed, especially if cluster roles were previously bound to it. **How to avoid**: Always create a dedicated service account for each StatefulSet and grant only the required RBAC permissions. Set `automountServiceAccountToken: false` if the pod does not need API access. **Recovery**: Switch to a new service account with proper RBAC and restart the StatefulSet pods. ### Pitfall 4: Secrets exposed via environment variables **Why it happens**: Developers often pass secrets as environment variables because it is convenient, but env vars can be logged or exposed via the API. **How to avoid**: Mount secrets as files in a volume and ensure they are read-only. Use a secrets management tool like External Secrets Operator or Sealed Secrets for GitOps. **Recovery**: Refactor the application to read secrets from files, update the StatefulSet spec, and rotate the secrets. ### Pitfall 5: Storage reclaim policy causes data loss **Why it happens**: The default storage class often has `Delete` reclaim policy. If a PVC is deleted accidentally, the underlying volume and all data are lost. **How to avoid**: Use a storage class with `Retain` policy for stateful workloads. Regularly back up persistent volumes. **Recovery**: If data is lost, restore from backup. If the volume still exists but is in `Released` state, you can manually recover it by creating a new PV and PVC referencing it. ### Pitfall 6: Ignoring Pod Security Standards warnings **Why it happens**: Teams apply PSA labels without checking compliance, leading to pods being rejected at creation time or warnings being ignored. **How to avoid**: Gradually enforce PSA by starting with `warn` and `audit` modes before `enforce`. Review existing workloads and fix security contexts. **Recovery**: Remove or adjust the PSA label temporarily, fix the pod specs, then reapply the label. ## Operations Checklist Use this checklist as part of your regular security review and when deploying new StatefulSets. Assign a single owner for each item and set a recurring review cadence. | Area | Check | Owner (example) | Review Frequency | Command or Action | |------|-------|-----------------|------------------|-------------------| | Service Account | Dedicated SA, token not automounted if unnecessary | Security Engineer (e.g., Priya Shah) | Monthly | `kubectl get pod -o json` inspect | | RBAC | Least privilege roles for SA | Platform Admin (e.g., Carlos Mendes) | Monthly | `kubectl auth can-i --as=system:serviceaccount:mynamespace:myapp-sa list pods` | | Security Context | runAsNonRoot, drop caps, seccomp | Application Owner (e.g., David Chen) | Weekly | `kubectl get pod -o jsonpath='{.spec.containers[0].securityContext}'` | | Secrets | Mounted as volumes, not env vars; encryption at rest | Security Engineer | Monthly | `kubectl get secret` and inspect pod spec | | Network Policies | Ingress/Egress restricted to necessary endpoints | Platform Admin | Monthly | `kubectl get networkpolicy` | | Pod Security | Namespace PSA label set to baseline/restricted | Platform Admin | Monthly | `kubectl get ns mynamespace --show-labels` | | Storage | PVC access modes, reclaim policy, backups | Application Owner | Quarterly | `kubectl get pvc` and `kubectl get storageclass` | | Auditing | Audit logs enabled for StatefulSet events | Security Engineer | Monthly | Check API server flags or cloud provider | | Updates | StatefulSet image updates use rolling update with health checks | Application Owner | Weekly | `kubectl get statefulset -o yaml` inspect `updateStrategy` | Run these checks periodically and after any configuration change. The owner is responsible for ensuring the check is performed and for remediating any failures. ## Conclusion Securing StatefulSets requires a layered approach: least privilege service accounts, runtime security contexts, secret management, network restrictions, and storage protection. This guide provided practical examples and verification steps for each layer. By implementing these hardening measures, you reduce the risk of data breaches and service disruption. Security is an ongoing process. Regularly review your StatefulSet configurations against the operations checklist, stay updated with Kubernetes security advisories, and test changes in a staging environment before production. The steps in this guide are designed to be incremental, allowing you to adopt them without a full redesign. Start with the most impactful changes: service accounts and security contexts, then add network policies and PSA. Your stateful workloads will be better protected against common threats. For further reading, consult the official Kubernetes documentation on StatefulSets, Pod Security Standards, and Network Policies. Remember to validate all changes with your team and maintain backups of critical data.