I have a service sitting on the edge. This service needs to send some stuff somewhere over the Internet.
I'm using Canal CNI.
Can I define a NetworkPolicy that allows egress only to the internet, and not the rest of the cluster?
Something like the following would work:
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: only-allow-internet
spec:
policyTypes:
- Egress
# match all pods in the namespace
podSelector: {}
egress:
- to:
- ipBlock:
# allow all IPs
cidr: 0.0.0.0/0
except:
# except the private IP ranges: https://en.wikipedia.org/wiki/Private_network
- 10.0.0.0/8
- 192.168.0.0/16
- 172.16.0.0/20
It allows all IPs (since every IP matches 0.0.0.0/0
), except the private IP ranges that are defined by the IANA as private IP ranges.
Please note that this will break DNS lookups too, since by default kubernetes pods use the DNS server inside Kubernetes. You can verify it by running the following commands inside a pod:
$ nslookup google.com
$ nslookup google.com 8.8.8.8
First one will time out, while second one will work.
By default, Kubernetes DNS IP would be 10.96.0.10
. You can verify it by checking /etc/resolv.conf
inside a pod. Therefore, if you want DNS lookups to work, you might want to customize the NetworkPolicy
further, define more specific IP ranges to allow DNS lookups.
Alternatively, you can define the DNS at the pod definition level. Details are here: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-dns-config
Additionally, instead of blocking all private IP ranges, you can only block the cluster pod/service ranges. You can find them out in the kube-apiserver
parameters.