You can generate Tetragon tracing policies with an LLM in a few seconds, and the YAML will look right: apiVersion: cilium.io/v1alpha1, a kprobes list, a selectors block with matchArgs and matchActions. The trouble is that a TracingPolicy is a thin layer over kernel functions. The model has to pick a real hook, declare the right argument types, and use only the operators and actions the CRD allows. Models get these wrong in two ways. Some mistakes fail loudly. Others pass validation, load into the agent, and never match anything. In our lab, a model-style draft for "alert on writes to /etc/shadow" got through the schema and the selector checks, and Tetragon's own kernel check only logged a warning about it. The agent would have loaded it, and the path filter would have read the wrong memory. A policy an LLM wrote is a draft until it fires on a write you planted and stays quiet on the ones you allowed.
Tetragon isn't Falco. Falco rules are conditions over a stream of events, while a Tetragon TracingPolicy picks the kernel hook itself and filters inside eBPF, so the failure modes are different. If you write Falco rules, see Falco rules with an LLM. This post is about Cilium Tetragon.
What we tested, and what we didn't
The real judge of a TracingPolicy is a running Tetragon agent on the kernel you care about. We didn't have a cluster or a privileged host for this guide, and our lab box can't load BPF programs. So we split the work into checks we could actually run, using Tetragon's own code instead of a look-alike linter:
- The CRD schema. We built a small Go harness against the cilium/tetragon source at the v1.7.1 release tag. It calls
tracingpolicy.FromFile, which parses the YAML strictly and validates it against the TracingPolicy CRD's OpenAPI schema, the same schemakubectlchecks when the CRD is installed. The TracingPolicy reference documents every field. - Selector encoding. The harness calls
selectors.InitKernelSelectors, the function the agent uses to turn selectors into the byte layout the BPF program reads. It enforces limits the schema doesn't, such as at most five selectors per hook. - The kernel. For kprobes, the harness calls
btf.ValidateKprobeSpec, the same check the agent runs before loading (source). It looks the function up in the kernel's BTF and compares argument indexes and types. For LSM hooks, it looks upbpf_lsm_<hook>in BTF, as the agent does. We ran it against the box's own kernel (Linux 6.12, BTF available, BPF LSM enabled). - The policy-mode option. The harness runs the
policy-modevalue throughpolicyconf.ParseMode, the parser the agent's option handler uses.
Two shortcuts, stated plainly: the box hides kernel addresses from non-root users, so the harness reads a copy of /proc/kallsyms with real symbol names and placeholder addresses (only names are used). And unprivileged feature probes can't confirm large-program support, so we told the harness to use the limits for kernels 5.3 and newer, which is what the agent detects on a 6.12 kernel.
The drafts below were written for this guide to reproduce mistakes models commonly make in Tetragon policies. They aren't a captured model transcript, and no model was called in the lab. Nothing here was loaded into a running agent, so we don't show Tetragon events.
How to generate Tetragon tracing policies with an LLM
The goal: alert when anything other than the expected admin tools writes to /etc/shadow, /etc/gshadow, /etc/sudoers or files under /root/.ssh/. These are classic persistence and credential targets (MITRE ATT&CK lists /etc/passwd and /etc/shadow, SSH authorized keys and sudo as techniques), and the goal is easy to state, which makes it a good test.
Step 1: Give the model the TracingPolicy schema and a real hook
Models write better Tetragon policies when the prompt pins down four things:
- The hook and its signature. Tetragon's hook points page covers kprobes, fentry, tracepoints, uprobes, USDTs and LSM hooks. For file writes, Tetragon's own file monitoring example hooks
security_file_permission, a kernel function that takes astruct file *and anintmask, and comments that0x2isMAY_WRITEand0x4isMAY_READ. Tell the model the hook and the argument types, and saysyscall: false. - The operators you allow. Paste the operator lists from the selectors page: for
matchArgsthat'sEqual,NotEqual,Prefix,Postfix,Maskand friends, and formatchBinariesit'sIn,NotIn,Prefix,NotPrefix,PostfixandNotPostfix. - The actions you allow. Start with
Postonly. AddOverrideorSigkilllater, on purpose. - Full binary paths.
matchBinariescompares the executable path, sopasswdwon't match/usr/bin/passwd.
Then ask for one policy and nothing else.
Step 2: Validate the first Tetragon draft against the CRD schema
Here's a typical first draft. It reads like Tetragon, but three of its words are borrowed:
apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
name: credential-file-writes
spec:
kprobes:
- call: "security_file_permission"
syscall: true
args:
- index: 0
type: "string"
- index: 1
type: "int"
selectors:
- matchArgs:
- index: 0
operator: "Contains"
values:
- "/etc/shadow"
- "/etc/sudoers"
- "/root/.ssh/authorized_keys"
- index: 1
operator: "Equal"
values:
- "2"
matchBinaries:
- operator: "NotEqual"
values:
- "passwd"
- "chpasswd"
- "visudo"
matchActions:
- action: Alert
The schema check:
$ tpcheck draft1.yaml
== draft1.yaml
[schema] FAIL: validation failed: spec.kprobes[0].selectors[0].matchBinaries[0].operator in body should be one of [In NotIn Prefix NotPrefix Postfix NotPostfix]
spec.kprobes[0].selectors[0].matchActions[0].action in body should be one of [Post FollowFD UnfollowFD Sigkill CopyFD Override GetUrl DnsLookup NoPost Signal TrackSock UntrackSock NotifyEnforcer CleanupEnforcerNotification Set]
spec.kprobes[0].selectors[0].matchArgs[0].operator in body should be one of [Equal NotEqual Prefix NotPrefix Postfix NotPostfix GreaterThan LessThan GT LT Mask SPort NotSPort SPortPriv NotSportPriv DPort NotDPort DPortPriv NotDPortPriv SAddr NotSAddr DAddr NotDAddr Protocol Family State InMap NotInMap CapabilitiesGained InRange NotInRange SubString SubStringIgnCase CelExpr FileType NotFileType]
All three findings are right. Contains isn't a matchArgs operator, NotEqual isn't a matchBinaries operator, and Alert isn't an action: events come from Post, which is also the default. Feed the exact output back and the model will usually pick Prefix, NotIn and Post.
One note on those lists: the enum values come from the CRD of the version you build against, and they change between releases. When we ran the same drafts through a newer build of Tetragon, the action list was different. Validate against the CRD of the version you actually run.
The schema check is fast, but it only knows field names and enum values. Everything below passed it.
Step 3: Check the hook against the kernel
With the three words fixed, the second draft is schema-clean. The kernel check disagrees:
$ tpcheck draft2.yaml
== draft2.yaml
[schema] ok (credential-file-writes "credential-file-writes")
[selectors] kprobes[0] security_file_permission: ok
[kernel] kprobes[0] __x64_security_file_permission: FAIL: validation error: syscall "__x64_security_file_permission" (or "__x64_security_file_permission") not found
RESULT: FAIL (1)
syscall: true tells Tetragon the function uses the system call ABI, so it adds the architecture prefix (__x64_ on x86-64, __arm64_ on Arm). The hooks page explains why: syscalls and kernel functions use different calling conventions, and Tetragon adapts the name for syscalls. security_file_permission is a regular kernel function, so the lookup fails. Set syscall: false.
The same class of mistake shows up with LSM hooks. Asked for the BPF LSM version, models often write the kernel's security_ function name:
lsmhooks:
- hook: "security_file_open"
[kernel] lsmhooks[0] security_file_open: FAIL: bpf_lsm_security_file_open not in BTF: not found
The hook field takes the LSM hook name without the prefix. The hooks page's own example uses hook: "file_open", which passed on our kernel. LSM hooks also need BPF LSM enabled on the host; the hooks page shows how to check with cat /sys/kernel/security/lsm.
Step 4: The warning that still loads
Set syscall: false, and the third draft looks done:
$ tpcheck draft3.yaml
== draft3.yaml
[schema] ok (credential-file-writes "credential-file-writes")
[selectors] kprobes[0] security_file_permission: ok
[kernel] kprobes[0] security_file_permission: WARN (agent logs this and still loads): validation warning: type (struct file *) of argument 0 does not match spec type (string)
RESULT: pass (offline checks only)
This is the most useful thing the lab caught. The first argument is a struct file *, and the draft declares it as string. Tetragon's kernel check notices, but it raises a warning, not an error. In the agent's code, a warning is logged and loading continues. So this policy would load cleanly, and BPF would read the start of a struct file as if it were a C string. It would almost certainly never equal /etc/shadow, and you'd see no events and no error.
The fix is type: "file", which tells Tetragon to resolve the file's path. If you automate the loop, treat these warnings as failures. If you load policies by hand, read the agent log after every load.
Step 5: The Tetragon tracing policy we'd run
apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
name: credential-file-writes
spec:
kprobes:
- call: "security_file_permission"
syscall: false
args:
- index: 0
type: "file" # struct file *: Tetragon resolves the path
- index: 1
type: "int" # mask: 0x2 MAY_WRITE, 0x4 MAY_READ
selectors:
- matchArgs:
- index: 0
operator: "Prefix"
values:
- "/etc/shadow"
- "/etc/gshadow"
- "/etc/sudoers"
- "/root/.ssh/"
- index: 1
operator: "Equal"
values:
- "2"
matchBinaries:
- operator: "NotIn"
values:
- "/usr/bin/passwd"
- "/usr/sbin/chpasswd"
- "/usr/sbin/usermod"
- "/usr/sbin/visudo"
matchActions:
- action: Post
$ tpcheck final.yaml
== final.yaml
[schema] ok (credential-file-writes "credential-file-writes")
[selectors] kprobes[0] security_file_permission: ok
[kernel] kprobes[0] security_file_permission: ok
RESULT: pass (offline checks only)
Why it's shaped this way:
- Inside one selector, filters are ANDed: path prefix, write mask and binary allowlist must all match. Values inside one filter are ORed. The selector semantics section spells this out.
Prefixon/etc/shadowmatches any path that starts with it, such as the/etc/shadow-backup./root/.ssh/coversauthorized_keysand anything else in that directory.Equal 2matches a mask of exactlyMAY_WRITE, as in Tetragon's own example. If you want any mask with the write bit set, use theMaskoperator.- The allowlist uses full paths. Check them on your distribution with
command -v passwd, because/usr/binand/usr/sbindiffer between distros. The selectors page also warns that for scripts with a shebang,matchBinariessees the interpreter, so allowlisting/usr/bin/python3would allow every Python script. security_file_permissionruns on every read and write call, not once per open. A busy legitimate writer outside the allowlist can produce a lot of events.Posttakes arateLimitparameter (for examplerateLimit: 5m) if that becomes a problem.
What it still misses: a tool that writes a new file and renames it over /etc/shadow (the write goes to another path, and the rename is a different hook), writes through mmap, and truncation. Tetragon's file monitoring example adds security_mmap_file and security_path_truncate for the last two. Treat those as separate hooks, not a longer selector.
Step 6: Test the policy on a lab host you own
Load it. On a disposable VM or a test cluster you control, follow the file access quick start. In Docker, mount the policy into /etc/tetragon/tetragon.tp.d/ when you start the privileged Tetragon container. In Kubernetes, kubectl apply -f the policy. Then watch events with tetra getevents -o compact. Check the agent log for validation warnings before you trust the result.
Plant the activity. On the lab host:
# should produce a write event: tee is not on the allowlist
echo "lab canary" | sudo tee /root/.ssh/tetragon-lab-canary
# should stay quiet: a read, not a write
sudo cat /etc/shadow > /dev/null
# should stay quiet: an allowlisted binary, on a throwaway lab user
echo 'labuser:Lab-Only-Passw0rd' | sudo chpasswd
The policy passes when the tee write shows up and the other two don't. Remove the canary file afterwards. We didn't run this step for this guide, so we don't show event output.
Moving from monitor to enforcement
Once the alert-only policy has run long enough to show you what writes those files, you can block. Tetragon has two ways to enforce, and the enforcement docs are clear about the difference: Override makes the function return an error instead of running, while Sigkill kills the process but doesn't guarantee the operation itself was stopped. For blocking a write, Override is the one you want. On an LSM hook it's supported with argError:
apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
name: credential-file-writes-enforce
spec:
options:
- name: "policy-mode"
value: "monitor"
lsmhooks:
- hook: "file_permission"
args:
- index: 0
type: "file"
- index: 1
type: "int"
selectors:
- matchArgs:
- index: 0
operator: "Prefix"
values:
- "/etc/shadow"
- "/etc/sudoers"
- index: 1
operator: "Equal"
values:
- "2"
matchBinaries:
- operator: "NotIn"
values:
- "/usr/bin/passwd"
- "/usr/sbin/chpasswd"
- "/usr/sbin/usermod"
- "/usr/sbin/visudo"
matchActions:
- action: Override
argError: -1
It passed all four checks. The policy-mode option is the safety catch: in monitor mode, the enforcement mode page says enforcement operations are elided, so the policy runs without blocking anything while you watch it. You can switch a loaded policy with tetra tp set-mode.
Here's a trap we hit while writing this. That page describes the modes in prose as "monitoring" and "enforcement", and a model reading it will happily write value: "monitoring". The schema accepts any string there:
$ tpcheck m_mode.yaml
== m_mode.yaml
[schema] ok (credential-file-writes-enforce "credential-file-writes-enforce")
[options] policy-mode: FAIL: invalid mode: "monitoring"
The parser only accepts monitor or enforce, which is what the page's YAML and CLI examples use. A schema-only check would have passed this policy.
More mistakes the harness caught
A few smaller drafts, one mistake each:
$ tpcheck m_index2.yaml m_argref.yaml m_six_selectors.yaml draft6_falco.yaml
== m_index2.yaml
[kernel] kprobes[0] security_file_permission: FAIL: kprobe arg 0 has an invalid index: 2 based on prototype: FuncProto
== m_argref.yaml
[selectors] kprobes[0] security_file_permission: FAIL: parseMatchArgs error: argFilter for unknown index
== m_six_selectors.yaml
[selectors] kprobes[0] security_file_permission: FAIL: no more than 5 selectors supported (6 provided)
== draft6_falco.yaml
[schema] FAIL: failed to unmarshal into typed object: error unmarshaling JSON: while decoding JSON: json: unknown field "condition"
(Lines trimmed to the failing check.) In order: an argument index the function doesn't have (security_file_permission has two arguments, indexes 0 and 1); a matchArgs filter on an argument the args list doesn't declare; six selectors when the limit is five, which is easy to hit when a model writes one selector per path; and Falco's condition, output and priority keys pasted into a kprobe.
One the harness missed: a kprobe with matchReturnArgs but no return: true. The selectors page says such a policy fails to load, but none of our four checks rejected it. That's a reminder that a clean offline run isn't a load test.
Automate the loop: draft, validate, test
The model drafts, the validator judges, and the exact output goes back. The drafting side calls RedRouter's OpenAI-compatible endpoint: base URL https://redrouter.org/v1 and a Bearer key, per the RedRouter quickstart. We didn't call a model or load a policy in the lab, so treat this as a sketch:
import os, subprocess, tempfile
from openai import OpenAI
client = OpenAI(base_url="https://redrouter.org/v1",
api_key=os.environ["REDROUTER_API_KEY"])
SYSTEM = ("You write Cilium Tetragon TracingPolicy YAML (apiVersion cilium.io/v1alpha1). "
"Use only the hooks, argument types, operators and actions given. matchArgs operators: "
"Equal, NotEqual, Prefix, Postfix, Mask. matchBinaries operators: In, NotIn, Prefix, "
"NotPrefix, Postfix, NotPostfix, with full paths. Actions: Post only. At most 5 selectors. "
"No Falco fields. Return one YAML document and nothing else.")
HOOK = ("kprobe security_file_permission, syscall: false. "
"args: index 0 struct file * (type file), index 1 int mask (0x2 MAY_WRITE).")
GOAL = ("Post an event when a binary other than /usr/bin/passwd, /usr/sbin/chpasswd, "
"/usr/sbin/usermod or /usr/sbin/visudo writes /etc/shadow, /etc/gshadow, "
"/etc/sudoers or anything under /root/.ssh/.")
def draft(feedback=""):
r = client.chat.completions.create(
model="glm-5.3-flash-red", temperature=0,
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"{HOOK}\n\nGoal: {GOAL}\n\n{feedback}"}])
return r.choices[0].message.content.strip().strip("`").removeprefix("yaml\n")
def check(policy):
with tempfile.NamedTemporaryFile("w", suffix=".yaml", delete=False) as f:
f.write(policy)
p = subprocess.run(["./tpcheck", f.name], capture_output=True, text=True)
return p.returncode, p.stdout
policy = draft()
for _ in range(4):
code, out = check(policy)
if code == 0 and "WARN" not in out:
break
policy = draft(f"Your policy:\n{policy}\n\nThe validator returned:\n{out}\nFix every FAIL and WARN.")
print(policy) # next: monitor-mode load on a lab host, planted writes, read the agent log
The stop condition treats warnings as failures, for the reason in Step 4. The loop ends at the validator on purpose. A lab load with planted activity is the real gate.
The core of our harness is short. These are Tetragon's own packages; the glue is ours:
tp, err := tracingpolicy.FromFile(path) // strict YAML + CRD OpenAPI schema
spec := tp.TpSpec()
kspec, _ := ciliumbtf.LoadKernelSpec() // this kernel's BTF
ks, _ := ksyms.KernelSymbols() // kernel symbols; needs root to read addresses
for i := range spec.KProbes {
kp := &spec.KProbes[i]
_, err = selectors.InitKernelSelectors(kp.Selectors, kp.Args, kp.Data, idtable.New())
call := kp.Call
if kp.Syscall {
call, _ = arch.AddSyscallPrefix(call)
}
err = btf.ValidateKprobeSpec(kspec, call, kp, ks) // ValidationWarnError = logged, still loads
}
for i := range spec.LsmHooks {
var fn *ciliumbtf.Func
err = kspec.TypeByName("bpf_lsm_"+spec.LsmHooks[i].Hook, &fn)
}
Build it inside a checkout of the Tetragon tag you run, with go build -mod=vendor.
What to send the model
Runtime policies are written from what you know about your hosts, so be deliberate about prompts.
- Send the hook, argument types, allowed operators and the goal. That's usually enough to draft a policy.
- Send the validator's or agent's exact output back, not a paraphrase.
- Use generic paths and placeholder names in examples. Don't paste your real hostnames, internal service names or a full inventory of which binaries run where.
On RedRouter, Zero Data Retention is an opt-in setting and off by default. The data handling docs explain what's stored and how to turn it on, and what RedRouter keeps is the short version. Our security page covers how we handle security workloads.
Which model to use for Tetragon policies
For drafting Tetragon policies, we'd start with GLM 5.3 Flash Red (glm-5.3-flash-red). On docs.redrouter.org/models it lists at $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens. A draft-and-fix round like the ones above is a few thousand tokens. For policy work inside a broader authorized red-team or purple-team engagement, red-cyber-1 (Beta) lists at $0.28 / $0.13 / $1.10 per 1M. Plans are on /pricing.
Common LLM mistakes in Tetragon tracing policies
| Mistake in the draft | What caught it | Fix |
|---|---|---|
operator: Contains in matchArgs | CRD schema enum | Prefix, Postfix or Equal |
NotEqual in matchBinaries | CRD schema enum | NotIn |
action: Alert | CRD schema enum | Post (the default) |
syscall: true on a kernel function | Kernel check: __x64_ name not found | syscall: false |
hook: security_file_open | Kernel check: bpf_lsm_security_file_open not in BTF | hook: file_open |
type: string for a struct file * | Kernel check warning only; the agent still loads it | type: file |
| Argument index 2 on a 2-argument function | Kernel check: invalid index | Read the function signature |
matchArgs on an undeclared argument | Selector encoding: unknown index | Declare it under args |
| Six selectors | Selector encoding: max 5 | Merge paths into one filter |
Falco condition/output keys | Strict YAML: unknown field | Use selectors |
policy-mode: monitoring | Option parser, not the schema | monitor or enforce |
Bare binary names (passwd) | Nothing; silently never matches | Full paths |
matchReturnArgs without return: true | Nothing offline; fails at load per the docs | Add return: true and returnArg |
Validation checklist
apiVersion: cilium.io/v1alpha1andkind: TracingPolicy(orTracingPolicyNamespaced).- Every operator and action is in the CRD of the Tetragon version you run.
- The hook exists on your kernel:
syscallis set correctly for kprobes, and LSM hook names have nosecurity_prefix. - Every argument index exists, and every type matches the kernel signature. Warnings count as failures.
- Every
matchArgsindex is declared underargs, and there are no more than five selectors. matchBinariesuses full paths you checked on the host.- Enforcement policies start with
policy-mode: monitor. - It loads on a lab host without warnings in the agent log.
- It fires on your planted write and stays quiet on the allowed ones.
FAQ
Can an LLM write Tetragon tracing policies that work the first time?
Sometimes, but plan on checking. In this guide, the first draft had six problems. The schema caught three, the kernel check caught one, and one more, the wrong argument type, was only a warning that the agent would have loaded anyway. The sixth, bare binary names, nothing caught. Use the model as a fast drafter and the schema, the kernel check and a lab load as the judges.
How do I validate a Tetragon policy without a cluster?
Partly. Tetragon's Go packages let you run the CRD schema check, selector encoding and the BTF check against a kernel's BTF without loading anything, which is what we did. None of that proves the policy loads or fires. For that you need a Tetragon agent on a host you control and planted activity. If you do have a cluster with the CRDs installed, kubectl apply --dry-run=server runs the schema part on the API server.
Should I use kprobes or LSM hooks?
Kprobes on security_ functions work on more kernels and are what Tetragon's own file monitoring examples use. LSM hooks need BPF LSM enabled, but they're built for access decisions, and Override on them is the cleanest way to block an operation. A common path is to alert with a kprobe first, then enforce with an LSM hook in monitor mode.
How is a Tetragon policy different from a Falco rule?
A Falco rule is a condition evaluated over events Falco collects. A Tetragon TracingPolicy chooses the kernel hook and filters in eBPF, and it can enforce with Override or Sigkill. Falco syntax pasted into a TracingPolicy fails strict parsing, as the condition example above shows.
What should I not paste into the prompt?
Real hostnames, internal service names and a map of which binaries run on which hosts. The model needs the hook, the argument types, the allowed operators and the goal, and placeholders work for everything else.
Related guides
Only load tracing policies on hosts and clusters you own or are authorized to change, and plant test activity only on lab systems you're allowed to test.