2
votes

Im trying to implement network policy in my kubernetes cluster to isolate my pods in a namespace but still allow them to access the internet since im using Azure MFA for authentication.

This is what i tried but cant seem to get it working. Ingress is working as expected but these policies blocks all egress.


apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
spec:
  podSelector: {}
  policyTypes:
  - Ingress 
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: grafana-policy
  namespace: default
spec:
  podSelector:
    matchLabels: 
      app: grafana
  ingress:
  - from:
    - podSelector:
       matchLabels: 
        app: nginx-ingress

Anybody who can tell me how i make above configuration work so i will also allow internet traffic but blocking traffic to other POD's?

3

3 Answers

2
votes

Try adding a default deny all network policy on the namespace:

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

Then adding an allow Internet policy after:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-internet-only
spec:
  podSelector: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 10.0.0.0/8
        - 192.168.0.0/16
        - 172.16.0.0/20

This will block all traffic except for internet outbound. In the allow-internet-only policy, there is an exception for all private IPs which will prevent pod to pod communication.

You will also have to allow Egress to Core DNS from kube-system if you require DNS lookups, as the default-deny-all policy will block DNS queries.

0
votes

Can you try like this?

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
spec:
  podSelector: {}
  policyTypes:
  - Ingress,Egress
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0

It should allow egress to all destinations. But if the destination is a pod, it should be blocked by the lacking ingress rules of the same NetworkPolicy.

0
votes

Kubernetes will allow all traffic unless there is a network policy. If a Network Policy is set, it will only allow traffic set by the network policy and deny everything else.

By default, pods are non-isolated; they accept traffic from any source.

Pods become isolated by having a NetworkPolicy that selects them. Once there is any NetworkPolicy in a namespace selecting a particular pod, that pod will reject any connections that are not allowed by any NetworkPolicy. (Other pods in the namespace that are not selected by any NetworkPolicy will continue to accept all traffic.)

https://kubernetes.io/docs/concepts/services-networking/network-policies/#isolated-and-non-isolated-pods

So you will need to specify the Egress rules as well in order for it to work the way you want :)