Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

Runtime Detection and Cluster Audit Logs

Produce a real Kubernetes audit log from a local v1.37 API server, read what it records for Secret reads, role bindings and pods/exec, write detections with an approved-exception list and a negative test, and triage three Falco shell alerts by correlating them with the audit log.

Contentsand lesson path

What you will learn

  • Deploy runtime threat detection and Kubernetes audit logging, and investigate an alert such as an interactive shell spawned in a container.

Prerequisites: Kubernetes Fundamentals

01. Goal and setup

Two sources show what happens in a cluster. The Kubernetes audit log is written by the API server: one event per request, with who made it, what it touched and the answer. A runtime sensor such as Falco watches system calls on each node and raises an alert when a process does something a rule describes, for example a shell starting inside a container. Neither is enough alone: the audit log does not see inside containers, and Falco does not know which API user caused a process. Here you write detections over a real audit log and use it to triage Falco alerts.

The activity maps to ATT&CK techniques: reading Secrets through the API (Unsecured Credentials: Container API, T1552.007), granting a powerful role (T1098.006) and running commands in a container (Container Administration Command, T1609).

Real and prepared parts. The control plane and its audit log are real. Falco cannot run here: it needs a kernel module or eBPF probe on a node, and this control plane has no nodes. A script writes three alerts in the JSON format of Falco 0.45, with rule names and output fields from the falcosecurity/rules 5.2.0 release.

You need: Linux on amd64, bash, curl, openssl, Python 3.10 or later, a terminal (for the interactive kubectl exec), and free ports 18379, 18380 and 18443. Versions: Kubernetes v1.37.2, etcd v3.6.16.

Folder layout
k8s-sec-lab/
├── get-bins.sh, bin/       step 1: Kubernetes v1.37.2 and etcd v3.6.16
├── audit-policy.yaml       step 2: what the API server records
├── start-cp.sh, stop-cp.sh step 2: start and stop the control plane
├── pki/, data/, logs/      created by start-cp.sh (logs/audit.log)
├── tokens.csv, encryption.yaml, kubeconfig  created by start-cp.sh
├── scenario.yaml, activity.sh              steps 3 and 4
└── falco_sample.py, investigate.py, report.txt  steps 6 and 7

02. Step 1: Get the binaries and start a clean control plane

If you did the lab Cluster Hardening: RBAC, Pod Security and Network Policy, you already have these files: stop it, delete its state with rm -rf data logs pki tokens.csv encryption.yaml *kubeconfig, and skip to the start command. Otherwise create k8s-sec-lab/ with the three scripts below and audit-policy.yaml from step 2.

Bash · get-bins.sh
#!/usr/bin/env bash
# get-bins.sh: download pinned control-plane binaries (Linux amd64) and check them.
set -euo pipefail
mkdir -p bin && cd bin
K=v1.37.2; E=v3.6.16
for b in kube-apiserver kube-controller-manager kube-scheduler kubectl; do
  curl -sSLO "https://dl.k8s.io/release/$K/bin/linux/amd64/$b"
  echo "$(curl -sSL "https://dl.k8s.io/release/$K/bin/linux/amd64/$b.sha256")  $b" \
    | sha256sum -c
done
ETCD=etcd-$E-linux-amd64
curl -sSLO "https://github.com/etcd-io/etcd/releases/download/$E/$ETCD.tar.gz"
curl -sSL "https://github.com/etcd-io/etcd/releases/download/$E/SHA256SUMS" \
  | grep " $ETCD.tar.gz$" | sha256sum -c
tar xzf "$ETCD.tar.gz" --strip-components=1 "$ETCD/etcd" "$ETCD/etcdctl"
rm "$ETCD.tar.gz"
chmod +x kube-* kubectl
./kubectl version --client | head -1
./etcd --version | head -1
Bash · start-cp.sh
#!/usr/bin/env bash
# start-cp.sh: a Kubernetes control plane on 127.0.0.1 with no nodes. Lab use only.
set -euo pipefail
cd "$(dirname "$0")"
B=$PWD/bin              # absolute paths, so kube-bench can recognise the processes
for port in 18379 18380 18443; do   # refuse to start next to another control plane
  if (exec 3<>/dev/tcp/127.0.0.1/$port) 2>/dev/null; then
    echo "port $port is already in use: run ./stop-cp.sh first"; exit 1
  fi
done
mkdir -p pki data logs
# 1. Keys and credentials, created on the first run only.
[ -f pki/sa.key ] || openssl genrsa -out pki/sa.key 2048 2>/dev/null
[ -f tokens.csv ] || cat > tokens.csv <<CSV
lab-admin-token,lab-admin,1000,system:masters
lab-alice-token,alice,1001,developers
lab-kcm-token,system:kube-controller-manager,1002,
lab-sched-token,system:kube-scheduler,1003,
CSV
[ -f encryption.yaml ] || cat > encryption.yaml <<YAML
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources: [secrets]
    providers:
      - secretbox:
          keys:
            - name: key1
              secret: $(head -c 32 /dev/urandom | base64)
      - identity: {}
YAML
# 2. etcd, plain HTTP on loopback (a real cluster uses TLS and client certs).
$B/etcd --name lab --data-dir data/etcd \
  --listen-client-urls http://127.0.0.1:18379 \
  --advertise-client-urls http://127.0.0.1:18379 \
  --listen-peer-urls http://127.0.0.1:18380 \
  --initial-advertise-peer-urls http://127.0.0.1:18380 \
  --initial-cluster lab=http://127.0.0.1:18380 > logs/etcd.log 2>&1 &
echo $! > etcd.pid
until $B/etcdctl --endpoints=127.0.0.1:18379 endpoint health >/dev/null 2>&1; do
  sleep 0.5
done
# 3. kube-apiserver with RBAC, audit logging and encryption at rest.
$B/kube-apiserver --bind-address=127.0.0.1 --secure-port=18443 \
  --advertise-address=127.0.0.1 --endpoint-reconciler-type=none --cert-dir=pki \
  --etcd-servers=http://127.0.0.1:18379 \
  --service-account-issuer=https://kubernetes.default.svc \
  --service-account-key-file=pki/sa.key \
  --service-account-signing-key-file=pki/sa.key \
  --service-cluster-ip-range=10.96.0.0/16 \
  --anonymous-auth=false --token-auth-file=tokens.csv \
  --authorization-mode=Node,RBAC \
  --audit-policy-file=audit-policy.yaml --audit-log-path=logs/audit.log \
  --encryption-provider-config=encryption.yaml \
  ${APISERVER_EXTRA_FLAGS:-} > logs/apiserver.log 2>&1 &
echo $! > apiserver.pid
for i in $(seq 30); do [ -f pki/apiserver.crt ] && break; sleep 1; done
# 4. One kubeconfig per identity: you (lab-admin, alice) and two controllers.
kc() {  # kc <file> <user> <token>
  local k="$B/kubectl --kubeconfig=$1 config"
  $k set-cluster lab --server=https://127.0.0.1:18443 \
    --certificate-authority=pki/apiserver.crt --embed-certs >/dev/null
  $k set-credentials "$2" --token="$3" >/dev/null
  $k set-context "$2" --cluster=lab --user="$2" >/dev/null
  $k use-context "$2" >/dev/null
}
kc kubeconfig alice lab-alice-token
kc kubeconfig lab-admin lab-admin-token
kc kcm.kubeconfig kcm lab-kcm-token
kc sched.kubeconfig sched lab-sched-token
export KUBECONFIG=$PWD/kubeconfig
for i in $(seq 60); do
  $B/kubectl get --raw /readyz >/dev/null 2>&1 && break
  kill -0 "$(cat apiserver.pid)" 2>/dev/null || { tail -3 logs/apiserver.log; exit 1; }
  sleep 1
done
# 5. Controller manager (namespaces, service accounts, aggregated roles) and scheduler.
$B/kube-controller-manager --kubeconfig=kcm.kubeconfig --secure-port=0 \
  --leader-elect=false \
  --controllers=*,-kube-apiserver-serving-clustertrustbundle-publisher-controller \
  --use-service-account-credentials --root-ca-file=pki/apiserver.crt \
  > logs/controller-manager.log 2>&1 &
echo $! > kcm.pid
$B/kube-scheduler --kubeconfig=sched.kubeconfig --secure-port=0 --leader-elect=false \
  > logs/scheduler.log 2>&1 &
echo $! > scheduler.pid
until $B/kubectl get serviceaccount default >/dev/null 2>&1; do sleep 1; done
echo "control plane ready on https://127.0.0.1:18443"
Bash · stop-cp.sh
#!/usr/bin/env bash
# stop-cp.sh: stop the processes that start-cp.sh started, by PID, and wait.
cd "$(dirname "$0")"
for p in scheduler kcm apiserver etcd; do
  [ -f $p.pid ] || continue
  pid=$(cat $p.pid)
  kill "$pid" 2>/dev/null && while kill -0 "$pid" 2>/dev/null; do sleep 0.2; done
  echo "stopped $p"
  rm -f $p.pid
done
Terminal
chmod +x get-bins.sh
./get-bins.sh
Expected output
kube-apiserver: OK
kube-controller-manager: OK
kube-scheduler: OK
kubectl: OK
etcd-v3.6.16-linux-amd64.tar.gz: OK
Client Version: v1.37.2
etcd Version: 3.6.16

03. Step 2: Decide what the API server records

An audit policy is a list of rules, checked in order; the first rule that matches a request sets its level. There are four levels. None records nothing. Metadata records the user, source address, verb, resource, response code and annotations, but no bodies. Request adds the request body. RequestResponse adds the response body too. Events are also written per stage; omitStages: [RequestReceived] drops the early copy of every request, and long-running requests such as exec still log both ResponseStarted and ResponseComplete.

YAML · audit-policy.yaml
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: [RequestReceived]
rules:
  # 1. Secrets, ConfigMaps, TokenRequests and TokenReviews: who touched which object,
  #    never the Secret values or the bearer tokens in the bodies.
  - level: Metadata
    resources:
      - group: ""
        resources: [secrets, configmaps, serviceaccounts/token]
      - group: authentication.k8s.io
        resources: [tokenreviews]
  # 2. Interactive access into pods: who, which pod, which command.
  - level: Metadata
    resources:
      - group: ""
        resources: [pods/exec, pods/attach, pods/portforward]
  # 3. Bodies that normally hold no Secret values: the image of a debug container, and
  #    the whole role binding after a change (the response, not only the patch).
  - level: Request
    resources:
      - group: ""
        resources: [pods/ephemeralcontainers]
  - level: RequestResponse
    verbs: [create, update, patch]
    resources:
      - group: rbac.authorization.k8s.io
        resources: [rolebindings, clusterrolebindings]
  # 4. Noise: health checks, leader-election leases, control-plane reads.
  - level: None
    nonResourceURLs: ["/readyz*", "/livez*", "/healthz*", "/version"]
  - level: None
    resources:
      - group: coordination.k8s.io
        resources: [leases]
  - level: None
    users: [system:apiserver, system:kube-controller-manager, system:kube-scheduler]
    verbs: [get, list, watch]
  - level: None
    userGroups: ["system:serviceaccounts:kube-system"]
    verbs: [get, list, watch]
  # 5. Changes keep the request body: who changed what, and to what.
  - level: Request
    verbs: [create, update, patch, delete, deletecollection]
  # 6. Everything else: metadata only.
  - level: Metadata

Rule 1 comes first for a reason. A Secret's value is in the request body when it is created and in the response body when it is read, so any level above Metadata would copy Secret values into the log, and the log would then need the same protection as etcd. Tokens need the same care: a TokenRequest (kubectl create token) returns a token in its response, and a TokenReview carries a live bearer token in spec.token of its request. Kubelets, aggregated API servers such as metrics-server, and Vault send TokenReviews to check tokens, so without tokenreviews in rule 1, rule 5 would log those tokens. Rule 2 records exec and port-forward sessions; the request URI holds the command and whether a terminal was requested. Rule 3 keeps bodies that normally hold no Secret values: a debug container's image, and the response for role bindings, which shows the whole binding even after a small patch. Rule 4 drops traffic that nobody investigates and keeps the log small enough to retain. The trade-off: reads with a stolen kube-system token are then logged only for the resources in rule 1. Rule 5 keeps bodies for other changes.

Terminal · keep this terminal for the whole lab
chmod +x start-cp.sh stop-cp.sh
./start-cp.sh
export KUBECONFIG=$PWD/kubeconfig PATH=$PWD/bin:$PATH
kubectl version | grep Server
kubectl auth whoami
Expected output
control plane ready on https://127.0.0.1:18443
Server Version: v1.37.2
ATTRIBUTE   VALUE
Username    lab-admin
UID         1000
Groups      [system:masters system:authenticated]

04. Step 3: Create the scenario

The shop namespace has a reporting job whose Role can read every Secret (the mistake you will find), a secrets operator in platform that may read exactly one Secret (an approved exception), and developers who may open shells in pods. The Role grants both get and create on pods/exec, because Kubernetes v1.37 opens kubectl exec over a WebSocket, an HTTP GET.

YAML · scenario.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: shop
---
apiVersion: v1
kind: Namespace
metadata:
  name: platform
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: reporter
  namespace: shop
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: external-secrets
  namespace: platform
---
# The mistake under investigation: a reporting job that may read every Secret.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: reporter
  namespace: shop
rules:
  - apiGroups: [""]
    resources: ["pods", "secrets"]
    verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: reporter
  namespace: shop
subjects:
  - kind: ServiceAccount
    name: reporter
    namespace: shop
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: reporter
---
# The approved pattern: one named Secret, read by the secrets operator.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: db-credentials-reader
  namespace: shop
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    resourceNames: ["db-credentials"]
    verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: external-secrets-db-credentials
  namespace: shop
subjects:
  - kind: ServiceAccount
    name: external-secrets
    namespace: platform
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: db-credentials-reader
---
# Developers may look at pods in shop and open a shell in them.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-debugger
  namespace: shop
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list"]
  - apiGroups: [""]
    resources: ["pods/exec"]
    verbs: ["get", "create"]   # kubectl exec over WebSocket needs both
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: developers-pod-debugger
  namespace: shop
subjects:
  - kind: Group
    name: developers
    apiGroup: rbac.authorization.k8s.io
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pod-debugger
---
apiVersion: v1
kind: Pod
metadata:
  name: web-0
  namespace: shop
spec:
  containers:
    - name: web
      image: registry.shop.example/web:1.4.2
---
apiVersion: v1
kind: Pod
metadata:
  name: api-0
  namespace: shop
spec:
  containers:
    - name: api
      image: registry.shop.example/api:2.3.0
Terminal
kubectl apply -f scenario.yaml
kubectl -n shop create secret generic db-credentials \
  --from-literal=password=lab-only-S3cret
Expected output
namespace/shop created
namespace/platform created
serviceaccount/reporter created
serviceaccount/external-secrets created
role.rbac.authorization.k8s.io/reporter created
rolebinding.rbac.authorization.k8s.io/reporter created
role.rbac.authorization.k8s.io/db-credentials-reader created
rolebinding.rbac.authorization.k8s.io/external-secrets-db-credentials created
role.rbac.authorization.k8s.io/pod-debugger created
rolebinding.rbac.authorization.k8s.io/developers-pod-debugger created
pod/web-0 created
pod/api-0 created
secret/db-credentials created

05. Step 4: Generate the activity

The script makes ten requests: four that are expected and six that an investigator should notice. Run it in a terminal, because the exec step asks for one.

Bash · activity.sh
#!/usr/bin/env bash
# activity.sh: generate the API activity that you will investigate.
cd "$(dirname "$0")"
export KUBECONFIG=$PWD/kubeconfig
k() { bin/kubectl "$@" 2>&1 | fold -s -w 80; }
REPORTER=$(bin/kubectl -n shop create token reporter --duration=10m)
ESO=$(bin/kubectl -n platform create token external-secrets --duration=10m)
echo "1. alice lists pods in shop (expected)"
k --user=alice -n shop get pods -o name
echo "2. external-secrets reads its one Secret (expected)"
k --token="$ESO" -n shop get secret db-credentials -o name
echo "3. reporter lists every Secret in shop"
k --token="$REPORTER" -n shop get secrets -o name
echo "4. reporter tries every namespace"
k --token="$REPORTER" get secrets --all-namespaces -o name
echo "5. alice opens an interactive shell in web-0"
bin/kubectl --user=alice -n shop exec -it web-0 -- sh 2>&1   # needs a terminal
echo "6. someone with admin rights gives reporter cluster-admin"
k create clusterrolebinding reporter-admin --clusterrole=cluster-admin \
  --serviceaccount=shop:reporter
echo "7. an admin gives alice read-only access to platform (expected)"
k -n platform create rolebinding alice-view --clusterrole=view --user=alice
echo "8. an admin labels alice-view (expected)"
k -n platform label rolebinding alice-view team=payments
echo "9. an admin adds mallory to the existing cluster-admin binding"
k patch clusterrolebinding cluster-admin --type=json -p '[{"op": "add",
  "path": "/subjects/-", "value": {"kind": "User", "name": "mallory"}}]'
echo "10. an admin acts as reporter (--as) and lists Secrets in platform"
k --as=system:serviceaccount:shop:reporter -n platform get secrets
Terminal
chmod +x activity.sh
./activity.sh
Expected output
1. alice lists pods in shop (expected)
pod/api-0
pod/web-0
2. external-secrets reads its one Secret (expected)
secret/db-credentials
3. reporter lists every Secret in shop
secret/db-credentials
4. reporter tries every namespace
Error from server (Forbidden): secrets is forbidden: User 
"system:serviceaccount:shop:reporter" cannot list resource "secrets" in API 
group "" at the cluster scope
5. alice opens an interactive shell in web-0
error: unable to upgrade connection: pod web-0 does not have a host assigned
6. someone with admin rights gives reporter cluster-admin
clusterrolebinding.rbac.authorization.k8s.io/reporter-admin created
7. an admin gives alice read-only access to platform (expected)
rolebinding.rbac.authorization.k8s.io/alice-view created
8. an admin labels alice-view (expected)
rolebinding.rbac.authorization.k8s.io/alice-view labeled
9. an admin adds mallory to the existing cluster-admin binding
clusterrolebinding.rbac.authorization.k8s.io/cluster-admin patched
10. an admin acts as reporter (--as) and lists Secrets in platform
No resources found in platform namespace.

The exec fails because the pod has no node. On a real cluster it opens a shell with one successful request.

06. Step 5: Read one audit event

Terminal
python3 - <<'PY' | fold -s -w 80
import json
for line in open("logs/audit.log"):
    e = json.loads(line)
    if e.get("objectRef", {}).get("subresource") == "exec":
        break  # the first exec event
print("level:", e["level"], "| stage:", e["stage"], "| verb:", e["verb"])
print("user:", e["user"]["username"], e["user"]["groups"])
print("from:", e["sourceIPs"], e["userAgent"])
print("object:", e["objectRef"])
print("requestURI:", e["requestURI"])
print("response:", e["responseStatus"]["code"], e["responseStatus"].get("message"))
for key, value in e["annotations"].items():
    print(f"{key}: {value}")
PY
Expected output
level: Metadata | stage: ResponseStarted | verb: get
user: alice ['developers', 'system:authenticated']
from: ['127.0.0.1'] kubectl/v1.37.2 (linux/amd64) kubernetes/c50e539
object: {'resource': 'pods', 'namespace': 'shop', 'name': 'web-0', 
'apiVersion': 'v1', 'subresource': 'exec'}
requestURI: 
/api/v1/namespaces/shop/pods/web-0/exec?command=sh&container=web&stdin=true&stdo
ut=true&tty=true
response: 400 pod web-0 does not have a host assigned
authorization.k8s.io/decision: allow
authorization.k8s.io/reason: RBAC: allowed by RoleBinding 
"developers-pod-debugger/shop" of Role "pod-debugger" to Group "developers"

This one event answers most first questions about a shell in a pod: who (alice, in group developers), from where, with which client, into which pod, which command (command=sh), with a terminal (tty=true), and which binding allowed it. The ResponseStarted stage marks the start of a long-running session; its matching ResponseComplete event marks the end. kubectl tried the WebSocket (get) first and then the older SPDY protocol (create), so this attempt appears as two requests.

07. Step 6: Understand the Falco alerts

A Falco rule has a condition over event fields and macros (named, reusable conditions), an output template and a priority. Here is the stable rule for interactive shells, with the macro that decides what counts as an entry point.

YAML · excerpt from falco_rules.yaml (falcosecurity/rules 5.2.0)
- rule: Terminal shell in container
  condition: >
    spawned_process
    and container
    and shell_procs
    and proc.tty != 0
    and container_entrypoint
    and not user_expected_terminal_shell_in_container_conditions
  priority: NOTICE
  tags: [maturity_stable, container, shell, mitre_execution, T1059]

- macro: container_entrypoint
  condition: (not proc.pname exists or proc.pname in (runc:[0:PARENT],
    runc:[1:CHILD], runc, docker-runc, exe, docker-runc-cur, containerd-shim,
    systemd, crio, conmon))

The rule fires only for a shell with a terminal whose parent is the container runtime: what kubectl exec -it or a runtime exec on the node produces. A shell that the application itself starts, for example after command injection, has the application as its parent and no terminal, so it is caught by another stable rule, Run shell untrusted, which lists web servers, databases and similar programs as parents that should not start shells. Falco adds k8s.ns.name and k8s.pod.name as JSON fields when append_output in falco.yaml lists them as extra_fields; the sample assumes that.

Python · falco_sample.py
"""falco_sample.py: write three alerts in the JSON format of Falco 0.45.

Falco needs a kernel module or eBPF probe on a real node, so this lab cannot run it.
Rule names, tags and output labels (a subset for "Run shell untrusted") follow
falcosecurity/rules 5.2.0. Only the timestamps come from your audit log.
"""
import json
from datetime import datetime, timedelta, timezone

COMMON = [("evt_type", "evt.type"), ("user", "user.name"), ("user_uid", "user.uid"),
          ("user_loginuid", "user.loginuid"), ("process", "proc.name"),
          ("proc_exepath", "proc.exepath"), ("parent", "proc.pname"),
          ("command", "proc.cmdline"), ("terminal", "proc.tty"),
          ("exe_flags", "evt.arg.flags"), ("container_id", "container.id"),
          ("container_name", "container.name")]
ANCESTORS = [("parent_exe", "proc.pexe"), ("parent_exepath", "proc.pexepath"),
             ("pcmdline", "proc.pcmdline"), ("gparent", "proc.aname[2]"),
             ("ggparent", "proc.aname[3]")]
RULES = {
    "Terminal shell in container": (
        "A shell was spawned in a container with an attached terminal", COMMON,
        ["maturity_stable", "container", "shell", "mitre_execution", "T1059"]),
    "Run shell untrusted": (
        "Shell spawned by untrusted binary", ANCESTORS + COMMON,
        ["maturity_stable", "host", "container", "process", "shell",
         "mitre_execution", "T1059.004"]),
}


def alert(when, rule, fields):
    message, labels, tags = RULES[rule]
    shown = {field: fields.get(field, "<NA>") for _, field in labels}
    text = " ".join(f"{label}={shown[field]}" for label, field in labels)
    clock = when.strftime("%H:%M:%S.%f") + "000"
    return {"hostname": "lab-node-1", "output": f"{clock}: Notice {message} | {text}",
            "priority": "Notice", "rule": rule, "source": "syscall", "tags": tags,
            "time": when.strftime("%Y-%m-%dT%H:%M:%S.%f") + "000Z",
            "output_fields": {**shown, "k8s.ns.name": "shop",
                              "k8s.pod.name": fields["pod"]}}


def shell(pod, cid, parent, exe, cmdline, tty, **extra):
    return {"pod": pod, "evt.type": "execve", "user.name": "root", "user.uid": 0,
            "user.loginuid": -1, "proc.name": exe.rsplit("/", 1)[-1],
            "proc.exepath": exe, "proc.pname": parent, "proc.cmdline": cmdline,
            "proc.tty": tty, "evt.arg.flags": "EXE_LOWER_LAYER",
            "container.id": cid, "container.name": pod.rsplit("-", 1)[0], **extra}


execs = [json.loads(line) for line in open("logs/audit.log")
         if '"subresource":"exec"' in line]
t0 = datetime.strptime(execs[-1]["requestReceivedTimestamp"],
                       "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
nginx = {"proc.pexe": "/usr/sbin/nginx", "proc.pexepath": "/usr/sbin/nginx",
         "proc.pcmdline": "nginx -g daemon off;", "proc.aname[2]": "nginx",
         "proc.aname[3]": "containerd-shim"}
alerts = [
    alert(t0 + timedelta(seconds=2), "Terminal shell in container",
          shell("web-0", "3f1c2a9b7d10", "runc", "/bin/sh", "sh", 34816)),
    alert(t0 + timedelta(seconds=45), "Run shell untrusted",
          shell("api-0", "8be41d0c55a2", "nginx", "/bin/sh", "sh -c id", 0, **nginx)),
    alert(t0 + timedelta(minutes=20), "Terminal shell in container",
          shell("web-0", "3f1c2a9b7d10", "runc", "/bin/bash", "bash", 34817)),
]
with open("falco-alerts.jsonl", "w") as out:
    out.writelines(json.dumps(a) + "\n" for a in alerts)
print(f"wrote {len(alerts)} alerts to falco-alerts.jsonl")
Terminal
python3 falco_sample.py
head -n 1 falco-alerts.jsonl | python3 -m json.tool | fold -s -w 80
Illustrative output (the times come from your audit log)
wrote 3 alerts to falco-alerts.jsonl
{
    "hostname": "lab-node-1",
    "output": "15:08:52.132190000: Notice A shell was spawned in a container 
with an attached terminal | evt_type=execve user=root user_uid=0 
user_loginuid=-1 process=sh proc_exepath=/bin/sh parent=runc command=sh 
terminal=34816 exe_flags=EXE_LOWER_LAYER container_id=3f1c2a9b7d10 
container_name=web",
    "priority": "Notice",
    "rule": "Terminal shell in container",
    "source": "syscall",
    "tags": [
        "maturity_stable",
        "container",
        "shell",
        "mitre_execution",
        "T1059"
    ],
    "time": "2026-11-16T15:08:52.132190000Z",
    "output_fields": {
        "evt.type": "execve",
        "user.name": "root",
        "user.uid": 0,
        "user.loginuid": -1,
        "proc.name": "sh",
        "proc.exepath": "/bin/sh",
        "proc.pname": "runc",
        "proc.cmdline": "sh",
        "proc.tty": 34816,
        "evt.arg.flags": "EXE_LOWER_LAYER",
        "container.id": "3f1c2a9b7d10",
        "container.name": "web",
        "k8s.ns.name": "shop",
        "k8s.pod.name": "web-0"
    }
}

08. Step 7: Detect and triage

The script has three audit detections and one triage function. Secret reads by a service account alert unless they are on the approved list; denied reads alert at a lower level, because they show someone probing. Creating, updating or patching a binding to cluster-admin or admin alerts, except the bootstrap bindings the API server creates for itself. Each exec attempt becomes one record. With kubectl --as, user is who asked and impersonatedUser the identity whose rights were used; the script judges the second and reports both. For each Falco alert, the triage looks at the parent process first and only then for an exec into the same pod in the 60 seconds before the alert.

Python · investigate.py
"""investigate.py: detections over a Kubernetes audit log, then Falco alert triage."""
import json
from datetime import datetime, timedelta, timezone

# Approved exceptions, each with an owner and a ticket. Keep this list short.
ALLOWED_SECRET_READS = {
    ("system:serviceaccount:platform:external-secrets", "shop", "db-credentials"),
}
POWERFUL_ROLES = {"cluster-admin", "admin"}
BINDINGS = ("clusterrolebindings", "rolebindings")
RUNTIME_PARENTS = {"runc", "runc:[0:PARENT]", "runc:[1:CHILD]", "containerd-shim",
                   "crio", "conmon"}
EXEC_WINDOW = timedelta(seconds=60)
RETRY = timedelta(seconds=5)


def when(stamp):  # RFC 3339, up to 9 fractional digits -> aware datetime
    head, _, frac = stamp.rstrip("Z").partition(".")
    moment = datetime.fromisoformat(f"{head}.{frac[:6]:0<6}")
    return moment.replace(tzinfo=timezone.utc)


def who(user):  # "system:serviceaccount:shop:reporter" -> "sa shop/reporter"
    prefix = "system:serviceaccount:"
    if user.startswith(prefix):
        return "sa " + user[len(prefix):].replace(":", "/")
    return user


def actor(e):  # (identity whose rights the request used, name for the report)
    user = e["user"]["username"]
    acted_as = e.get("impersonatedUser", {}).get("username")
    if acted_as:  # kubectl --as: the request ran with the impersonated identity
        return acted_as, f"{who(user)} as {who(acted_as)}"
    return user, who(user)


def audit_detections(events):
    findings, execs = [], []
    for e in events:
        if e["stage"] != "ResponseComplete":
            continue  # long-running requests also log ResponseStarted; count each once
        ref, verb, (user, name) = e.get("objectRef", {}), e["verb"], actor(e)
        code, ns = e["responseStatus"]["code"], ref.get("namespace")
        if (ref.get("resource") == "secrets" and verb in ("get", "list", "watch")
                and user.startswith("system:serviceaccount:")):
            if (user, ns, ref.get("name")) in ALLOWED_SECRET_READS:
                continue  # approved exception: not an alert
            scope = f"in {ns}" if ns else "in all namespaces"
            findings.append(["HIGH" if code < 400 else "MEDIUM", "T1552.007",
                             f"{name} {verb} secrets {scope} -> {code}"])
        elif ref.get("resource") == "pods" and ref.get("subresource") == "exec":
            query = e["requestURI"].partition("?")[2]
            key, t = (name, ns, ref["name"], query), when(e["requestReceivedTimestamp"])
            if execs and execs[-1]["key"] == key and t - execs[-1]["time"] < RETRY:
                execs[-1]["requests"] += 1  # kubectl retried: same attempt
                execs[-1]["code"] = code
            else:
                execs.append({"key": key, "time": t, "requests": 1, "code": code})
        elif (ref.get("resource") in BINDINGS and verb in ("create", "update", "patch")
              and user != "system:apiserver"):  # skip the bootstrap bindings
            # A patch body may hold only the change; the response has the whole binding
            bodies = (e.get("responseObject", {}), e.get("requestObject", {}))
            body = next((b for b in bodies if "roleRef" in b), {})
            role = body.get("roleRef", {}).get("name")
            if role in POWERFUL_ROLES:
                subjects = ", ".join(s["name"] for s in body.get("subjects", []))
                findings.append(["HIGH", "T1098.006", f"{name} {verb} {ref['name']}"
                                 f" -> {code}\n{'':19}{role} to {subjects}"])
    for x in execs:
        name, ns, pod, query = x["key"]
        tty = "true" if "tty=true" in query else "false"
        findings.append(["INFO", "T1609", f"{name} exec into {ns}/{pod} tty={tty}"
                         f" ({x['requests']} requests) -> {x['code']}"])
    return findings, execs


def triage(alert, execs):
    f = alert["output_fields"]
    ns, pod, parent = f["k8s.ns.name"], f["k8s.pod.name"], f["proc.pname"]
    if parent not in RUNTIME_PARENTS:
        return "parent is the app, not an exec: likely code execution; contain the pod"
    for x in execs:
        delay = when(alert["time"]) - x["time"]
        if x["key"][1:3] == (ns, pod) and timedelta(0) <= delay <= EXEC_WINDOW:
            return f"matches an API exec by {x['key'][0]}: confirm the session"
    return "no API exec within 60 s: look for node-level access (crictl, nodes/proxy)"


audit = [json.loads(line) for line in open("logs/audit.log")]
falco = [json.loads(line) for line in open("falco-alerts.jsonl")]
findings, execs = audit_detections(audit)
print(f"audit findings: {len(findings)}")
for level, technique, text in findings:
    print(f"  {level:<6} {technique:<9} {text}")
print(f"falco alerts: {len(falco)}")
for a in falco:
    f = a["output_fields"]
    print(f'  {a["rule"]}: {f["k8s.ns.name"]}/{f["k8s.pod.name"]},'
          f' parent={f["proc.pname"]}, cmd="{f["proc.cmdline"]}"')
    print(f"    -> {triage(a, execs)}")
Terminal
python3 investigate.py | tee report.txt
Expected output
audit findings: 6
  HIGH   T1552.007 sa shop/reporter list secrets in shop -> 200
  MEDIUM T1552.007 sa shop/reporter list secrets in all namespaces -> 403
  HIGH   T1098.006 lab-admin create reporter-admin -> 201
                   cluster-admin to reporter
  HIGH   T1098.006 lab-admin patch cluster-admin -> 200
                   cluster-admin to system:masters, mallory
  HIGH   T1552.007 lab-admin as sa shop/reporter list secrets in platform -> 200
  INFO   T1609     alice exec into shop/web-0 tty=true (2 requests) -> 400
falco alerts: 3
  Terminal shell in container: shop/web-0, parent=runc, cmd="sh"
    -> matches an API exec by alice: confirm the session
  Run shell untrusted: shop/api-0, parent=nginx, cmd="sh -c id"
    -> parent is the app, not an exec: likely code execution; contain the pod
  Terminal shell in container: shop/web-0, parent=runc, cmd="bash"
    -> no API exec within 60 s: look for node-level access (crictl, nodes/proxy)

A detection is only useful if it stays quiet on normal activity. Check that the operator's Secret read and both changes to alice-view did not reach the report (request 1 reads pods, which no detection examines), and that no Secret value reached the log. Then review a fresh token, as a kubelet would: the TokenReview event must be in the log, the token must not. Finally, remove the approved exception from a copy of the script and run it, to prove that the exception, not a bug, silences the operator's read.

Terminal
echo "expected events that reached the report: \
$(grep -c -E 'external-secrets|alice-view' report.txt)"
echo "audit lines that contain the Secret value: \
$(grep -c lab-only-S3cret logs/audit.log)"
# Review a fresh token as a kubelet would; the log must hold the event, not the token.
T=$(kubectl -n shop create token reporter --duration=10m)
kubectl create -o jsonpath='{.status.user.username}{"\n"}' -f - <<EOF
{"apiVersion": "authentication.k8s.io/v1", "kind": "TokenReview",
 "spec": {"token": "$T"}}
EOF
sleep 1   # let the API server write the event
echo "TokenReview events at level Metadata: \
$(grep '"resource":"tokenreviews"' logs/audit.log | grep -c '"level":"Metadata"')"
echo "audit lines that contain the token: $(grep -c -F "$T" logs/audit.log)"
Expected output
expected events that reached the report: 0
audit lines that contain the Secret value: 0
system:serviceaccount:shop:reporter
TokenReview events at level Metadata: 1
audit lines that contain the token: 0
Terminal
grep -v '"system:serviceaccount:platform:external-secrets"' investigate.py \
  > no-allowlist.py
python3 no-allowlist.py | grep T1552
Expected output
  HIGH   T1552.007 sa platform/external-secrets get secrets in shop -> 200
  HIGH   T1552.007 sa shop/reporter list secrets in shop -> 200
  MEDIUM T1552.007 sa shop/reporter list secrets in all namespaces -> 403
  HIGH   T1552.007 lab-admin as sa shop/reporter list secrets in platform -> 200

The reporter read the Secrets in shop and then probed every namespace: remove secrets from its Role, then rotate db-credentials, because it has been read. Both cluster-admin changes came from an administrator identity: revert them unless its owner has a ticket, and ask about the read made as reporter. The first shell matches alice's exec: confirm with her that it was planned. The second shell was started by nginx with no exec at all, which points to code execution through the application (Exploit Public-Facing Application, T1190). Isolate the pod with a deny-all NetworkPolicy and keep it running for forensics instead of deleting it. The third shell came from the runtime but not through the API. The Kubernetes documentation warns that access to the kubelet API through nodes/proxy bypasses audit logging, and crictl on a node does too, so check who has those rights or node access. Finally, run ./stop-cp.sh.

09. Check your understanding

Practice check · 3 questions

Audit logs and runtime alerts

Three questions about the policy and the alerts in this lab.

Q1. A colleague moves the `Request` rule for create, update and patch to the top of `audit-policy.yaml` and restarts the API server. What does the log now hold for `kubectl create secret generic app --from-literal=token=abc`?
Q2. Why does the rule *Terminal shell in container* not fire for the `sh -c id` that nginx started in `api-0`?
Q3. Your audit policy records `pods/exec` at `Metadata`, as in step 5. After a real interactive session, which fact is missing from that event?
Practice only: not graded, not saved, not evidence.

10. Apply it

For the skill project, install Falco on your kind cluster with its Helm chart, enable the Kubernetes audit log on the kind control plane with this policy, and send both to one place. Then open an interactive shell in an application pod and write a short investigation note: the Falco alert, the matching audit event, who it was, and your conclusion. Extend investigate.py with one more detection, for example a service account that creates pods outside its own namespace (Deploy Container, T1610), and add a benign event that must not trigger it.

11. Review prompt

Without looking back:

  1. Why must the Secrets rule come before any rule with level Request or RequestResponse?
  2. Which fields of a pods/exec audit event tell you who ran what, in which pod, with a terminal?
  3. What separates the three shell alerts in this lab, and what would you do for each?
  4. How do you show that a detection does not alert on normal activity, and that an exception is what silences an alert?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check