Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Default-deny network policies

After this lesson: I can add default-deny network policies and prove that traffic stops.

60 min lesson7 commandsKubernetes lab: a one-node k3s cluster for each student on a private Ubuntu VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

One weak pod, and a flat network

An attacker gets into a small pod that only shows a status page. From there they reach the orders service, then the database.

Nothing stopped them, because in a new cluster every pod can reach every other pod.

The one rule

Warning

Everything in this module happens in the cluster of your own lab. Testing a cluster you do not own needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can add default-deny network policies and prove that traffic stops.

Key words

WordWhat it meansExample
NetworkPolicyrules for which traffic may reach or leave pods
Ingresstraffic coming in to a pod
Egresstraffic going out of a pod
Default denya policy that selects every pod and allows nothing
Selectorlabels that choose podsapp: api
Policy controllerthe part of the network that enforces policies

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A selected pod takes only allowed traffic

A pod no policy selects takes traffic from anyone. As soon as one policy selects it, only traffic some policy allows gets through.

Policies add up and never take away. So you start with a default deny that selects every pod, then add one small policy for each path the app needs.

The paths in orders

FromToNeeded?
front (role=frontend)api on 8080Yes
frontDNS in kube-systemYes, to find api by name
visitor in guestapiNo

The cells students fill in are left blank in this preview.

Try it: selected or not

Code: python
policies = [{"selects": "api", "from": ["frontend"]}]
pods = ["api", "db"]
for target in pods:
    chosen = [p for p in policies if p["selects"] == target]
    for source in ["frontend", "visitor"]:
        ok = not chosen or any(source in p["from"] for p in chosen)
        print(source, "->", target, "allowed" if ok else "refused")
# Add a policy that selects "db" and allows nobody. What changes?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A policy is only an object until enforced

The API server stores a NetworkPolicy and does nothing else. The network must enforce it. Flannel, your cluster's network, does not.

k3s adds a policy controller beside flannel, from kube-router. Never trust that from a document: send traffic before and after, and see it stop.

Start the api, the frontend and a visitor

Command
kubectl create namespace orders; kubectl create namespace guest; kubectl run api -n orders --image=busybox:1.37.0 --labels=app=api -- sh -c "mkdir -p /tmp/w && echo orders > /tmp/w/index.html && exec httpd -f -p 8080 -h /tmp/w"; kubectl expose pod api -n orders --port=80 --target-port=8080; kubectl run front -n orders --image=busybox:1.37.0 --labels=role=frontend -- sleep 3600; kubectl run visitor -n guest --image=busybox:1.37.0 -- sleep 3600; kubectl wait -n orders --for=condition=Ready pod/api pod/front --timeout=120s && kubectl wait -n guest --for=condition=Ready pod/visitor --timeout=120s

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Both reach the api before any policy

Command
kubectl exec -n orders front -- wget -qO- -T 3 http://api; kubectl exec -n guest visitor -- wget -qO- -T 3 http://api.orders

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the default deny

Command
mkdir -p ~/ch && printf '%s\n' 'apiVersion: networking.k8s.io/v1' 'kind: NetworkPolicy' 'metadata:' '  name: default-deny' '  namespace: orders' 'spec:' '  podSelector: {}' '  policyTypes: ["Ingress", "Egress"]' > ~/ch/deny.yaml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Apply it, try again, look up a name

Command
cd ~/ch && kubectl apply -f deny.yaml && sleep 5; kubectl exec -n orders front -- wget -qO- -T 3 http://api; kubectl exec -n guest visitor -- wget -qO- -T 3 http://api.orders; kubectl exec -n orders front -- nslookup api

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think a stored NetworkPolicy means the traffic is blocked. The API server accepts policies on a network that ignores them. Prove each policy by sending traffic that should fail, on the cluster you run.

Open only the two paths the app needs

Two small policies open what the table needs. The api takes port 8080 from pods labelled role=frontend. The frontend may go out to the api on 8080 and to DNS in kube-system on port 53.

Nothing else changes, so the visitor is still refused.

Write the two openings

Command
mkdir -p ~/ch && printf '%s\n' 'apiVersion: networking.k8s.io/v1' 'kind: NetworkPolicy' 'metadata:' '  name: api-from-frontend' '  namespace: orders' 'spec:' '  podSelector:' '    matchLabels:' '      app: api' '  policyTypes: ["Ingress"]' '  ingress:' '    - from:' '        - podSelector:' '            matchLabels:' '              role: frontend' '      ports:' '        - port: 8080' '---' 'apiVersion: networking.k8s.io/v1' 'kind: NetworkPolicy' 'metadata:' '  name: frontend-out' '  namespace: orders' 'spec:' '  podSelector:' '    matchLabels:' '      role: frontend' '  policyTypes: ["Egress"]' '  egress:' '    - to:' '        - podSelector:' '            matchLabels:' '              app: api' '      ports:' '        - port: 8080' '    - to:' '        - namespaceSelector:' '            matchLabels:' '              kubernetes.io/metadata.name: kube-system' '      ports:' '        - port: 53' '          protocol: UDP' '        - port: 53' '          protocol: TCP' > ~/ch/allow.yaml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Apply them and try both again

Command
cd ~/ch && kubectl apply -f allow.yaml && sleep 5; kubectl exec -n orders front -- wget -qO- -T 3 http://api; kubectl exec -n guest visitor -- wget -qO- -T 3 http://api.orders

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Find namespaces with no policy at all

A new namespace starts flat, with no policy. So list every namespace with its number of policies and ask about each zero.

Keep a test that sends one connection which must fail. If it ever succeeds, a policy or the controller has gone.

Count the policies in every namespace

Command
for n in $(kubectl get namespaces -o name | cut -d/ -f2); do echo "$n: $(kubectl get networkpolicy -n $n --no-headers 2>/dev/null | wc -l)"; done

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Assignment: decide like a policy controller

Write a small ingress policy checker.

selects(selector, labels) is True when every key and value of the selector is in the labels; {} selects every pod. ingress_allowed(policies, pod, source, port) is True when no policy selects the pod, or when some rule of a selecting policy matches: a from selector matches the source (no from means anyone) and the port is listed (no ports means any).

Code: python
def selects(selector, labels):
    # True when every key and value of selector is in labels. {} selects every pod.
    return False


def ingress_allowed(policies, pod, source, port):
    # policies: [{"podSelector": {...}, "ingress": [{"from": [selector, ...], "ports": [8080]}]}]
    # A pod no policy selects takes anything. Otherwise one rule must match:
    # a "from" selector matches the source (no "from" means anyone),
    # and the port is listed (no "ports" means any port).
    return False

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.