Pipelines stop known-bad code from shipping; they cannot see what happens after. Runtime detection watches running workloads (Falco and other eBPF-based sensors read system calls: a shell spawned in a container, a write to /etc, an unexpected outbound connection). Cloud security posture management (CSPM) continuously checks cloud accounts against benchmarks for misconfiguration. Compliance as code maps the controls of frameworks (CIS, SOC 2, ISO 27001, PCI DSS) to automated checks, so evidence is collected continuously instead of in a yearly scramble. All of it feeds incident response, and is tested with red-team and blue-team exercises. This lesson follows one intrusion attempt, and shows two failures: detections nobody tuned, and compliance that was a spreadsheet.
Difficulty: Master · Know this first: Lesson 246, Lesson 232
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from exploitation (or misconfiguration) to containment. It is a worked example, not a measurement. The triage and compliance hops decide whether problems are found in minutes or months.
Pick how detection rules are managed, how compliance is checked, and how often detections are exercised.
Three questions. No score is saved anywhere — this is just you against the material.
Runtime security and compliance grow in four levels: reading alerts and findings, running sensors and posture checks, automating compliance and response, and proving it with exercises.
At the basic level you can read a runtime alert and a posture finding.
Where it breaks: closing an alert as "expected" without recording why.
Try it: Basic
Falco reports "Terminal shell in container" for a production pod. What do you check first?
Now do it: Find the parent process in a Falco alert.
At the intermediate level you deploy and tune detection and posture tools.
Try it: Intermediate
An init container writes to /etc and triggers a rule on every deploy. What is the right fix?
Now do it: Write a Falco exception for one known behaviour.
At the advanced level evidence and containment are automated.
Try it: Advanced
An auditor asks for proof that databases were encrypted all year. What do you provide?
Now do it: Retrieve one control's evidence for last month.
At the master level detection and response are measured against real attacker behaviour.
Trade-off: more rules catch more and cost more triage; measure precision and coverage together.
Try it: Master
An exercise shows 5 of 19 techniques detected. What next?
Now do it: Map your current rules to ATT&CK techniques.
A Falco rule for a shell started in an application container, with a narrow exception, and a rule for application pods talking to the Kubernetes API (Falco rule syntax; check the default rules shipped with your version):
- macro: app_namespaces
condition: k8s.ns.name in (payments, checkout, exports)
- rule: Shell spawned in application container
desc: An interactive or scripted shell started inside an application container
condition: >
spawned_process and container and app_namespaces
and proc.name in (sh, bash, ash, dash, zsh)
and not proc.pname in (entrypoint.sh) # known: the image's own entrypoint
output: >
Shell in container (user=%user.name ns=%k8s.ns.name pod=%k8s.pod.name
image=%container.image.repository cmd=%proc.cmdline parent=%proc.pname)
priority: CRITICAL
tags: [mitre_execution, T1059]
- rule: Application pod contacts the Kubernetes API
desc: Application workloads should not talk to the API server
condition: outbound and container and app_namespaces and fd.sip.name = "kubernetes.default.svc"
output: K8s API contacted from app pod (pod=%k8s.pod.name cmd=%proc.cmdline)
priority: WARNING
Quarantining a pod during response: label it, and a pre-created NetworkPolicy that selects quarantine=true denies all its traffic, while the pod stays running for forensics.
kubectl label pod "$POD" -n exports quarantine=true --overwrite kubectl cordon "$NODE"
Posture and compliance on each cloud: AWS Security Hub (CIS AWS Foundations, AWS Foundational Security Best Practices, PCI DSS standards), AWS Config conformance packs, and Audit Manager; Microsoft Defender for Cloud with regulatory compliance dashboards and Azure Policy initiatives; Google Security Command Center with compliance reports; Prowler as an open-source multi-cloud checker.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The alert in a muted queue.
Rules were tuned to 6 alerts a day with documented exceptions, high-confidence rules page the security on-call, a quarantine runbook was automated, hostPath mounts are denied by admission policy, and quarterly purple-team exercises test the detections.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A practice cluster (kind and kubectl) and Helm, to run Falco; Python 3 for the program. Falco needs a kernel with eBPF support (most recent Linux kernels, and WSL 2).
Type each one, read what it prints, and compare it with the note above it.
Install Falco with the modern eBPF driver into the practice cluster.
Changes a real system: On a shared cluster, a new DaemonSet with kernel access needs a security review: use your own kind cluster.
helm repo add falcosecurity https://falcosecurity.github.io/charts && helm repo update helm install falco falcosecurity/falco -n falco --create-namespace --set driver.kind=modern_ebpf --set tty=true kubectl -n falco rollout status ds/falco --timeout=300s
Behave like an attacker: open a shell in a running container and read a sensitive file.
kubectl run victim --image=nginx:1.27 --restart=Never kubectl wait --for=condition=Ready pod/victim --timeout=120s kubectl exec victim -- sh -c "id; cat /etc/shadow > /dev/null"
Read what Falco detected.
kubectl -n falco logs ds/falco --tail=200 | grep -E "Terminal shell|sensitive file|shadow" | tail -5
detections.pyThis program measures a detection rule set the way a security team tunes it: alerts per rule per day, how many were real, and what a narrow exception does to precision without hiding the real intrusion. Then it builds compliance evidence for one control from daily check results and shows the gap that a yearly attestation would have missed. Save it as detections.py, then run it.
# detections.py
from datetime import date, timedelta
ALERTS = [ # (rule, source, real?)
*[("shell in container", "kubectl exec by an engineer", False)] * 40,
*[("write below /etc", "init container writes nginx.conf", False)] * 900,
*[("outbound to unknown IP", "metrics agent", False)] * 300,
("shell in container", "parent: java (payments-export)", True),
]
def report(alerts, exceptions):
kept = [a for a in alerts if not any(exc(a) for exc in exceptions)]
real = sum(1 for a in kept if a[2])
caught = any(a[2] for a in kept)
print(f" {len(kept):>5} alerts a day, {real} real, precision {(real / len(kept) if kept else 0):.1%}, intrusion {'SEEN' if caught else 'HIDDEN'}")
print("default rules:")
report(ALERTS, [])
print("with narrow, documented exceptions:")
report(ALERTS, [lambda a: a[1] == "init container writes nginx.conf",
lambda a: a[1] == "metrics agent",
lambda a: a[1] == "kubectl exec by an engineer"]) # exec is still logged in the API audit log
print("with a broad exception (all shells ignored):")
report(ALERTS, [lambda a: a[1] in ("init container writes nginx.conf", "metrics agent"),
lambda a: a[0] == "shell in container"])
print()
start = date(2026, 1, 1)
public_from = date(2026, 3, 14)
checks = [(start + timedelta(days=d), (start + timedelta(days=d)) >= public_from) for d in range(300)]
failing = [d for d, bad in checks if bad]
print("control STOR-01 'no public storage', evidence from daily checks:")
print(f" days checked {len(checks)}, days failing {len(failing)}, first failure {failing[0]}")
print(f" yearly attestation on {date(2026, 1, 15)} said: compliant")
Run it, and you should see this output:
$ python3 detections.py
default rules:
1241 alerts a day, 1 real, precision 0.1%, intrusion SEEN
with narrow, documented exceptions:
1 alerts a day, 1 real, precision 100.0%, intrusion SEEN
with a broad exception (all shells ignored):
0 alerts a day, 0 real, precision 0.0%, intrusion HIDDEN
control STOR-01 'no public storage', evidence from daily checks:
days checked 300, days failing 228, first failure 2026-03-14
yearly attestation on 2026-01-15 said: compliant
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/runtime-detection-cspm-and-compliance-as-code && cd ~/labs/runtime-detection-cspm-and-compliance-as-code) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Runtime Detection, Cloud Posture, Compliance as Code, and Security Evidence", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Install Falco with the modern eBPF driver into the practice cluster.'
'Behave like an attacker: open a shell in a running container and read a sensitive file.'
'Read what Falco detected.'
)
step_1() {
helm repo add falcosecurity https://falcosecurity.github.io/charts && helm repo update
helm install falco falcosecurity/falco -n falco --create-namespace --set driver.kind=modern_ebpf --set tty=true
kubectl -n falco rollout status ds/falco --timeout=300s
}
step_2() {
kubectl run victim --image=nginx:1.27 --restart=Never
kubectl wait --for=condition=Ready pod/victim --timeout=120s
kubectl exec victim -- sh -c "id; cat /etc/shadow > /dev/null"
}
step_3() {
kubectl -n falco logs ds/falco --tail=200 | grep -E "Terminal shell|sensitive file|shadow" | tail -5
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, tail, cat, Pipes, Redirection, If...Else.A fintech must pass SOC 2 and PCI DSS audits and has never detected an intrusion in its Kubernetes clusters. Design its runtime detection, posture, and compliance programme.
Which sensors and rules, and how are they tuned and routed? What is the containment runbook? How is cloud posture checked? How are controls mapped to checks, and where is evidence kept? How are detections tested?
Say 6 clusters, 900 pods, 40 cloud accounts, a security team of 5, and 2 audits a year.
Falco with the eBPF driver on every node, rules tuned per namespace with documented exceptions, critical rules paging a security on-call and others as tickets; a quarantine runbook (label, deny-all network policy, cordon, capture, rotate) with the first step automated; Security Hub (or the cloud equivalents) with CIS and PCI standards on all accounts, findings routed to owners with deadlines; controls mapped to Config conformance packs and Audit Manager (and OSCAL for documentation), manual controls marked with recorded evidence; daily evidence in an object-locked store; quarterly purple-team exercises with Atomic Red Team mapped to ATT&CK, gaps turned into rules.
Tuning takes weeks and must be maintained as workloads change; automated containment is fast and can disrupt service, so it starts with quarantine rather than deletion; continuous evidence needs storage and care with sensitive data in logs.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Untuned detections | Hop 4: Triage | Breaks | Default rules on all nodes produce 9,000 alerts a day, mostly from debugging sessions, init scripts, and monitoring agents. The queue was muted months ago. The "shell in container" alert from payments-export sits unread. |
| Compliance by spreadsheet | Hop 7: Compliance as code | Breaks | Controls are a spreadsheet, self-attested once a year. A storage account used for a partner integration allowed public blob access from March. Nothing checked it. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.