What are Network Policies?
Network Policies in Kubernetes are a feature that allows you to specify how a group of pods can communicate with each other at Layers 3 (IP) and 4 (TCP/UDP).
Note: Network policies are implemented by Network Plugins such as Weave, Calico, Cilium, etc, which are outside the scope of this document.
Specification Elements
The NetworkPolicy specification consists of four main elements:[1]
- podSelector - pods that this policy will apply to (i.e the policy target).
- policyTypes - defines which types of policies are included within this policy.
- ingress - allowed inbound traffic to the target pods (optional).
- egress - allowed outbound traffic from the target pods (optional).
Below shows an example:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
namespace: default
spec:
podSelector:
matchLabels:
app: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
- ipBlock:
cidr: 172.17.0.0/16
except:
- 172.17.1.0/24
- namespaceSelector:
matchLabels:
project: myproject
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 6379
egress:
- to:
- ipBlock:
cidr: 10.0.0.0/24
ports:
- protocol: TCP
port: 5978
Rule Order
The rules within the policy are not subjected to any order. Furthermore, the default behaviour, when no policies are defined, is to allow all communications so all pods can talk to each other freely.[2]
Deny All
To provide a deny all action to the policy a regular allow policy can be applied with an empty selector. Like so:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
namespace: default
spec:
podSelector: {}
policyTypes:
- Ingress
DNS Caveats
When applying your network policies you must ensure you do not block DNS, which Kubernetes uses to resolve name services to IP.
To permit DNS traffic for Kubernetes service lookup, the following can be added to your networkPolicy
.
...
- to:
- namespaceSelector:
matchLabels:
namespace: kube-system
ports:
- protocol: UDP
port: 53
Further Reading
If you are interested in learning more about Network Policies check out the following links:
https://kubernetes.io/docs/concepts/services-networking/network-policies/
References
"An Introduction to Kubernetes Network Policies for Security People." 23 Feb. 2019, https://medium.com/@reuvenharrison/an-introduction-to-kubernetes-network-policies-for-security-people-ba92dd4c809d. Accessed 5 Apr. 2019. ↩︎
"An Introduction to Kubernetes Network Policies for Security People." 23 Feb. 2019, https://medium.com/@reuvenharrison/an-introduction-to-kubernetes-network-policies-for-security-people-ba92dd4c809d. Accessed 5 Apr. 2019. ↩︎