Runtime Detection with Falco-Style Rules
Scanners and admission policies judge a container before it runs. Once it runs, the question changes: is it doing what it was built to do? A web server that suddenly spawns a shell, reads /etc/shadow, connects to the container runtime's socket or to the cloud metadata address is doing something no scanner could have predicted, because the attacker decided it at run time. Runtime detection watches the system calls of every container and matches them against rules. Falco (a CNCF graduated project) is the best-known open-source engine; Tetragon, Tracee and the providers' runtime agents (GuardDuty runtime monitoring, Defender for Containers, GKE threat detection) work on the same idea. This lesson explains how such rules are built and runs a small engine that reads Falco-style conditions.
How it works
- A driver (an eBPF probe, or a kernel module) captures system calls on the node:
execve,openat,connect,mount,setns,ptraceand many more. - Each event is enriched with context: process name and command line, parent process, user, file descriptor name, container ID and image, and Kubernetes pod, namespace and labels.
- The rule engine evaluates every enabled rule's condition on the event; a match emits an alert with an output template and a priority, which goes to logs, a SIEM or a response system.
A rule in Falco's YAML format names a condition over those fields, usually built from reusable macros and lists:
- list: shell_binaries
items: [bash, sh, zsh, ash, dash]
- macro: spawned_process
condition: evt.type = execve
- macro: container
condition: container.id != host
- rule: Shell spawned in a container
desc: An interactive shell started inside a container; application containers should never need one.
condition: spawned_process and container and proc.name in (shell_binaries) and proc.tty != 0
output: "Shell in container (user=%user.name pod=%k8s.pod.name ns=%k8s.ns.name image=%container.image.repository cmd=%proc.cmdline parent=%proc.pname)"
priority: WARNING
tags: [container, shell, mitre_execution]Falco ships a default rule set along these lines; the rules in this lesson are written for the course and simplified, but use the same field names.
A tiny rule engine
The program parses Falco-style conditions (and, or, not, parentheses, =, !=, in (…), startswith, macros and lists) and runs seven rules over a synthetic stream of enriched events from the lab cluster: normal application activity followed by the steps an attacker takes after exploiting the web pod.
import re
LISTS = {"shell_binaries": ["bash", "sh", "zsh", "ash", "dash"],
"pkg_mgmt": ["apt", "apt-get", "apk", "yum", "dnf", "pip"],
"runtime_sockets": ["/var/run/docker.sock", "/run/containerd/containerd.sock"],
"sensitive_files": ["/etc/shadow", "/etc/sudoers", "/root/.ssh/id_rsa"]}
MACROS = {"spawned_process": "evt.type = execve",
"container": "container.id != host",
"open_write": "evt.type = openat and evt.is_open_write = true",
"open_read": "evt.type = openat and evt.is_open_write = false"}
RULES = [
("Shell spawned in a container", "WARNING", "spawned_process and container and proc.name in (shell_binaries) and proc.tty != 0"),
("Package manager in a container", "ERROR", "spawned_process and container and proc.name in (pkg_mgmt)"),
("Sensitive file read", "WARNING", "open_read and container and fd.name in (sensitive_files) and not proc.name in (sshd)"),
("Write below /etc", "ERROR", "open_write and container and fd.name startswith /etc/"),
("Runtime socket opened", "CRITICAL", "evt.type in (connect, openat) and container and fd.name in (runtime_sockets)"),
("Mount in a container", "CRITICAL", "evt.type = mount and container"),
("Cloud metadata contacted", "NOTICE", "evt.type = connect and container and fd.sip = 169.254.169.254 and not k8s.ns.name = kube-system"),
]
TOKEN = re.compile(r"\(|\)|,|!=|=|[^\s(),=!]+")
def parse(text):
toks = TOKEN.findall(text)
pos = 0
def peek():
return toks[pos] if pos < len(toks) else None
def take():
nonlocal pos
pos += 1
return toks[pos - 1]
def expr():
node = term()
while peek() == "or":
take(); node = ("or", node, term())
return node
def term():
node = factor()
while peek() == "and":
take(); node = ("and", node, factor())
return node
def factor():
if peek() == "not":
take(); return ("not", factor())
if peek() == "(":
take(); node = expr(); take(); return node
name = take()
if name in MACROS:
return parse(MACROS[name])
op = take()
if op == "in":
take(); items = []
while peek() != ")":
t = take()
if t != ",":
items += LISTS.get(t, [t])
take()
return ("in", name, items)
return (op, name, take())
return expr()
def ev(node, e):
op = node[0]
if op == "and": return ev(node[1], e) and ev(node[2], e)
if op == "or": return ev(node[1], e) or ev(node[2], e)
if op == "not": return not ev(node[1], e)
val = str(e.get(node[1], ""))
if op == "=": return val == node[2]
if op == "!=": return val != node[2]
if op == "in": return val in node[2]
if op == "startswith": return val.startswith(node[2])
raise ValueError(op)
compiled = [(name, prio, parse(cond)) for name, prio, cond in RULES]
def E(t, pod, etype, proc, **kw):
base = {"time": t, "k8s.pod.name": pod, "k8s.ns.name": kw.pop("ns", "shop"), "evt.type": etype, "proc.name": proc,
"container.id": "host" if pod == "-" else "c0ffee" + pod[-2:], "proc.tty": kw.pop("tty", 0)}
base.update(kw)
return base
events = [
E("10:00:01", "web-7d9", "execve", "gunicorn"),
E("10:00:02", "web-7d9", "openat", "gunicorn", **{"fd.name": "/app/config.yaml", "evt.is_open_write": "false"}),
E("10:00:05", "web-7d9", "connect", "gunicorn", **{"fd.sip": "10.10.0.140", "fd.name": "10.10.0.140:5432"}),
E("10:00:07", "cni-x1", "connect", "aws-node", ns="kube-system", **{"fd.sip": "169.254.169.254"}),
E("10:00:09", "-", "openat", "sshd", **{"fd.name": "/etc/shadow", "evt.is_open_write": "false"}),
E("10:14:30", "web-7d9", "execve", "sh", tty=34816, **{"proc.cmdline": "sh -i"}),
E("10:14:41", "web-7d9", "openat", "cat", **{"fd.name": "/etc/shadow", "evt.is_open_write": "false"}),
E("10:14:55", "web-7d9", "connect", "python3", **{"fd.sip": "169.254.169.254", "fd.name": "169.254.169.254:80"}),
E("10:15:20", "web-7d9", "execve", "apt-get", **{"proc.cmdline": "apt-get install -y nmap"}),
E("10:15:58", "web-7d9", "openat", "sh", **{"fd.name": "/etc/ld.so.preload", "evt.is_open_write": "true"}),
E("10:16:10", "web-7d9", "connect", "python3", **{"fd.name": "/var/run/docker.sock"}),
E("10:16:30", "web-7d9", "mount", "mount", **{"fd.name": "/dev/sda1"}),
]
for e in events:
for name, prio, cond in compiled:
if ev(cond, e):
print(f"{e['time']} {prio:8} {name:30} pod={e['k8s.pod.name']} proc={e['proc.name']} {e.get('fd.name', e.get('proc.cmdline', ''))}")10:14:30 WARNING Shell spawned in a container pod=web-7d9 proc=sh sh -i
10:14:41 WARNING Sensitive file read pod=web-7d9 proc=cat /etc/shadow
10:14:55 NOTICE Cloud metadata contacted pod=web-7d9 proc=python3 169.254.169.254:80
10:15:20 ERROR Package manager in a container pod=web-7d9 proc=apt-get apt-get install -y nmap
10:15:58 ERROR Write below /etc pod=web-7d9 proc=sh /etc/ld.so.preload
10:16:10 CRITICAL Runtime socket opened pod=web-7d9 proc=python3 /var/run/docker.sock
10:16:30 CRITICAL Mount in a container pod=web-7d9 proc=mount /dev/sda1
The five legitimate events (the application starting, reading its config, talking to the database, the CNI agent using the node's metadata endpoint from kube-system, and sshd on the host reading /etc/shadow) raise nothing. The attacker's session, starting with an interactive shell in the web pod at 10:14:30, raises an alert at every step: shell, sensitive file, metadata access, package install, a write below /etc, the runtime socket and a mount attempt. In a hardened pod most of those steps would also fail (no shell in a distroless image, read-only root filesystem, no socket mounted, seccomp blocking mount), and the detection would still fire on the attempt.
Writing rules that stay useful
- Start from behaviour the workload never shows: shells in application containers, package managers at run time, writes to binaries and
/etc, runtime sockets, unexpected outbound connections. These have very low false-positive rates. - Scope with Kubernetes metadata, not process names alone: an exception for
kube-systemor a named DaemonSet is far safer thannot proc.name = x, which an attacker can satisfy by renaming a binary. - Version, test and tune rules as code, like any detection (Detection as Code); replay recorded event streams such as the one above in CI.
- Respond proportionately: alert on most rules; consider automatic responses (kill the pod, isolate it with a NetworkPolicy, snapshot it for forensics) only for rules with near-zero false positives.
How it fits with the other layers
Runtime detection is the last layer, not the first: image hardening and Pod Security remove most attack paths, and runtime rules catch what gets through (a zero-day in the application, a misconfiguration nobody noticed). It also produces the evidence for incident response: which pod, which process, which command line, when (DFIR handoff).
Pitfalls
- Enabling the full default rule set on day one and drowning in alerts from legitimate system pods; tune per namespace before paging anyone.
- Exceptions by process name (
not proc.name in (python3)) that whitelist half of all attacker tooling. - Running the detector without protecting it: an attacker with node root can unload it, so alert when its heartbeat stops.
Practice
1. Add a rule "Outbound connection to a non-allow-listed address" for the web pod, allowing only the database. Write the condition.
evt.type = connect and container and k8s.pod.name startswith web- and not fd.sip in (10.10.0.140). In the engine it fires on the metadata connection at 10:14:55, and also on the socket connection at 10:16:10, because a Unix-socket event has no fd.sip and "not in" is true for an empty value; add fd.typechar = 4 (IPv4) to scope it to network connections. Real Falco rules use fd.snet or lists of networks for ranges.
2. Why didn't the shell rule fire for the sh process that wrote /etc/ld.so.preload?
That event is an openat, not an execve; the shell had already been reported when it was spawned at 10:14:30. Rules match single events; the story is reassembled by grouping alerts per pod.
3. The CNI agent's metadata access didn't alert because of not k8s.ns.name = kube-system. What is the risk of that exception, and how would you narrow it?
Any pod an attacker manages to run in kube-system is exempt. Narrow it to the specific DaemonSet (k8s.pod.name startswith aws-node- and the expected image), and restrict who can create pods in kube-system (RBAC Review).
Test yourself
What does a runtime detector like Falco observe?
- Dockerfiles
- System calls of processes on the node, enriched with container and Kubernetes context
- Git commits
- Cloud bills
How many alerts did the attacker's session raise in the program?
- 3
- 5
- 7
- 12
Why are exceptions by namespace or workload safer than by process name?
- They are faster
- An attacker can name a binary anything, but can't as easily choose the pod's namespace and workload
- Falco ignores process names
- They aren't safer