Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 11 · 40 minutes

Check container workloads for settings that break isolation

After this lesson you can
  • Say who looks after which layer of a managed Kubernetes cluster
  • Recognise the manifest settings that give a container the rights of its node
  • Check manifests with a program and repair the findings
Lab files of this lesson (24)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Larkfield is moving its shop from virtual machines to containers on a managed Kubernetes cluster. The platform team sends you five workload files before the first deployment: "You are not a Kubernetes administrator, and you do not have to be. Tell us which of these files would let a break-in of one container become a break-in of the whole cluster." This lesson is an overview with one practical check. It does not make you a cluster operator, and its last table says what it leaves out.

Recall

Lesson 10: at which point of a pipeline does a plan scan run, and what stops the pipeline?

Between plan and apply. The scanner ends with exit code 1 when a finding is high, and the pipeline stops at a step that fails.

Lesson 8: why can a container on a machine be a path to the credentials of that machine?

The metadata service answers every program that runs on the machine, and a container is a program on the machine. The hop limit of IMDSv2 and a small role for the machine are the guards.

The idea

A container is a process that runs with its own view of the file system, the network and the process list, on a kernel that it shares with other containers. An image is the packed file system that a container starts from. Kubernetes is the system that runs containers on a group of machines. Its words, as far as this lesson needs them:

WordMeaning
NodeOne machine of the cluster
PodThe smallest unit that Kubernetes runs: one or a few containers that share a network address
ManifestA file that describes what should run: a Pod, or a controller such as a Deployment that keeps several copies of a pod alive
Control planeThe API server and the database of the cluster. Every change to the cluster is a call to this API.
NamespaceA named part of a cluster, used to separate teams and to attach rules

In a managed cluster, such as Amazon EKS, the shared responsibility of lesson 1 has more layers.

Who looks after what in a managed cluster
Cloud accountyou, with IAM, network and audit logControl planethe provider runs and patches itNodesyou, unless you pay for managed nodesPod settingsyou, in every manifestImageyou, and everything packed inside itCloud accountyou, with IAM, network and audit logControl planethe provider runs and patches itNodesyou, unless you pay for managed nodesPod settingsyou, in every manifestImageyou, and everything packed inside it

A container is isolated by the kernel of its node, and a few settings of the manifest switch that isolation off. They are the centre of this lesson.

SettingWhat it gives the container
privileged: trueAlmost every right of the node's root user
hostNetwork, hostPID, hostIPCThe network, the process list or the shared memory of the node
A hostPath volumeA folder of the node's own disk. With /, the whole disk.
allowPrivilegeEscalation not falseA process may gain more rights than it started with
No runAsNonRootThe container may run as root

Kubernetes publishes the Pod Security Standards with three levels. Privileged has no limits. Baseline forbids the known escalations: privileged containers, host namespaces and hostPath volumes are among them. Restricted adds hardening: allowPrivilegeEscalation must be false, the container must run as non-root, and it must drop all capabilities. A cluster enforces a level for a namespace with a label, through the built-in Pod Security admission controller.

Two more settings are about operations and matter for security. An image tag such as latest moves: tomorrow the same manifest may run different code. And a container without resource limits can take all memory of its node.

For cloud credentials the rule of lesson 4 holds: a pod gets a role, not a key. On EKS the features for this are named IAM roles for service accounts and EKS Pod Identity.

Same idea, other namesAWSMicrosoft AzureGoogle Cloud
Managed KubernetesAmazon EKSAzure Kubernetes Service (AKS)Google Kubernetes Engine (GKE)

Worked example

1. Make the manifests

People write manifests in YAML. Kubernetes accepts JSON as well, and Python reads JSON with no extra package, so this lesson uses JSON. make_manifests.py writes five files into the folder manifests. Its image names start with the address of a registry, a store for container images: ecr is the registry of AWS (Amazon Elastic Container Registry).

The finished file: make_manifests.py

make_manifests.py

"""make_manifests.py: write five Kubernetes manifests, as JSON, into the folder manifests. Invented workloads."""
import json
from pathlib import Path

OUT = Path("manifests")
REGISTRY = "111122223333.dkr.ecr.eu-west-1.amazonaws.com"


def container(name, image, **more):
    return {"name": name, "image": image, **more}


def deployment(name, pod_spec, replicas=2):
    return {"apiVersion": "apps/v1", "kind": "Deployment", "metadata": {"name": name, "namespace": "shop"},
            "spec": {"replicas": replicas, "selector": {"matchLabels": {"app": name}},
                     "template": {"metadata": {"labels": {"app": name}}, "spec": pod_spec}}}


LIMITS = {"requests": {"cpu": "100m", "memory": "128Mi"}, "limits": {"cpu": "500m", "memory": "256Mi"}}
TIGHT = {"runAsNonRoot": True, "allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]},
         "seccompProfile": {"type": "RuntimeDefault"}}

MANIFESTS = {
    "orders-api.json": deployment("orders-api", {"containers": [
        container("api", REGISTRY + "/orders-api:1.14.2", resources=LIMITS, securityContext=TIGHT)]}),
    "web.json": deployment("web", {"containers": [
        container("web", REGISTRY + "/web:latest", resources=LIMITS, securityContext=TIGHT),
        container("sidecar", "logshipper", securityContext={"allowPrivilegeEscalation": False})]}),
    "node-agent.json": {"apiVersion": "apps/v1", "kind": "DaemonSet", "metadata": {"name": "node-agent", "namespace": "ops"},
                        "spec": {"selector": {"matchLabels": {"app": "node-agent"}},
                                 "template": {"metadata": {"labels": {"app": "node-agent"}}, "spec": {
                                     "hostNetwork": True, "hostPID": True,
                                     "containers": [container("agent", REGISTRY + "/node-agent:3.2.0", resources=LIMITS,
                                                              securityContext={"privileged": True})],
                                     "volumes": [{"name": "root", "hostPath": {"path": "/"}}]}}}},
    "report-job.json": {"apiVersion": "batch/v1", "kind": "CronJob", "metadata": {"name": "report-job", "namespace": "shop"},
                        "spec": {"schedule": "0 5 * * *", "jobTemplate": {"spec": {"template": {"spec": {
                            "restartPolicy": "Never",
                            "containers": [container("report", REGISTRY + "/report-job:2.0.1", securityContext=TIGHT,
                                                     env=[{"name": "AWS_ACCESS_KEY_ID", "value": "AKIAQ7XJ2MPLW" + "EXAMPLE"},
                                                          {"name": "REPORT_BUCKET", "value": "larkfield-orders"}])],
                            "volumes": [{"name": "tmp", "emptyDir": {}}]}}}}}},
    "debug-pod.json": {"apiVersion": "v1", "kind": "Pod", "metadata": {"name": "debug", "namespace": "default"},
                       "spec": {"containers": [container("shell", "ubuntu:latest", securityContext={"runAsUser": 0})],
                                "volumes": [{"name": "sock", "hostPath": {"path": "/var/run/docker.sock"}}]}},
}

if __name__ == "__main__":
    OUT.mkdir(exist_ok=True)
    for name, manifest in MANIFESTS.items():
        (OUT / name).write_text(json.dumps(manifest, indent=2) + "\n")
    print(f"{len(MANIFESTS)} manifests in {OUT}")
python3 make_manifests.py
ls manifests
5 manifests in manifests
debug-pod.json
node-agent.json
orders-api.json
report-job.json
web.json

2. Read one manifest

python3 -c "
import json
m = json.load(open('manifests/node-agent.json'))
print(m['kind'], m['metadata'])
print(json.dumps(m['spec']['template']['spec'], indent=1))" | head -n 24
DaemonSet {'name': 'node-agent', 'namespace': 'ops'}
{
 "hostNetwork": true,
 "hostPID": true,
 "containers": [
  {
   "name": "agent",
   "image": "111122223333.dkr.ecr.eu-west-1.amazonaws.com/node-agent:3.2.0",
   "resources": {
    "requests": {
     "cpu": "100m",
     "memory": "128Mi"
    },
    "limits": {
     "cpu": "500m",
     "memory": "256Mi"
    }
   },
   "securityContext": {
    "privileged": true
   }
  }
 ],
 "volumes": [

The interesting part of every manifest is the pod specification: the block with containers and volumes. In a Pod it is spec. In a Deployment or a DaemonSet (one pod on every node) it is spec.template.spec, and in a CronJob (a pod on a schedule) it is two levels deeper. This one asks for the network and the process list of the node, a privileged container and the whole disk.

3. Save the checker

k8s_check.py finds the pod specification and tests it. The function check returns a severity, a code and a text for each problem.

def check(manifest):
    """Return (severity, code, text) for each problem of one manifest."""
    spec, out = pod_spec(manifest), []
    for field in ("hostNetwork", "hostPID", "hostIPC"):
        if spec.get(field):
            out.append(("high", "HOST-NAMESPACE", f"{field} is true"))
    for volume in spec.get("volumes", []):
        if "hostPath" in volume:
            out.append(("high", "HOST-PATH", f"volume {volume['name']} mounts {volume['hostPath']['path']} of the node"))
    for c in spec.get("containers", []) + spec.get("initContainers", []):
        ctx = c.get("securityContext", {})
        if ctx.get("privileged"):
            out.append(("high", "PRIVILEGED", f"container {c['name']} is privileged"))
        if ctx.get("allowPrivilegeEscalation") is not False:
            out.append(("medium", "ESCALATION", f"container {c['name']} does not set allowPrivilegeEscalation to false"))
        if not ctx.get("runAsNonRoot") and not spec.get("securityContext", {}).get("runAsNonRoot"):
            out.append(("medium", "MAY-RUN-AS-ROOT", f"container {c['name']} does not set runAsNonRoot"))
        if tag_of(c["image"]) in (None, "latest") and "@sha256:" not in c["image"]:
            out.append(("medium", "MOVING-TAG", f"container {c['name']} uses {c['image']}"))
        if "limits" not in c.get("resources", {}):
            out.append(("low", "NO-LIMITS", f"container {c['name']} has no resource limits"))
    return out

Note the test is not False for allowPrivilegeEscalation: a missing setting is a finding, as in lesson 10. The helper tag_of takes the tag from an image name, and an image that is pinned by its hash (@sha256:) passes. Open the block and save the file.

The finished file: k8s_check.py

k8s_check.py

"""k8s_check.py: check Kubernetes manifests (JSON) for settings that break the isolation of a container.

    python3 k8s_check.py [folder]        default folder: manifests. Exit code 1 when a finding is high.
"""
import json
import sys
from pathlib import Path


def pod_spec(manifest):
    """Find the pod specification inside a Pod, a Deployment, a DaemonSet, a StatefulSet, a Job or a CronJob."""
    spec = manifest.get("spec", {})
    if manifest["kind"] == "Pod":
        return spec
    if manifest["kind"] == "CronJob":
        spec = spec["jobTemplate"]["spec"]
    return spec["template"]["spec"]


def tag_of(image):
    """The tag of an image name, or None. The part after the last slash holds it, after a colon."""
    last = image.rsplit("/", 1)[-1]
    return last.split(":", 1)[1] if ":" in last else None


def check(manifest):
    """Return (severity, code, text) for each problem of one manifest."""
    spec, out = pod_spec(manifest), []
    for field in ("hostNetwork", "hostPID", "hostIPC"):
        if spec.get(field):
            out.append(("high", "HOST-NAMESPACE", f"{field} is true"))
    for volume in spec.get("volumes", []):
        if "hostPath" in volume:
            out.append(("high", "HOST-PATH", f"volume {volume['name']} mounts {volume['hostPath']['path']} of the node"))
    for c in spec.get("containers", []) + spec.get("initContainers", []):
        ctx = c.get("securityContext", {})
        if ctx.get("privileged"):
            out.append(("high", "PRIVILEGED", f"container {c['name']} is privileged"))
        if ctx.get("allowPrivilegeEscalation") is not False:
            out.append(("medium", "ESCALATION", f"container {c['name']} does not set allowPrivilegeEscalation to false"))
        if not ctx.get("runAsNonRoot") and not spec.get("securityContext", {}).get("runAsNonRoot"):
            out.append(("medium", "MAY-RUN-AS-ROOT", f"container {c['name']} does not set runAsNonRoot"))
        if tag_of(c["image"]) in (None, "latest") and "@sha256:" not in c["image"]:
            out.append(("medium", "MOVING-TAG", f"container {c['name']} uses {c['image']}"))
        if "limits" not in c.get("resources", {}):
            out.append(("low", "NO-LIMITS", f"container {c['name']} has no resource limits"))
    return out


if __name__ == "__main__":
    folder = Path(sys.argv[1] if len(sys.argv) > 1 else "manifests")
    total = high = 0
    for path in sorted(folder.glob("*.json")):
        manifest = json.loads(path.read_text())
        for severity, code, text in check(manifest):
            total += 1
            high += severity == "high"
            print(f"{severity:7s} {code:16s} {manifest['kind']}/{manifest['metadata']['name']}: {text}")
    print(f"{total} findings, {high} high")
    sys.exit(1 if high else 0)

4. Check the five files

python3 k8s_check.py
echo "exit code $?"
high    HOST-PATH        Pod/debug: volume sock mounts /var/run/docker.sock of the node
medium  ESCALATION       Pod/debug: container shell does not set allowPrivilegeEscalation to false
medium  MAY-RUN-AS-ROOT  Pod/debug: container shell does not set runAsNonRoot
medium  MOVING-TAG       Pod/debug: container shell uses ubuntu:latest
low     NO-LIMITS        Pod/debug: container shell has no resource limits
high    HOST-NAMESPACE   DaemonSet/node-agent: hostNetwork is true
high    HOST-NAMESPACE   DaemonSet/node-agent: hostPID is true
high    HOST-PATH        DaemonSet/node-agent: volume root mounts / of the node
high    PRIVILEGED       DaemonSet/node-agent: container agent is privileged
medium  ESCALATION       DaemonSet/node-agent: container agent does not set allowPrivilegeEscalation to false
medium  MAY-RUN-AS-ROOT  DaemonSet/node-agent: container agent does not set runAsNonRoot
low     NO-LIMITS        CronJob/report-job: container report has no resource limits
medium  MOVING-TAG       Deployment/web: container web uses 111122223333.dkr.ecr.eu-west-1.amazonaws.com/web:latest
medium  MAY-RUN-AS-ROOT  Deployment/web: container sidecar does not set runAsNonRoot
medium  MOVING-TAG       Deployment/web: container sidecar uses logshipper
low     NO-LIMITS        Deployment/web: container sidecar has no resource limits
16 findings, 5 high
exit code 1

The five high findings are in two workloads. node-agent asks for everything. A monitoring agent may really need parts of that: such a workload is an exception that someone must approve, in a namespace of its own. debug mounts the socket of the container runtime, which is a remote control for every container of the node. orders-api has no line: it meets every check.

5. Run the key scanner over the same folder

A manifest is a text file in a repository. Use the scanner of lesson 4.

python3 scan_keys.py manifests
manifests/report-job.json:34  access key id     AKIAQ7XJ2MPLWEXAMPLE  key of user ci-deploy, Active
1 findings in 1 files, 0 allowed

The report job carries an access key in an environment variable, and it is the deploy key of lesson 4 again. The checker for pod settings did not see it. Two tools with two purposes found two kinds of problem in the same file.

Your turn

Copy the folder manifests to manifests-fixed and repair it.

  • Delete debug-pod.json: a debug pod does not belong in the files of a cluster.
  • Repair web.json so that it has no finding: fixed image tags for both containers, the full security settings and resource limits for the sidecar. Use orders-api.json as a model.
  • Repair report-job.json: add resource limits and remove the access key from the environment (the job will get a role through its service account).
  • Leave node-agent.json as it is, as the documented exception.

Then run both checkers on manifests-fixed.

Check yourself

Why is a hostPath volume for / a break of isolation, even if the container is not privileged?

The container can read and change every file of the node: the keys of the node, the files of other containers, the configuration of the container runtime. Whoever controls the container controls the node, and from the node they can reach every pod that runs there.

In a managed cluster the provider patches the control plane. Name two things that stay with you.

Any two of these: the settings of every pod, the images and what is packed in them, the nodes (unless they are managed too), who may call the API of the cluster, the network rules between pods, and the cloud roles that pods may use.

What is wrong with the image name logshipper, with no registry and no tag?

With no tag, the runtime takes latest, which can point to different code tomorrow. With no registry, the image comes from a public default registry, from whoever owns that name there. A manifest should name your own registry and a fixed version, or better the hash of the image.

Field notes

  • Enforce the Pod Security Standards in the cluster with the namespace label, at the level baseline or restricted. A check in the pipeline is a help for developers, and the admission controller is the control.
  • What this lesson leaves out, and what a cluster operator must learn elsewhere: access control inside the cluster (RBAC), network policies between pods, secrets and their encryption, image scanning and signing, the audit log of the cluster API, and the hardening of nodes. The CIS Kubernetes Benchmark and the security checklist of the Kubernetes documentation are the lists to work from.
  • Scan images for known vulnerabilities in the registry and in the pipeline ("Security operations basics", lessons 9 and 10, show how to rank what a scan finds). Trivy is one open tool that scans images and manifests.
  • Give each workload its own service account and its own small cloud role. One shared role for a whole cluster brings back the wide policy of lesson 3.
  • The audit log of the cluster API is separate from the audit log of the account. In a managed cluster, check whether it is switched on: it is the log that shows who created a privileged pod.