Question 24 - NetworkPolicy
Question 24 | NetworkPolicy
Use context: kubectl config use-context k8s-c1-H
There was a security incident where an intruder was able to access the whole cluster from a single hacked backend Pod.
To prevent this create a NetworkPolicy called np-backend in Namespace project-snake. It should allow the backend-* Pods only to:
- connect to db1-* Pods on port 1111
- connect to db2-* Pods on port 2222
Use the app label of Pods in your policy.
After implementation, connections from backend-Pods to vault- Pods on port 3333 should for example no longer work.
Analyzing this question, we need to create a network policy with egress for backend only allowing connections with specific pods. Since each has a different port, we need two rules. If we created a single rule filtering both labels and allowing both ports, both ports would be allowed for both pods and that's not what we want.
kubectl get pods -n project-snake
backend-0 1/1 Running 0 8s
db1-0 1/1 Running 0 8s
db2-0 1/1 Running 0 10s
vault-0 1/1 Running 0 10s
# Checking the app labels and also more information
k -n project-snake get pod -L app
NAME READY STATUS RESTARTS AGE APP
backend-0 1/1 Running 0 3m15s backend
db1-0 1/1 Running 0 3m15s db1
db2-0 1/1 Running 0 3m17s db2
vault-0 1/1 Running 0 3m17s vault
#
➜ k -n project-snake get pod -o wide
NAME READY STATUS RESTARTS AGE IP ...
backend-0 1/1 Running 0 4m14s 10.44.0.24 ...
db1-0 1/1 Running 0 4m14s 10.44.0.25 ...
db2-0 1/1 Running 0 4m16s 10.44.0.23 ...
vault-0 1/1 Running 0 4m16s 10.44.0.22 ...
vim /opt/course/24/networkpol.yaml
Let's edit the file by copying a network policy example from the documentation and adjusting it.
# /opt/course/24/networkpol.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: np-backend
namespace: project-snake
spec:
podSelector:
matchLabels:
app: backend # the pods that will have these network policies applied
policyTypes:
- Egress # egress policy
egress:
- # first rule
to:
- podSelector: # first condition
matchLabels:
app: db1
ports: # second condition
- protocol: TCP
port: 1111
- # second rule
to:
- podSelector: # first condition
matchLabels:
app: db2
ports: # second condition
- protocol: TCP
port: 2222
Now let's apply and check.
k apply -f /opt/course/24/networkpol.yaml
# We can now test if the backend can communicate with the vault
k -n project-snake exec backend-0 -- curl -s 10.44.0.22:3333
vault secret storage
➜ k -n project-snake exec backend-0 -- curl -s 10.44.0.25:1111
database one
➜ k -n project-snake exec backend-0 -- curl -s 10.44.0.23:2222
database two
➜ k -n project-snake exec backend-0 -- curl -s 10.44.0.22:3333
# Didn't communicate, so it's ok.