Platform Engineering · Lesson 247

Runtime Detection, Cloud Posture, Compliance as Code, and Security Evidence

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: detect, contain, prove

Pick how detection rules are managed, how compliance is checked, and how often detections are exercised.

6alerts a day
18 minto contain an intrusion
48 hto find a misconfiguration

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

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.

Basic — Read alerts and findings

At the basic level you can read a runtime alert and a posture finding.

  • The alert's pod, image, process, parent, and rule; whether it is expected behaviour.
  • A posture finding's resource, check, owner, and fix.
  • Which framework control a check supports.

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.

Intermediate — Run sensors and posture checks

At the intermediate level you deploy and tune detection and posture tools.

  • Falco or Tetragon as a DaemonSet; rules tuned with documented exceptions.
  • Alert routing: page on high-confidence, ticket the rest; precision per rule.
  • CSPM with a benchmark on every account; findings routed to owners.

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.

Advanced — Automate compliance and response

At the advanced level evidence and containment are automated.

  • Controls mapped to checks (conformance packs, policy initiatives, OSCAL); gaps visible.
  • Evidence stored immutably, per control, per day.
  • First containment step automated (quarantine network policy), with safety rules.

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.

Master — Prove it with exercises

At the master level detection and response are measured against real attacker behaviour.

  • Purple-team exercises mapped to MITRE ATT&CK; coverage tracked per technique.
  • Metrics: time to detect, time to contain, precision, controls automated.
  • Findings from exercises and incidents turned into rules, runbooks, and controls.

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.

Go deeper

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.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The alert in a muted queue.

Timeline

  • Month 0Falco is deployed with default rules on all nodes. It produces about 9,000 alerts a day; the Slack channel is muted within a week.
  • Month 4, Day 0 02:10An attacker exploits a parser flaw in payments-export, gets a shell, and reads the pod's service account token. Falco raises a critical "shell in container" alert. Nobody reads it.
  • Day 0–4The attacker escapes to the node through a hostPath mount and collects secrets from other pods.
  • Day 4A cost anomaly leads to the investigation. Nodes are rebuilt, secrets rotated, and the Falco alert is found in the archive.

What changed after

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.

Try it yourself, from scratch

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).

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. 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

    Options: driver.kind=modern_ebpf uses the CO-RE eBPF probe, no kernel module; tty=true makes logs appear promptly.

    Expect: The Falco DaemonSet rolled out on every node.

    Clean up: helm uninstall falco -n falco, or delete the kind cluster.

  2. 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"

    Expect: The id output. Nothing visible happens in the pod; the sensor has seen it.

    Clean up: kubectl delete pod victim.

  3. Read what Falco detected.

    kubectl -n falco logs ds/falco --tail=200 | grep -E "Terminal shell|sensitive file|shadow" | tail -5

    Expect: Alerts naming the pod, the command line, and the rule (for example a shell in a container and a read of a sensitive file).

2. Python: detections.py

This 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

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

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.

Clarifying questions to ask

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?

Rough sizing

Say 6 clusters, 900 pods, 40 cloud accounts, a security team of 5, and 2 audits a year.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Untuned detectionsHop 4: TriageBreaksDefault 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 spreadsheetHop 7: Compliance as codeBreaksControls 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.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: The attack → eBPF sensors → Rules → Triage → Response → Cloud posture → Compliance as code → Evidence → Red and blue. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 248
Security Incident Response and Forensics: Contain the Attacker Without Destroying the Evidence

A security incident differs from an outage in one important way: there is someone on the other side, and the system is also a crime scene. Responders must preserve evidence before changing anything (disk snapshots, memory, logs…

Go to Lesson 248 →

Or browse the full course from the Lessons index.