Question about Network policies. I would like to "lock down" all ingress / egres . . .

Stan Butler:
Question about Network policies. I would like to “lock down” all ingress / egress traffic to pods in a specific namespace like so:

---
apiVersion: <http://networking.k8s.io/v1|networking.k8s.io/v1>
kind: NetworkPolicy
metadata:
  name: deny-all
  namespace: dev
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

I would then use another policy to allow only a few specific ports to the pods in that namespace:

---
apiVersion: <http://networking.k8s.io/v1|networking.k8s.io/v1>
kind: NetworkPolicy
metadata:
  name: allowed-dev-ports
  namespace: dev
spec:
  podSelector:
    matchLabels:
      tier: web
  policyTypes:
  - Ingress
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 10.200.232.0/24      
    - ipBlock:
        cidr: 10.175.184.0/24      
    - ipBlock:
        cidr: 20.60.178.68/32      
  ingress:
  - from:
    - ipBlock:
        cidr: 10.175.184.0/24         

Any thoughts on the best way to accomplish something like this?

Stan Butler:
The allowed-dev-ports policy works perfectly until I add port numbers. DNS never resolves properly when I start filtering ports. I tried adding the entire TCP port range on the egress block like this:

---
apiVersion: <http://networking.k8s.io/v1|networking.k8s.io/v1>
kind: NetworkPolicy
metadata:
  name: allowed-dev-ports
  namespace: dev
spec:
  podSelector:
    matchLabels:
      tier: web
  policyTypes:
  - Ingress
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 10.200.232.0/24      
    - ipBlock:
        cidr: 10.175.184.0/24      
    - ipBlock:
        cidr: 20.60.178.68/32      
    ports:
      - protocol: TCP
        port: 1 
        endPort: 65535  

…but no it still can’t resolve DNS. Thoughts?

Pavan Rangaraju:
did you try with UDP as well, ideally DNS is udp

Stan Butler:
that was it! been staring at this too long.

Stan Butler:
FYI: this is the final NetworkPolicy that works:

---
apiVersion: <http://networking.k8s.io/v1|networking.k8s.io/v1>
kind: NetworkPolicy
metadata:
  name: allowed-dev-ports
  namespace: dev
spec:
  podSelector:
    matchLabels:
      tier: web
  policyTypes:
  - Ingress
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 10.200.202.0/24      
    - ipBlock:
        cidr: 10.175.104.0/24      
    - ipBlock:
        cidr: 20.60.108.68/32      
    ports:
      - protocol: TCP
        port: 80     
      - protocol: UDP
        port: 53
      - protocol: TCP
        port: 443            
      - protocol: TCP
        port: 8443                                                          
  ingress:
  - from:
    - ipBlock:
        cidr: 10.175.104.0/24

Thanks again!

unnivkn:
Hi @Stan Butler fyr:


Stan Butler:
@unnivkn, if I am using ipBlock, I would need to include subnets where the k8 nodes are hosted as well as the DNS port, correct?

unnivkn:
fyr: