k3sec on Kubernetes
Run k3sec on every node of a cluster from the official DaemonSet: what it is allowed to do, how to configure it, how to write and test detection rules, and how to upgrade it.
k3sec only sees the containers that have a process on the node it runs on, so a cluster needs one k3sec per node. The project ships this as a plain Kubernetes manifest, deploy/kubernetes/k3sec.yaml: a DaemonSet with its namespace, service account, read-only RBAC and policy ConfigMap. There is no Helm chart.
This page covers the manifest as an engineer deploying and maintaining it. The workspace side (cluster codes, the Cluster tab) is in Cluster security.
How a node pod works
The image ghcr.io/mlab-sh/k3sec holds k3sec, mlab-agent and the default YARA rules. Its entrypoint (/usr/bin/k3sec-node) does three things:
- If a code file exists (
/etc/mlab-enroll/code, from thek3sec-enrollSecret), it runsmlab-agent enroll --if-unenrolled --code-file … --label $NODE_NAME, with--expect-fingerprint $MLAB_FINGERPRINTwhen that variable is set. A node that is already enrolled skips this. - It writes the agent policy from the ConfigMap template (
/etc/k3sec/policy.toml), replacing@K3SEC_SHA256@with the hash of the k3sec binary in the image and@NODE_NAME@with the node's name. - It runs
mlab-agent run, which startsk3sec serveas its tool.
| Entrypoint variable | Default | Meaning |
|---|---|---|
MLAB_SERVER | https://mlab.sh | The mlab.sh instance to enrol with |
MLAB_FINGERPRINT | unset | mlab.sh's key fingerprint. Set it: a node then refuses to enrol against a key that does not match |
NODE_NAME | from spec.nodeName | Label of the agent, and the node whose pods k3sec watches |
MLAB_AGENT_CONFIG_DIR | /var/lib/mlab-agent | Keys, enrolment and k3sec's work directory (a hostPath, mode 0700) |
K3SEC_POLICY_TEMPLATE | /etc/k3sec/policy.toml | The policy template (the ConfigMap) |
MLAB_ENROLL_CODE_FILE | /etc/mlab-enroll/code | The enrolment code (the Secret, mounted optional: true) |
Deploy
Create the namespace and the enrolment Secret with a cluster code (one code for up to the number of nodes it was made for, valid for 24 hours):
kubectl create namespace k3sec
kubectl -n k3sec create secret generic k3sec-enroll --from-literal=code=<cluster code>Download the manifest and pin it:
curl -fsSLO https://raw.githubusercontent.com/mlab-sh/k3sec/main/deploy/kubernetes/k3sec.yamlSet MLAB_FINGERPRINT in the DaemonSet, upload_hosts in the k3sec-policy ConfigMap (the upload host the Policy editor shows), and keep the image tag explicit (ghcr.io/mlab-sh/k3sec:1.8.0 in the current manifest). Commit the edited file to your GitOps repository rather than applying main directly.
Apply and watch the rollout:
kubectl apply -f k3sec.yaml
kubectl -n k3sec rollout status ds/k3sec
kubectl -n k3sec get pods -o wide
kubectl -n k3sec logs ds/k3sec # the agent's log and k3sec's stderrDelete the Secret once every node shows in the workspace's Agents tab. Restarted pods reuse the keys in /var/lib/mlab-agent on the node and never enrol again.
kubectl -n k3sec delete secret k3sec-enrollScheduling
The DaemonSet tolerates every taint (operator: Exists), so it also runs on control-plane nodes. A node affinity keeps it off serverless nodes, where a pod would stay pending: eks.amazonaws.com/compute-type not fargate, and type not virtual-kubelet. Requests are cpu: 50m, memory: 128Mi and the memory limit is 512Mi. Tune these in your copy of the manifest for busy nodes.
Privileges
Everything below comes from the manifest. Nothing in it runs in privileged mode.
| Area | What the pod gets | Why |
|---|---|---|
| User | runAsUser: 0, allowPrivilegeEscalation: false, readOnlyRootFilesystem: true | Reads other containers' files through /proc/<pid>/root |
| Capabilities | drop: ["ALL"], then BPF, PERFMON, SYS_RESOURCE, SYS_PTRACE, DAC_READ_SEARCH, NET_ADMIN | eBPF programs and maps, tracepoints and kprobes, locked memory for BPF maps on older kernels, other processes' /proc/<pid>/root, maps and exe, files of any owner inside containers, and the DNS / UDP egress program on the root cgroup |
| Host | hostPID: true | The node's process IDs: container processes, their roots and memory maps |
| Volumes | hostPath /var/lib/mlab-agent (DirectoryOrCreate), hostPath /sys/kernel/tracing (read-only), the policy ConfigMap (read-only), the enrolment Secret (read-only, optional), an emptyDir on /tmp | Node identity, tracefs for the probe, configuration |
| Pod Security | Namespace labelled pod-security.kubernetes.io/enforce: privileged (and warn) | hostPID, hostPath and BPF capabilities are refused where Pod Security enforces baseline (Talos, RKE2, some managed clusters) |
RBAC (ClusterRole k3sec) | events: list, watch. pods: get, list, watch. pods/log: get. nodes: get, list. namespaces: get, only kube-system | Read-only. The UID of kube-system is the cluster id |
| Network | The agent to mlab.sh (outbound HTTPS) and to the upload host, k3sec to the Kubernetes API | No listening port |
Node requirements: Linux 5.8 or later for the eBPF probe (the BPF ring buffer), and tracefs mounted at /sys/kernel/tracing. Without tracefs, the node reports its eBPF source as failed and keeps the other sources running.
Configure
The k3sec-policy ConfigMap is the agent's local policy on every node: the ceiling of what the workspace may turn on. The full list of keys is in k3sec › Settings. The manifest ships:
enabled = true
upload_hosts = ["<account>.eu.r2.cloudflarestorage.com"]
[tools.k3sec]
path = "/usr/bin/k3sec"
sha256 = "@K3SEC_SHA256@"
enabled = true
allowed_ops = ["status", "configure", "events_since", "inventory", "sbom"]
[tools.k3sec.settings]
node = "@NODE_NAME@"
allow_k8s_events = true
allow_logs = false
allow_ebpf = true
allow_rules = true
allow_vulns = true
namespaces = []
rulesets = ["/usr/share/k3sec/rules"]
allow_remote_rules = falseAfter editing the ConfigMap, restart the pods so each entrypoint writes the new policy:
kubectl -n k3sec rollout restart ds/k3secAdding detection rules and the audit log
detect and audit_log are paths inside the pod, and only the node policy can set them: the workspace cannot turn them on. Mount what they point to. The patch below is an example in plain Kubernetes; k3sec-detect is a ConfigMap you create from your rule files:
kubectl -n k3sec create configmap k3sec-detect --from-file=detect/# In the DaemonSet's pod spec
volumes:
- name: detect
configMap: { name: k3sec-detect }
- name: audit
hostPath: { path: /var/log/k3s-audit.log, type: File } # control-plane nodes only
containers:
- name: k3sec
volumeMounts:
- { name: detect, mountPath: /etc/k3sec-detect, readOnly: true }
- { name: audit, mountPath: /var/log/k3s-audit.log, readOnly: true }# In the k3sec-policy ConfigMap, [tools.k3sec.settings]
detect = "/etc/k3sec-detect"
audit_log = "/var/log/k3s-audit.log"Don't mount the rules under /etc/k3sec: the policy ConfigMap is already mounted there. Detection rules that fail to load stop k3sec from starting, so test them first (below). The audit log only exists where the API server writes one (audit-log-path, plus a policy at Request level for pods, workloads and RBAC). With type: File, a pod on a node without that file stays pending, so put the audit mount in a second DaemonSet scheduled only on control-plane nodes.
Without a workspace
The same image can stream k3sec's events to your own log pipeline with no mlab.sh enrolment. The project's deployment notes describe it as a privileged pod (hostPID, privileged: true) with the same RBAC, running watch --vulns -o json and writing NDJSON to stdout. --ebpf --rules /usr/share/k3sec/rules adds kernel events and YARA detections.
The image's entrypoint always starts the agent, so override command to run k3sec directly:
containers:
- name: k3sec
image: ghcr.io/mlab-sh/k3sec:1.8.0
command: ["/usr/bin/k3sec"]
args: ["watch", "--ebpf", "--rules", "/usr/share/k3sec/rules", "--vulns", "-o", "json"]
env:
- name: NODE_NAME
valueFrom: { fieldRef: { fieldPath: spec.nodeName } }
securityContext:
privileged: trueStandalone, --vulns calls https://vuln.mlab.sh (--mlab-url for an on-prem instance; set MLAB_API_KEY for higher API limits). In a workspace, matching happens in mlab.sh and k3sec reaches nothing but the Kubernetes API.
Write and test detection rules
A rule file is JSON: {"rules": [...]}, each rule with a name, a CEL condition in when, and either a severity and mitre ids or "drop": true. A matching rule raises the severity (it never lowers it), adds its MITRE ids to mitre and its name to rule and to the front of the message. A matching drop rule removes the event. --detect takes one file or a directory of *.json files.
{"rules": [
{"name": "shell-reads-token",
"when": "kind == 'secret_read' && meta.comm in ['cat', 'sh'] && payload.path.contains('serviceaccount')",
"severity": "critical", "mitre": ["T1059.004"]},
{"name": "shell-under-nginx",
"when": "kind == 'exec' && meta.ancestry.contains('nginx') && meta.comm in ['sh', 'bash']",
"severity": "critical", "mitre": ["T1059.004"]},
{"name": "quiet-dns", "when": "kind == 'dns' && namespace == 'kube-system'", "drop": true}
]}A condition sees:
| Variable | Content |
|---|---|
source | ebpf, yara, vuln, k8s-event, k8s-log |
kind | exec, connect, file_write, secret_read, dns, detection, vulnerability, … or the Kubernetes event reason |
severity | info < normal < warning < error < critical |
namespace, object, message | As in the event |
meta | The event's metadata, a map of strings (comm, pid, uid, pod, container, ancestry, …) |
payload | The raw source object (path for exec and file writes, dest for connects, …) |
A condition on a key the event does not have is false, not an error. Field details per source: SecEvent schema.
Test loop
Check that the rules load. Rule files and YARA rules are compiled before k3sec connects to the cluster, and a broken file stops it with exit code 1 and the compiler's message. A file that loads logs detection rules loaded with the rule count.
Run them on a test node, as root, scoped to the node and to what matters:
sudo NODE_NAME=$(hostname) k3sec watch --ebpf --detect ./detect/ \
--min-severity warning -o json --kubeconfig /etc/rancher/k3s/k3s.yaml--min-severity filters after --detect, so an info exec raised to critical by a rule is shown.
Trigger the behaviour from a test pod, and look for rule in the event:
kubectl -n demo exec deploy/nginx -- sh -c 'cat /var/run/secrets/kubernetes.io/serviceaccount/token >/dev/null'On the project's lab, this token read went from warning to critical, with rule=shell-reads-token and mitre=T1528,T1059.004.
Edit while it runs. Rule files are checked every 2 seconds while events flow, and reloaded when one is added, removed or modified. A broken edit is logged (detection rules not reloaded, the previous ones stay) and the rules in force stay.
Filter the stream with jq while you work:
sudo k3sec watch --ebpf --detect ./detect/ -o json | jq -c 'select(.metadata.rule != null)'Testing the YARA pipeline
The default rules include k3sec_test_marker, which matches the string K3SEC_YARA_TEST. Writing it to a watched path in a pod proves the scan path end to end (a file_write under /etc/, /usr/bin/, /root/ or /var/run/secrets is scanned):
sudo k3sec watch --ebpf --rules /usr/share/k3sec/rules -o json | jq -c 'select(.source=="yara")' &
kubectl -n demo exec deploy/nginx -- sh -c 'echo K3SEC_YARA_TEST > /etc/k3sec-test'A match is a source: "yara", kind: "detection" event, always critical. --rules without --ebpf does nothing (it warns), because scanning is driven by eBPF events. In a workspace, the rule sets the workspace may pick from are the rulesets of the node policy.
Upgrade
kubectl -n k3sec set image ds/k3sec k3sec=ghcr.io/mlab-sh/k3sec:<version>
kubectl -n k3sec rollout status ds/k3secThere is no hash to update by hand: each pod pins the SHA-256 of the k3sec binary in its own image when it starts, and nodes keep their keys. Read the changelog before upgrading, and compare your copy of the manifest with the new release's deploy/kubernetes/k3sec.yaml: new RBAC rules, capabilities or mounts ship there, not in the image.
To remove k3sec from a cluster, delete what the manifest created (kubectl delete -f k3sec.yaml), then remove /var/lib/mlab-agent from each node to discard its keys.
Troubleshooting
See Cluster security › Troubleshooting for enrolment loops, missing inventories, and sources that stay off.
Deploy mlab-agent on a fleet
Install, enrol and run mlab-agent on many Linux hosts without a person at each one: unattended enrolment, the systemd service, an Ansible playbook, policy distribution, upgrades and removal.
In CI pipelines
Run the mlab CLI, postmortem and assay in GitHub Actions, GitLab CI and Jenkins: exit codes per tool, failing a build on a threshold, caching and secrets.