Security Basics in Kubernetes
-
Role-Based Access Control (RBAC)
- Use RBAC to define what actions a user, or a system component, can perform.
kubectl create role read-pods --verb=get,list --resource=pods kubectl create rolebinding read-pods-binding --role=read-pods --user=john
-
API Throttling
- Limit API requests to prevent DoS attacks.
-
Secret Management
- Use Kubernetes Secrets for storing sensitive data like API keys.
kubectl create secret generic api-key-secret --from-literal=api-key='1234567890'
Securing Node and Network Traffic
-
Node Hardening
- Apply OS-level security best practices on the nodes, such as firewalls and system patches.
-
Network Policies
- Define rules for how pods communicate with each other and with external networks.
kubectl apply -f network-policy.yaml
-
Encryption
- Use Transport Layer Security (TLS) for encrypted communication between nodes.
Cluster Authentication and Authorization
-
Authentication
- Use OpenID or OAuth for user-based authentication. Service Accounts for pod-to-API-server communication.
-
Authorization
- Use RBAC for fine-grained control over who can do what within the cluster.
Keeping Software and Dependencies Updated
-
Patch Management
- Regularly update all components, including Kubernetes itself, to the latest secure versions.
-
Vulnerability Scanning
- Use tools to scan for vulnerabilities in container images.
Security Policies: Pod Security, Network Policies
-
Pod Security Policies (PSP)
- Enforce security configurations like disallowing running containers as root.
-
Network Policies
- Define ingress and egress rules at the pod level. Block traffic that doesn’t meet the defined policies.
Troubleshooting Exercise: Debugging Network Policies
Setup Commands
Create a network policy that allows traffic from a specific namespace.
kubectl create namespace test-ns
kubectl label namespace test-ns purpose=test
kubectl run nginx --image=nginx -n test-ns
Create a network policy file named allow-from-test-ns.yaml
.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-from-test-ns
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
purpose: test
Apply the network policy.
kubectl apply -f allow-from-test-ns.yaml
Exercise
- Create a new pod in a different namespace and try to access the
nginx
pod intest-ns
. - Debug why it can or cannot access the
nginx
pod.
Debugging
Check the existing network policies.
kubectl get networkpolicies -n test-ns
Check pod labels and namespace labels.
kubectl get pods --show-labels -n test-ns
kubectl get namespaces --show-labels
Solution
If the new pod cannot access the nginx
pod, it is likely because the network policy is correctly isolating the nginx
pod to only allow traffic from the test-ns
namespace.