Kubernetes Security Best Practices

Security is a critical aspect of Kubernetes cluster management. A comprehensive security strategy involves implementing multiple layers of protection to safeguard your applications, data, and infrastructure. Kubernetes provides several built-in security features that, when properly configured, create a robust security posture for your cluster.

Role-Based Access Control (RBAC)

RBAC is a method of regulating access to Kubernetes resources based on the roles of individual users within your organization. It provides fine-grained control over who can perform what actions on which resources.

RBAC Components

ServiceAccount

An identity for processes that run in a Pod. When you create a Pod without specifying a ServiceAccount, it automatically uses the default ServiceAccount in the same namespace.

apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-serviceaccount
  namespace: my-namespace
    

Role and ClusterRole

Roles define permissions within a specific namespace, while ClusterRoles are cluster-scoped.

# Role example (namespace-scoped)
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: my-namespace
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]

# ClusterRole example (cluster-scoped)
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: secret-reader
rules:
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["get", "list", "watch"]
    

RoleBinding and ClusterRoleBinding

These bind roles to users, groups, or ServiceAccounts.

# RoleBinding example
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: my-namespace
subjects:
- kind: User
  name: jane
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

# ClusterRoleBinding example
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: read-secrets-global
subjects:
- kind: Group
  name: developers
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: secret-reader
  apiGroup: rbac.authorization.k8s.io
    

RBAC Best Practices

  • Follow the principle of least privilege - grant only necessary permissions
  • Use dedicated ServiceAccounts for different applications
  • Regularly audit RBAC configurations
  • Use namespaces to isolate resources and limit scope
  • Avoid using cluster-admin privileges for routine operations

Network Policies

Network Policies allow you to control traffic flow between pods and network endpoints. They act as a firewall for your pod network, enabling you to define ingress and egress rules.

Network Policy Example

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow-frontend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api-server
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080
  - from:
    - namespaceSelector:
        matchLabels:
          name: monitoring
    ports:
    - protocol: TCP
      port: 9090
    

Default Network Policies

Implement default deny policies to ensure all traffic is blocked by default, then explicitly allow necessary communication:

# Default deny all ingress traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
spec:
  podSelector: {}
  policyTypes:
  - Ingress

# Default deny all egress traffic  
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-egress
spec:
  podSelector: {}
  policyTypes:
  - Egress

# Allow DNS egress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-egress
spec:
  podSelector: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector: {}
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - protocol: UDP
      port: 53
    

Network Policy Best Practices

  • Start with default deny policies for both ingress and egress
  • Use namespace labels to control cross-namespace communication
  • Label your pods consistently to make policy creation easier
  • Regularly review and test network policies
  • Use a network policy visualization tool to understand traffic flows

Pod Security Standards

Kubernetes provides Pod Security Standards that define different isolation levels for pods. These standards help you enforce security best practices at the pod level.

Pod Security Levels

Privileged

Unrestricted policy, providing the widest possible level of permissions.

Baseline

Minimally restrictive policy that prevents known privilege escalations.

Restricted

Highly restrictive policy, following current Pod hardening best practices.

Pod Security Admission

Kubernetes includes a built-in admission controller to enforce Pod Security Standards:

apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodSecurity
  configuration:
    apiVersion: pod-security.admission.config.k8s.io/v1
    kind: PodSecurityConfiguration
    defaults:
      enforce: "restricted"
      enforce-version: "latest"
      audit: "restricted"
      audit-version: "latest"
      warn: "restricted"
      warn-version: "latest"
    exemptions:
      usernames: []
      runtimeClasses: []
      namespaces: [kube-system]
    

Security Context

Apply security contexts to your pods and containers to enforce security practices:

apiVersion: v1
kind: Pod
metadata:
  name: security-context-demo
spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
    runAsNonRoot: true
  containers:
  - name: sec-ctx-demo
    image: busybox
    command: ["sh", "-c", "sleep 1h"]
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]
      readOnlyRootFilesystem: true
    

Pod Security Best Practices

  • Run containers as a non-root user whenever possible
  • Set readOnlyRootFilesystem to true
  • Drop all capabilities and add only required ones
  • Set allowPrivilegeEscalation to false
  • Use seccomp profiles to restrict system calls
  • Implement resource limits to prevent resource exhaustion attacks

Additional Security Considerations

Image Security

  • Use trusted base images from reputable sources
  • Regularly scan images for vulnerabilities
  • Sign images and verify signatures before deployment
  • Use minimal images without unnecessary packages

Secret Management

  • Use Kubernetes Secrets or external secret management systems
  • Enable encryption at rest for Secrets
  • Regularly rotate secrets and credentials
  • Limit access to secrets using RBAC

Audit Logging

  • Enable and regularly review Kubernetes audit logs
  • Monitor for suspicious activities
  • Set up alerts for critical security events

Runtime Security

  • Consider using runtime security tools like Falco
  • Monitor for unusual process activity
  • Implement behavioral analysis for containers

Implementing these Kubernetes security best practices will help you build a defense-in-depth strategy that protects your cluster, applications, and data from potential threats. Remember that security is an ongoing process that requires regular review and updates as new threats emerge and your environment evolves.

Post a Comment

0 Comments