Audit trails and compliance reporting are called out explicitly in the exam blueprint, yet almost nobody practices them because home labs rarely turn on API audit logging. This lab turns it on right when the cluster is built, so you can query real events.
make up cicdmake secOrientation
Three artifacts, three concrete questions. The audit log answers "who did what to what, and did it work?". SBOMs answer "what's actually inside the thing we shipped?". Compliance reports answer "which controls are we failing right now?". Being able to produce and query all three on demand is the competency.
API server audit logs
Here's how the pipeline works: a policy file tells kube-apiserver what to record and at what detail level, and a backend (a log file on the control-plane node here, or a webhook to a SIEM in production) writes one JSON event per stage of every matching request.
| Level | Records | Use for |
|---|---|---|
| None | Nothing | High-volume noise: leases, events, health endpoints |
| Metadata | Who, what, when, verb, and response code | The sensible catch-all (and Secrets, so values stay out of logs) |
| Request | Metadata + the request body | Writes where you want the input without redundant response bloat |
| RequestResponse | Metadata + both request and response bodies | High-value changes only (RBAC, policy); output grows fast |
Stages mark where in the request lifecycle the event fires: RequestReceived, ResponseStarted (for long-running streams like watches), ResponseComplete, and Panic. Almost all analysis filters on ResponseComplete. Policy rules match top to bottom, first hit wins (just like Alertmanager routes), so a well-structured policy always reads in three bands: drop noise first, elevate sensitive kinds next, and catch everything else at Metadata. Open kind/audit-policy.yaml in this repo and you'll see that exact layout.
Fields that answer real questions
| Field | Answers |
|---|---|
| user.username, user.groups | Who called (a person, or system:serviceaccount:ns:name) |
| verb, objectRef.{resource,namespace,name} | What they did, and to which object |
| responseStatus.code | Whether it worked (403 = denied, 201 = created) |
| sourceIPs, userAgent | Where the call came from and which client sent it |
| annotations["authorization.k8s.io/decision"] | Whether RBAC said allow or forbid (with the matching rule in …/reason) |
| annotations["pod-security.kubernetes.io/audit-violations"] | PSS violations from section 5.3, logged quietly without blocking |
| stageTimestamp, auditID | When it happened, and how to tie multiple stages of one request together |
The API server starts with --audit-policy-file pointing at a mounted file. If that file is missing or malformed, the API server refuses to start at all. An audit config typo therefore looks like a completely dead cluster, making it one of the nastiest control-plane failure modes in this curriculum.
Audit logging only sees Kubernetes API requests. It won't see a shell spawned inside a container, lateral network traffic between pods, or anything bypassing the API server. Pair it with Falco-style runtime detection, network flow logs (Hubble), and image scanning to cover the other layers, and say so explicitly whenever a scenario asks for a "complete audit trail".
Audit policy and backends, field by field
Rule fields
An audit Policy (audit.k8s.io/v1) consists of rules[] plus an optional top-level omitStages. Each rule sets a level and filters by any mix of users, userGroups, verbs, resources[] (each taking group, resources like pods or pods/exec, and optional resourceNames), namespaces, and nonResourceURLs (/healthz*, /metrics, /version), along with per-rule omitStages and omitManagedFields. Because Kubernetes evaluates rules top to bottom and stops on the first match, order them cleanly: drop noise, protect sensitive bodies, raise RBAC/policy diffs, then catch everything else.
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: [RequestReceived] # one event per request, not two
rules:
- level: None # noise first
users: ["system:kube-proxy"]
verbs: ["watch"]
resources: [{ group: "", resources: ["endpoints", "services", "endpointslices"] }]
- level: None
nonResourceURLs: ["/healthz*", "/readyz*", "/livez*", "/metrics", "/version"]
- level: None
resources: [{ group: "coordination.k8s.io", resources: ["leases"] }]
- level: Metadata # never the body: it holds the values
resources: [{ group: "", resources: ["secrets", "configmaps"] },
{ group: "authentication.k8s.io", resources: ["tokenreviews"] }]
- level: Metadata
resources: [{ group: "", resources: ["pods/exec", "pods/attach", "pods/portforward"] }]
- level: RequestResponse # who changed access and policy, with the diff
resources: [{ group: "rbac.authorization.k8s.io" },
{ group: "kyverno.io" }, { group: "policies.kyverno.io" },
{ group: "constraints.gatekeeper.sh" }, { group: "admissionregistration.k8s.io" }]
- level: Metadata # everything else
omitStages: [RequestReceived]- Why those levels. Setting
RequestorRequestResponseon Secrets dumps plaintext credentials straight into your log files; keeping them atMetadatastill tells you who accessed which Secret and whether they succeeded. Loggingpods/execatMetadataanswers "who shelled into production?". Putting RBAC and policy kinds atRequestResponsecaptures the full diff for permissions changes, whileRequestfits busy writes (like Deployment updates) where the response body adds noise. - Stages.
RequestReceivedfires before authorization, so it catches requests before they're rejected; most policies omit it and inspectResponseCompleteinstead, since that event already includesresponseStatus.code.ResponseStartedonly applies to streaming requests (watch, exec, port-forward), andPanicis rare. All events from a single request share the sameauditID. - Extra fields you'll grep for:
level,stage,requestURI,impersonatedUser(populated whenever--aswas used, whileuserrecords the real caller),requestObject/responseObjectat higher levels, andrequestReceivedTimestamp. AddingomitManagedFields: truestrips the verbosemanagedFieldsnoise from both bodies.
Backends and their flags
| Flag | Backend | Means |
|---|---|---|
| --audit-policy-file | Both | Path to the Policy YAML above; omit it and nothing is logged, get the path wrong and the API server won't start |
| --audit-log-path | Log | JSON-lines output file (or - for stdout); this flag activates the log backend |
| --audit-log-maxage / -maxbackup / -maxsize | Log | Log rotation: retention days, max backup files, and max MB per file |
| --audit-log-format | Log | json (default) or legacy |
| --audit-log-mode | Log | blocking (default), blocking-strict (a write failure at RequestReceived fails the API call itself), or batch |
| --audit-webhook-config-file | Webhook | A kubeconfig pointing at the remote sink (a SIEM, Falco's k8saudit plugin, or a Fluent Bit input) |
| --audit-webhook-mode | Webhook | batch (default), blocking, or blocking-strict |
| --audit-webhook-batch-buffer-size / -max-size / -max-wait | Webhook | Defaults: 10000 buffered events, 400 per batch, 30s max wait; overflowing the buffer drops events |
| --audit-webhook-initial-backoff | Webhook | Wait time before the first retry after a failed delivery (exponential backoff afterward) |
On static-pod control planes (kubeadm, kind), remember to mount both the policy file and the log directory as hostPath volumes on kube-apiserver; forgetting a mount triggers the dead-cluster failure above. On managed Kubernetes, you don't touch these flags at all: you consume the cloud provider's audit stream, so exam questions there pivot to "what do you query for?".
Annotations other controls leave in the audit event
authorization.k8s.io/decisionandauthorization.k8s.io/reason: RBAC's verdict and the exact rule that matched.pod-security.kubernetes.io/audit-violations: findings recorded by a namespace's PSSauditlabel, per pod.validation.policy.admission.k8s.io/validation_failure: failures from aValidatingAdmissionPolicyBindingwithvalidationActions: [Audit], alongside any custom keys from the policy'sauditAnnotations.mutation.webhook.admission.k8s.io/round_0_index_Nandpatch.webhook.admission.k8s.io/...: which mutating webhooks modified the object and what they patched (recorded at levelRequestor higher).
Expect two task styles. Writing or fixing a policy: "log who reads Secrets without recording their values, and drop health checks" maps to a Metadata rule on secrets plus a None rule on nonResourceURLs, both placed above the catch-all. Querying the log: "which ServiceAccount deleted the Deployment?" becomes a jq filter over verb, objectRef.resource, objectRef.name, and user.username. Both get verified on real output, so always run the query after making your edit.
Supply-chain paper trail: Trivy Operator
The Trivy Operator rescans running workloads continuously and stores every finding as a Kubernetes CR. That's the core platform-engineering move: turning compliance from PDF attachments into queryable API objects so kubectl, RBAC, GitOps, and Grafana dashboards all work on compliance data out of the box.
| Kind | Holds |
|---|---|
| vulnerabilityreports | CVEs per workload image, including severity totals and fixed versions |
| sbomreports | CycloneDX component inventory per image |
| configauditreports | Security misconfigurations in the workload spec itself |
| exposedsecretreports | Hard-coded credentials found inside image layers |
| rbacassessmentreports | Overly permissive or risky RBAC rules |
| clusterinfraassessmentreports | Per-node control-plane and kubelet checks |
| clustercompliancereports | CIS, NSA, and PSS rollups aggregated from the reports above |
make validate asserts minimum counts for these reports, so a fresh cicd layer gives you live data to practice real queries against.
SBOM vocabulary, because the words get tested
- CycloneDX and SPDX are the two standard formats. Trivy outputs both, so picking one is a tooling compatibility question rather than a quality debate.
- An SBOM lists components and versions; it isn't a vulnerability report on its own. You join it against a CVE feed, which is why an SBOM generated at build time stays valuable long after new CVEs drop.
- The one-sentence pitch: when the next log4shell hits, you query your SBOMs for the affected package in seconds instead of rescanning the entire fleet.
- Its neighbors: provenance/attestations (how the artifact was built; see section 5.6) and signatures (who vouches for these bytes). Three distinct documents forming one trust story.
Runtime detection, SBOM tooling, and compliance evidence
Falco fills the gap the API audit leaves
The API server never sees a shell spawned inside a container, a file modified under /etc, or an unexpected outbound socket. Falco does. Its kernel driver (modern eBPF by default) watches syscalls, and its k8saudit plugin can ingest the API audit webhook stream too, letting one tool cover both runtime and control-plane events.
Every Falco rule defines rule, desc, condition (filtering fields like proc.name, container.image.repository, k8s.ns.name, and fd.sip), output (a format string), priority (EMERGENCY down to DEBUG), and tags, with macro and list blocks factoring out repeated logic. Rules ship in maturity tiers (stable bundled by default; incubating and sandbox opt-in) and should be tuned via override files rather than editing defaults. Alerts stream to stdout, files, gRPC, or HTTP, and Falcosidekick routes them to Slack, Loki, or Alertmanager. Keep the boundary clean: "alert on a shell in production or writes under /etc" is Falco; "who created that pod?" is the API audit log.
SBOM and scanner tooling, one line each
- Formats. SPDX (ISO/IEC 5962, tag-value or JSON) and CycloneDX (OWASP, JSON or XML) both capture components, versions, licenses, and hashes: run
trivy image --format cyclonedx|spdx-jsonorsyft <image> -o cyclonedx-json. Any SBOM feeds straight back into a vulnerability scanner (trivy sbom sbom.json,grype sbom:sbom.json), which is why build-time SBOMs can be rescanned later without pulling the image again. - Attaching it to the image.
cosign attest --predicate sbom.json --type cyclonedx <image@digest>stores the SBOM as a signed in-toto attestation right beside the image, ready for admission policies to verify (5.6). - VEX (Vulnerability Exploitability eXchange, in OpenVEX or CSAF) records a vendor's or platform team's statement that a CVE doesn't actually affect a shipped product. Passing
trivy --vex <file>or--vex reposuppresses those findings with a written justification, giving you an auditable alternative to an ever-growing ignore file.
The Trivy Operator's report kinds
| Kind (aquasecurity.github.io/v1alpha1) | Scope | Holds |
|---|---|---|
| VulnerabilityReport | Namespaced, one per workload container; named <kind>-<name>-<container> and owned by the ReplicaSet/controller so it garbage-collects automatically | report.summary.criticalCount|highCount|... and report.vulnerabilities[] (vulnerabilityID, installedVersion, fixedVersion, severity, primaryLink) |
| SbomReport / ClusterSbomReport | Per container | A CycloneDX BOM under report.components |
| ConfigAuditReport / ClusterConfigAuditReport | Per workload / per cluster object | Misconfiguration checks (AVD-KSV-* IDs): privileged pods, missing limits, root users |
| ExposedSecretReport | Per container | Credentials detected inside image layers |
| RbacAssessmentReport / ClusterRbacAssessmentReport | Per Role / ClusterRole | Risky RBAC rules (wildcards, secrets reads, escalate) |
| InfraAssessmentReport / ClusterInfraAssessmentReport | Per node component | Kubelet, API server, and etcd checks (the same ground as kube-bench) |
| ClusterComplianceReport | Cluster-scoped | spec.compliance.id in k8s-cis-1.23, k8s-nsa-1.0, k8s-pss-baseline-0.1, k8s-pss-restricted-0.1; spec.cron and spec.reportType: summary|all; status.summary.passCount/failCount plus per-control results mapped to the check IDs above |
Every report carries trivy-operator.resource.kind, trivy-operator.resource.name, and trivy-operator.container.name labels, so -l trivy-operator.resource.name=payments filters cleanly without string-parsing report names. Because scans run as short-lived Kubernetes Jobs (in the operator's namespace or the workload's, per OPERATOR_SCAN_JOB_...), a strict NetworkPolicy or missing registry pull secret can silently block reports from ever showing up: a scan job is just a pod. Rescans trigger on a TTL (OPERATOR_VULNERABILITY_SCANNER_REPORT_TTL) and whenever an image digest changes.
Benchmarks and attestations
- CIS Kubernetes Benchmark audits control-plane and node hardening (API server flags, kubelet settings, file permissions) and versions independently of Kubernetes. kube-bench runs it as a Job against specific targets (
master,node,etcd,policies) and prints PASS/FAIL/WARN with control IDs (like1.2.xfor the API server). Use--benchmarkto pin a CIS version or pick managed-cluster profiles (eks, gke, aks). The Trivy Operator'sk8s-ciscompliance report covers the same controls as native CRDs. - in-toto attestation is the standard wrapper everything shares: a DSSE envelope (
payloadType: application/vnd.in-toto+jsonplus signatures) enclosing a Statement (_type: https://in-toto.io/Statement/v1,subject[]with name anddigest.sha256,predicateType, andpredicate). SLSA provenance, SBOMs, scan results, and VEX are all just predicate types inside that envelope. Whenever a task says "attestation", picture one of these signed envelopes attached to an image digest. - An end-to-end evidence pipeline: the build produces the image and SBOM; the scan gates on severity and emits a scan attestation; cosign signs the digest; SBOM and provenance attestations live in the registry next to the image; admission enforces signatures and attestations; and the Trivy Operator continuously rescans running workloads while compliance reports roll everything up. Every hop leaves a queryable artifact, which is what "generating audit trails" means for a software supply chain.
A ClusterComplianceReport is only as fresh as its spec.cron schedule and the underlying reports. After fixing a cluster issue, the rollup still shows yesterday's numbers until the next scheduled run. Always check status.updateTimestamp before quoting a pass count, and remember exam graders often verify the refreshed report rather than just your underlying fix.
Exercises
The audit log sits on the control-plane node, reachable straight through Docker:
docker exec cnpe-control-plane tail -1 /var/log/kubernetes/audit.log | jq .outputcaptured 2026-08-26
$ docker exec cnpe-control-plane tail -1 /var/log/kubernetes/audit.log | jq .
{
"kind": "Event",
"apiVersion": "audit.k8s.io/v1",
"level": "Metadata",
"auditID": "90a334b1-0a03-420e-a1bc-96d14fb79e67",
"stage": "ResponseComplete",
"requestURI": "/apis/wgpolicyk8s.io/v1alpha2/namespaces/spire/policyreports/6c7a1017-58fc-422a-8ba5-eed66dba4c27",
"verb": "get",
"user": {
"username": "system:serviceaccount:kyverno:kyverno-reports-controller",
"uid": "94675045-58e9-4c7d-a50a-0745ac4b4687",
"groups": [
"system:serviceaccounts",
"system:serviceaccounts:kyverno",
"system:authenticated"
],
"extra": {
"authentication.kubernetes.io/credential-id": [
"JTI=48fd7eed-ebbd-47c4-b311-ef850241a1ec"
],
"authentication.kubernetes.io/node-name": [
"cnpe-worker2"
],
"authentication.kubernetes.io/node-uid": [
"3e493a08-e750-4c41-b117-9792d6b3d3e2"
],
"authentication.kubernetes.io/pod-name": [
"kyverno-reports-controller-7447456448-trwwg"
],
"authentication.kubernetes.io/pod-uid": [
"c2953876-66ee-4bd1-9d50-2ec02831230b"
]
}
},
"sourceIPs": [
"172.18.0.2"
],
"userAgent": "reports-controller/v0.0.0 (linux/amd64) kubernetes/$Format",
"objectRef": {
"resource": "policyreports",
"namespace": "spire",
"name": "6c7a1017-58fc-422a-8ba5-eed66dba4c27",
"apiGroup": "wgpolicyk8s.io",
"apiVersion": "v1alpha2"
},
"responseStatus": {
"metadata": {},
"code": 200
},
"requestReceivedTimestamp": "2026-08-27T02:44:31.144541Z",
"stageTimestamp": "2026-08-27T02:44:31.157282Z",
"annotations": {
"authorization.k8s.io/decision": "allow",
"authorization.k8s.io/reason": "RBAC: allowed by ClusterRoleBinding \"kyverno:reports-controller\" of ClusterRole \"kyverno:reports-controller\" to ServiceAccount \"kyverno-reports-controller/kyverno\""
}
}Now answer three classic auditor questions, one jq pipeline each: who read a Secret today (select(.objectRef.resource=="secrets" and .verb=="get"), printing user and name), every delete that succeeded (select(.verb=="delete" and .responseStatus.code<300)), and all denied requests (select(.annotations["authorization.k8s.io/decision"]=="forbid")). Then close the loop: run something unmistakable (like kubectl -n team-a delete pod bare --ignore-not-found, or a kubectl auth can-i as dev-a from 5.1) and spot your own fingerprints in the log within seconds.
After running through 5.3, grep the audit log for pod-security.kubernetes.io inside annotations.
audit: restricted label. That single log line ties sections 5.2, 5.3, and 5.4 together, mirroring how real compliance programs operate.Skip "do reports exist?" and ask a real triage question:
kubectl get vulnerabilityreports -A -o json | jq -r '
.items[] | [.metadata.namespace, .metadata.name,
(.report.summary.criticalCount|tostring), (.report.summary.highCount|tostring)] | @tsv' | sort -t$'\t' -k3 -rn | headoutputcaptured 2026-08-26
$ kubectl get vulnerabilityreports -A -o json | jq -r '
.items[] | [.metadata.namespace, .metadata.name,
(.report.summary.criticalCount|tostring), (.report.summary.highCount|tostring)] | @tsv' | sort -t$'\t' -k3 -rn | head
default pod-build-and-scan-skfx6-build-pod-step-build-and-push 25 233
default pod-build-and-scan-skfx6-clone-pod-step-clone 19 113
tekton-pipelines-resolvers replicaset-79d56b68cd 6 24
default replicaset-example-7c5474d4c8-prometheus-example-app 4 37
default pod-build-and-scan-skfx6-clone-pod-place-scripts 4 45
default pod-build-and-scan-skfx6-build-pod-place-scripts 4 45
tekton-pipelines replicaset-tekton-triggers-webhook-5ddd9c4cbd-webhook 3 10
tekton-pipelines replicaset-tekton-pipelines-webhook-5568b6-webhook 3 10
tekton-pipelines replicaset-7c789d7fd9 3 10
tekton-pipelines replicaset-6985f46fcc 3 15Pick the top offender and drill in: which CVE, which package, and whether a fixed version exists (.report.vulnerabilities[] | select(.severity=="CRITICAL")).
Fleet side: run kubectl get sbomreports -A | head, then pick one and count its components (kubectl get sbomreport <name> -n <ns> -o jsonpath='{.report.components.components}' | jq length). Pipeline side (from 2.4): run trivy image --format cyclonedx --output sbom.json ghcr.io/nginxinc/nginx-unprivileged:1.27-alpine and confirm both SBOMs speak the same CycloneDX schema.
Run kubectl get clustercompliancereports (CIS, NSA, and PSS profiles), inspect one summary via kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.status.summary}', then dig into the full output to pull out one failing control's ID and description.
An SBOM only pays off if you can scan it and compare it. Generate one with Trivy and one with Syft, feed it back into the scanner, then suppress one CVE with a VEX document so the exception lives in a reviewable file rather than a CLI flag.
trivy image --format spdx-json --output /tmp/sbom-trivy.json ghcr.io/stefanprodan/podinfo:6.7.1
jq '{name: .name, packages: (.packages | length)}' /tmp/sbom-trivy.json
mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
command -v syft >/dev/null || curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b "$HOME/.local/bin"
syft version | head -2
syft ghcr.io/stefanprodan/podinfo:6.7.1 -o spdx-json=/tmp/sbom-syft.json
jq '{name: .name, packages: (.packages | length)}' /tmp/sbom-syft.json
jq -r '.packages[].name' /tmp/sbom-trivy.json | sort -u > /tmp/p-trivy.txt
jq -r '.packages[].name' /tmp/sbom-syft.json | sort -u > /tmp/p-syft.txt
wc -l /tmp/p-trivy.txt /tmp/p-syft.txt
comm -3 /tmp/p-trivy.txt /tmp/p-syft.txt | head -10
trivy sbom /tmp/sbom-trivy.json --severity HIGH,CRITICAL | head -30
trivy image --severity HIGH,CRITICAL --format json ghcr.io/stefanprodan/podinfo:6.7.1 | jq -r '[.Results[].Vulnerabilities // [] | .[].VulnerabilityID] | unique | .[0:3][]'
CVE=$(trivy image --severity HIGH,CRITICAL --format json ghcr.io/stefanprodan/podinfo:6.7.1 | jq -r '[.Results[].Vulnerabilities // [] | .[].VulnerabilityID] | unique | .[0]')
echo "suppressing $CVE"
cat > /tmp/vex.json <<EOF
{
"@context": "https://openvex.dev/ns/v0.2.0",
"@id": "https://lab.local/vex/podinfo",
"author": "platform team",
"statements": [
{
"vulnerability": { "name": "${CVE}" },
"products": [{ "@id": "pkg:oci/podinfo" }],
"status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path"
}
]
}
EOF
trivy image --vex /tmp/vex.json --severity HIGH,CRITICAL ghcr.io/stefanprodan/podinfo:6.7.1 | head -20outputcaptured 2026-09-12
$ trivy image --format spdx-json --output /tmp/sbom-trivy.json ghcr.io/stefanprodan/podinfo:6.7.1
2026-09-13T13:01:03-04:00 INFO "--format spdx-json" disables security scanning. Specify "--scanners vuln" explicitly if you want to include vulnerabilities in the "spdx-json" report.
2026-09-13T13:01:03-04:00 INFO Detected OS family="alpine" version="3.20.3"
2026-09-13T13:01:03-04:00 INFO Number of language-specific files num=2
📣 Notices:
- Version 0.74.0 of Trivy is now available, current version is 0.73.0
To suppress version checks, run Trivy scans with the --skip-version-check flag
$ jq '{name: .name, packages: (.packages | length)}' /tmp/sbom-trivy.json
{
"name": "ghcr.io/stefanprodan/podinfo:6.7.1",
"packages": 115
}
$ mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
$ command -v syft >/dev/null || curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b "$HOME/.local/bin"
$ syft version | head -2
Application: syft
Version: 1.51.1
$ syft ghcr.io/stefanprodan/podinfo:6.7.1 -o spdx-json=/tmp/sbom-syft.json
$ jq '{name: .name, packages: (.packages | length)}' /tmp/sbom-syft.json
{
"name": "ghcr.io/stefanprodan/podinfo",
"packages": 112
}
$ jq -r '.packages[].name' /tmp/sbom-trivy.json | sort -u > /tmp/p-trivy.txt
$ jq -r '.packages[].name' /tmp/sbom-syft.json | sort -u > /tmp/p-syft.txt
$ wc -l /tmp/p-trivy.txt /tmp/p-syft.txt
103 /tmp/p-trivy.txt
100 /tmp/p-syft.txt
203 total
$ comm -3 /tmp/p-trivy.txt /tmp/p-syft.txt | head -10
alpine
ghcr.io/stefanprodan/podinfo
ghcr.io/stefanprodan/podinfo:6.7.1
home/app/podinfo
usr/local/bin/podcli
$ trivy sbom /tmp/sbom-trivy.json --severity HIGH,CRITICAL | head -30
2026-09-13T13:01:08-04:00 INFO [vuln] Vulnerability scanning is enabled
2026-09-13T13:01:08-04:00 INFO Detected SBOM format format="spdx-json"
2026-09-13T13:01:08-04:00 INFO Detected OS family="alpine" version="3.20.3"
2026-09-13T13:01:08-04:00 INFO [alpine] Detecting vulnerabilities... os_version="3.20" repository="" pkg_num=27
2026-09-13T13:01:08-04:00 INFO Number of language-specific files num=2
2026-09-13T13:01:08-04:00 INFO [gobinary] Detecting vulnerabilities...
2026-09-13T13:01:08-04:00 WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.73/guide/scanner/vulnerability#severity-selection for details.
2026-09-13T13:01:08-04:00 WARN This OS version is no longer supported by the distribution family="alpine" version="3.20.3"
2026-09-13T13:01:08-04:00 WARN The vulnerability detection may be insufficient because security updates are not provided
Report Summary
┌──────────────────────────────────────┬──────────┬─────────────────┐
│ Target │ Type │ Vulnerabilities │
├──────────────────────────────────────┼──────────┼─────────────────┤
│ /tmp/sbom-trivy.json (alpine 3.20.3) │ alpine │ 21 │
├──────────────────────────────────────┼──────────┼─────────────────┤
│ home/app/podinfo │ gobinary │ 36 │
├──────────────────────────────────────┼──────────┼─────────────────┤
│ usr/local/bin/podcli │ gobinary │ 33 │
└──────────────────────────────────────┴──────────┴─────────────────┘
Legend:
- '-': Not scanned
- '0': Clean (no security findings detected)
/tmp/sbom-trivy.json (alpine 3.20.3)
====================================
Total: 21 (HIGH: 19, CRITICAL: 2)
┌────────────┬────────────────┬──────────┬────────┬───────────────────┬───────────────┬──────────────────────────────────────────────────────────────┐
│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │
├────────────┼────────────────┼──────────┼────────┼───────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤
│ libcrypto3 │ CVE-2026-31789 │ CRITICAL │ fixed │ 3.3.2-r0 │ 3.3.7-r0 │ openssl: OpenSSL: Heap buffer overflow on 32-bit systems │
│ │ │ │ │ │ │ from large X.509 certificate... │
│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-31789 │
│ ├────────────────┼──────────┤ │ ├───────────────┼──────────────────────────────────────────────────────────────┤
│ │ CVE-2024-12797 │ HIGH │ │ │ 3.3.3-r0 │ openssl: RFC7250 handshakes with unauthenticated servers │
│ │ │ │ │ │ │ don't abort as expected │
$ trivy image --severity HIGH,CRITICAL --format json ghcr.io/stefanprodan/podinfo:6.7.1 | jq -r '[.Results[].Vulnerabilities // [] | .[].VulnerabilityID] | unique | .[0:3][]'
2026-09-13T13:01:08-04:00 INFO [vuln] Vulnerability scanning is enabled
2026-09-13T13:01:08-04:00 INFO [secret] Secret scanning is enabled
2026-09-13T13:01:08-04:00 INFO [secret] If your scanning is slow, please try '--scanners vuln' to disable secret scanning
2026-09-13T13:01:08-04:00 INFO [secret] Please see https://trivy.dev/docs/v0.73/guide/scanner/secret#recommendation for faster secret detection
2026-09-13T13:01:08-04:00 INFO Detected OS family="alpine" version="3.20.3"
2026-09-13T13:01:08-04:00 INFO [alpine] Detecting vulnerabilities... os_version="3.20" repository="3.20" pkg_num=27
2026-09-13T13:01:08-04:00 INFO Number of language-specific files num=2
2026-09-13T13:01:08-04:00 INFO [gobinary] Detecting vulnerabilities...
2026-09-13T13:01:08-04:00 WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.73/guide/scanner/vulnerability#severity-selection for details.
2026-09-13T13:01:08-04:00 WARN This OS version is no longer supported by the distribution family="alpine" version="3.20.3"
2026-09-13T13:01:08-04:00 WARN The vulnerability detection may be insufficient because security updates are not provided
📣 Notices:
- Version 0.74.0 of Trivy is now available, current version is 0.73.0
To suppress version checks, run Trivy scans with the --skip-version-check flag
CVE-2024-12797
CVE-2024-45338
CVE-2025-15467
$ CVE=$(trivy image --severity HIGH,CRITICAL --format json ghcr.io/stefanprodan/podinfo:6.7.1 | jq -r '[.Results[].Vulnerabilities // [] | .[].VulnerabilityID] | unique | .[0]')
2026-09-13T13:01:08-04:00 INFO [vuln] Vulnerability scanning is enabled
2026-09-13T13:01:08-04:00 INFO [secret] Secret scanning is enabled
2026-09-13T13:01:08-04:00 INFO [secret] If your scanning is slow, please try '--scanners vuln' to disable secret scanning
2026-09-13T13:01:08-04:00 INFO [secret] Please see https://trivy.dev/docs/v0.73/guide/scanner/secret#recommendation for faster secret detection
2026-09-13T13:01:09-04:00 INFO Detected OS family="alpine" version="3.20.3"
2026-09-13T13:01:09-04:00 INFO [alpine] Detecting vulnerabilities... os_version="3.20" repository="3.20" pkg_num=27
2026-09-13T13:01:09-04:00 INFO Number of language-specific files num=2
2026-09-13T13:01:09-04:00 INFO [gobinary] Detecting vulnerabilities...
2026-09-13T13:01:09-04:00 WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.73/guide/scanner/vulnerability#severity-selection for details.
2026-09-13T13:01:09-04:00 WARN This OS version is no longer supported by the distribution family="alpine" version="3.20.3"
2026-09-13T13:01:09-04:00 WARN The vulnerability detection may be insufficient because security updates are not provided
📣 Notices:
- Version 0.74.0 of Trivy is now available, current version is 0.73.0
To suppress version checks, run Trivy scans with the --skip-version-check flag
$ echo "suppressing $CVE"
suppressing CVE-2024-12797
$ cat > /tmp/vex.json <<EOF
{
"@context": "https://openvex.dev/ns/v0.2.0",
"@id": "https://lab.local/vex/podinfo",
"author": "platform team",
"statements": [
{
"vulnerability": { "name": "${CVE}" },
"products": [{ "@id": "pkg:oci/podinfo" }],
"status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path"
}
]
}
EOF
$ trivy image --vex /tmp/vex.json --severity HIGH,CRITICAL ghcr.io/stefanprodan/podinfo:6.7.1 | head -20
2026-09-13T13:01:09-04:00 INFO [vuln] Vulnerability scanning is enabled
2026-09-13T13:01:09-04:00 INFO [secret] Secret scanning is enabled
2026-09-13T13:01:09-04:00 INFO [secret] If your scanning is slow, please try '--scanners vuln' to disable secret scanning
2026-09-13T13:01:09-04:00 INFO [secret] Please see https://trivy.dev/docs/v0.73/guide/scanner/secret#recommendation for faster secret detection
2026-09-13T13:01:09-04:00 INFO Detected OS family="alpine" version="3.20.3"
2026-09-13T13:01:09-04:00 INFO [alpine] Detecting vulnerabilities... os_version="3.20" repository="3.20" pkg_num=27
2026-09-13T13:01:09-04:00 INFO Number of language-specific files num=2
2026-09-13T13:01:09-04:00 INFO [gobinary] Detecting vulnerabilities...
2026-09-13T13:01:09-04:00 WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.73/guide/scanner/vulnerability#severity-selection for details.
2026-09-13T13:01:09-04:00 WARN This OS version is no longer supported by the distribution family="alpine" version="3.20.3"
2026-09-13T13:01:09-04:00 WARN The vulnerability detection may be insufficient because security updates are not provided
2026-09-13T13:01:09-04:00 INFO Some vulnerabilities have been ignored/suppressed. Use the "--show-suppressed" flag to display them.
Report Summary
┌────────────────────────────────────────────────────┬──────────┬─────────────────┬─────────┐
│ Target │ Type │ Vulnerabilities │ Secrets │
├────────────────────────────────────────────────────┼──────────┼─────────────────┼─────────┤
│ ghcr.io/stefanprodan/podinfo:6.7.1 (alpine 3.20.3) │ alpine │ 19 │ - │
├────────────────────────────────────────────────────┼──────────┼─────────────────┼─────────┤
│ home/app/podinfo │ gobinary │ 36 │ - │
├────────────────────────────────────────────────────┼──────────┼─────────────────┼─────────┤
│ usr/local/bin/podcli │ gobinary │ 33 │ - │
└────────────────────────────────────────────────────┴──────────┴─────────────────┴─────────┘
Legend:
- '-': Not scanned
- '0': Clean (no security findings detected)
ghcr.io/stefanprodan/podinfo:6.7.1 (alpine 3.20.3)
==================================================
Total: 19 (HIGH: 17, CRITICAL: 2)comm highlights where the two catalogers disagree. Slightly different counts are completely normal: each tool draws its own line on what counts as a package, and trivy sbom happily scans either file. On the VEX half, rescanning with --vex drops Alpine findings from 21 to 19 and prints a clear notice ("Some vulnerabilities have been ignored/suppressed"): an auditable exception you can review in git, not an ad-hoc flag someone remembered to type.Because a ClusterComplianceReport runs on a cron schedule, a stale timestamp means you're staring at yesterday's picture. Patching spec.cron is the supported way to trigger a fresh rollup, and status.updateTimestamp proves it ran.
kubectl get clustercompliancereport
BEFORE=$(kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.status.updateTimestamp}'); echo "before: $BEFORE"
kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.spec.cron}{"\n"}'
kubectl patch clustercompliancereport k8s-cis-1.23 --type merge -p '{"spec":{"cron":"*/1 * * * *"}}'
for i in $(seq 1 24); do NOW=$(kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.status.updateTimestamp}'); [ "$NOW" != "$BEFORE" ] && { echo "after: $NOW (took ${i}0s)"; break; }; sleep 10; done
kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.status.summary}' | jq
kubectl patch clustercompliancereport k8s-cis-1.23 --type merge -p '{"spec":{"cron":"0 */6 * * *"}}'outputcaptured 2026-09-13
$ kubectl get clustercompliancereport
NAME AGE
k8s-cis-1.23 15h
k8s-nsa-1.0 15h
k8s-pss-baseline-0.1 15h
k8s-pss-restricted-0.1 15h
$ BEFORE=$(kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.status.updateTimestamp}'); echo "before: $BEFORE"
before: 2026-09-13T00:00:00Z
$ kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.spec.cron}{"\n"}'
0 */6 * * *
$ kubectl patch clustercompliancereport k8s-cis-1.23 --type merge -p '{"spec":{"cron":"*/1 * * * *"}}'
clustercompliancereport.aquasecurity.github.io/k8s-cis-1.23 patched
$ for i in $(seq 1 24); do NOW=$(kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.status.updateTimestamp}'); [ "$NOW" != "$BEFORE" ] && { echo "after: $NOW (took ${i}0s)"; break; }; sleep 10; done
after: 2026-09-13T10:49:49Z (took 10s)
$ kubectl get clustercompliancereport k8s-cis-1.23 -o jsonpath='{.status.summary}' | jq
{
"failCount": 34,
"passCount": 82
}
$ kubectl patch clustercompliancereport k8s-cis-1.23 --type merge -p '{"spec":{"cron":"0 */6 * * *"}}'
clustercompliancereport.aquasecurity.github.io/k8s-cis-1.23 patchedCIS benchmark output is the lingua franca of cluster compliance: a control ID, a verdict, and a concrete remediation step. Run it once so those numbered IDs click immediately when a task quotes one at you.
kubectl apply -f - <<'EOF'
apiVersion: batch/v1
kind: Job
metadata: { name: kube-bench, namespace: default }
spec:
template:
spec:
hostPID: true
nodeSelector: { node-role.kubernetes.io/control-plane: "" }
tolerations:
- { key: node-role.kubernetes.io/control-plane, operator: Exists, effect: NoSchedule }
containers:
- name: kube-bench
image: docker.io/aquasec/kube-bench:latest
command: ["kube-bench", "run", "--targets", "master"]
volumeMounts:
- { name: etc-kubernetes, mountPath: /etc/kubernetes, readOnly: true }
- { name: var-lib-etcd, mountPath: /var/lib/etcd, readOnly: true }
restartPolicy: Never
volumes:
- { name: etc-kubernetes, hostPath: { path: /etc/kubernetes } }
- { name: var-lib-etcd, hostPath: { path: /var/lib/etcd } }
backoffLimit: 0
EOF
kubectl wait --for=condition=complete job/kube-bench --timeout=300s || true
kubectl logs job/kube-bench | grep -E '^\[(PASS|FAIL)\]' | head -10
kubectl logs job/kube-bench | tail -20
kubectl delete job kube-benchoutputcaptured 2026-09-12
$ kubectl apply -f - <<'EOF'
apiVersion: batch/v1
kind: Job
metadata: { name: kube-bench, namespace: default }
spec:
template:
spec:
hostPID: true
nodeSelector: { node-role.kubernetes.io/control-plane: "" }
tolerations:
- { key: node-role.kubernetes.io/control-plane, operator: Exists, effect: NoSchedule }
containers:
- name: kube-bench
image: docker.io/aquasec/kube-bench:latest
command: ["kube-bench", "run", "--targets", "master"]
volumeMounts:
- { name: etc-kubernetes, mountPath: /etc/kubernetes, readOnly: true }
- { name: var-lib-etcd, mountPath: /var/lib/etcd, readOnly: true }
restartPolicy: Never
volumes:
- { name: etc-kubernetes, hostPath: { path: /etc/kubernetes } }
- { name: var-lib-etcd, hostPath: { path: /var/lib/etcd } }
backoffLimit: 0
EOF
job.batch/kube-bench created
$ kubectl wait --for=condition=complete job/kube-bench --timeout=300s || true
job.batch/kube-bench condition met
$ kubectl logs job/kube-bench | grep -E '^\[(PASS|FAIL)\]' | head -10
[PASS] 1.1.1 Ensure that the API server pod specification file permissions are set to 600 or more restrictive (Automated)
[PASS] 1.1.2 Ensure that the API server pod specification file ownership is set to root:root (Automated)
[PASS] 1.1.3 Ensure that the controller manager pod specification file permissions are set to 600 or more restrictive (Automated)
[PASS] 1.1.4 Ensure that the controller manager pod specification file ownership is set to root:root (Automated)
[PASS] 1.1.5 Ensure that the scheduler pod specification file permissions are set to 600 or more restrictive (Automated)
[PASS] 1.1.6 Ensure that the scheduler pod specification file ownership is set to root:root (Automated)
[PASS] 1.1.7 Ensure that the etcd pod specification file permissions are set to 600 or more restrictive (Automated)
[PASS] 1.1.8 Ensure that the etcd pod specification file ownership is set to root:root (Automated)
[PASS] 1.1.11 Ensure that the etcd data directory permissions are set to 700 or more restrictive (Automated)
[FAIL] 1.1.12 Ensure that the etcd data directory ownership is set to etcd:etcd (Automated)
$ kubectl logs job/kube-bench | tail -20
1.4.1 Edit the Scheduler pod specification file /etc/kubernetes/manifests/kube-scheduler.yaml file
on the control plane node and set the below parameter.
--profiling=false
1.4.2 Edit the Scheduler pod specification file /etc/kubernetes/manifests/kube-scheduler.yaml
on the control plane node and ensure the correct value for the --bind-address parameter
== Summary master ==
38 checks PASS
11 checks FAIL
11 checks WARN
0 checks INFO
== Summary total ==
38 checks PASS
11 checks FAIL
11 checks WARN
0 checks INFO
$ kubectl delete job kube-bench
job.batch "kube-bench" deleted from default namespaceSelf-check
Which audit level would you set for Secrets, and which for Events? Why?
Secrets go at Metadata, never Request or RequestResponse, so you don't leak secret values straight into log files. Events go at None because they're noisy, high-volume, and low-value. Because rules are first-match-wins, put both near the top of your policy file.
Find every request a specific ServiceAccount was denied. What does the query look like?
Filter on .user.username == "system:serviceaccount:<ns>:<name>" paired with either .responseStatus.code == 403 or .annotations["authorization.k8s.io/decision"] == "forbid", then project out verb and objectRef. That's the audit-log twin of the RBAC debugging you practiced in 5.1.
An SBOM and a vulnerability report: what is the difference and why keep both?
An SBOM is a static inventory of components and versions; a vulnerability report is that inventory matched against a CVE database at one moment in time. Keep both because the inventory stays constant while new CVEs appear every day, which is why continuous rescanning via an operator beats scanning only at build time.
Why is "compliance as CRDs" a platform-engineering idea rather than a Trivy feature?
Because storing compliance findings as Kubernetes API objects makes them queryable with kubectl, governed by RBAC, watchable by controllers, graphable in Grafana, and reviewable in git. Static reports dumped into an object bucket can't integrate cleanly with anything else your platform already runs.
Your cluster's API server will not start after an audit change. First hypothesis?
The policy file at --audit-policy-file is missing, unreadable, or has invalid YAML (or its hostPath mount in the static pod manifest is broken). By design, kube-apiserver refuses to start rather than run silently unaudited, so a small audit mistake looks like a dead control plane.
Your audit policy puts the catch-all Metadata rule first and the Secrets rule after it. What is wrong, and what else should precede the catch-all?
First match wins, so putting the catch-all first makes every rule below it dead code. Here Secrets still land at Metadata by luck, but any None rule below the catch-all stops filtering noise, and any RequestResponse rule below it stops capturing RBAC diffs. Always order from top to bottom: None for health URLs, leases, and kube-proxy watches; Metadata for secrets, configmaps, tokenreviews, and pods/exec; RequestResponse for RBAC and policy groups; and the catch-all last.
Which layer catches each: a user reads a Secret; a process in a container starts /bin/sh; an image contains a package with a new CVE; a node's kubelet allows anonymous auth?
In order: the API audit log (Metadata rule on secrets), Falco syscall rules, the Trivy Operator's VulnerabilityReport on rescan (or a pipeline scan at build time), and kube-bench or the Trivy Operator's InfraAssessmentReport / CIS compliance report. Four distinct sensors telling one compliance story; naming which layer catches what is how you nail "design a complete audit trail".
What is the difference between an SBOM attestation and a VEX document, and why keep both?
The SBOM lists every component inside an artifact, while VEX states whether specific CVEs in those components actually affect the product (not affected, affected, fixed, or under investigation) along with a justification. Scanners match the SBOM against CVE feeds and then apply VEX to suppress non-applicable findings with a documented rationale, which is auditable in a way a bare .trivyignore entry isn't.
Docs to know your way around
- kubernetes.io: Auditing (policy levels, stages, and the event schema).
- aquasecurity.github.io/trivy-operator: the CRD reference pages, one per report kind.
- cyclonedx.org / spdx.dev: just enough to tell the two formats apart cleanly.
- Offline:
jqagainst the audit log file, pluskubectl explain clustercompliancereport.status. - kubernetes.io/docs/tasks/debug/debug-cluster/audit: rule fields, stages, and every flag for both backends; check the
audit.k8s.io/v1PolicyAPI reference foromitManagedFields. - aquasecurity.github.io/trivy-operator/latest/docs/crds (per-kind references) and /docs/compliance (the four compliance spec IDs); aquasecurity.github.io/trivy/latest/docs/configuration/filtering for VEX and ignore files.
- falco.org/docs/rules for rule syntax and github.com/in-toto/attestation/tree/main/spec for the Statement and DSSE layout.