TExcelTAD
Home › Cloud & Container Security › Kubernetes Secrets, Audit Logs, CIS Benchmarks and Managed Clusters

Kubernetes Secrets, Audit Logs, CIS Benchmarks and Managed Clusters

This lesson closes the Kubernetes section with the four things a cluster review always ends on: how Secrets are protected, whether the audit log would show an attack, how the cluster compares with the CIS Kubernetes Benchmark, and what changes on managed services, where part of the cluster is the provider's.

Secrets: what they are and aren't

A Kubernetes Secret is an API object whose values are base64-encoded, which is an encoding for binary safety, not protection. What actually protects a Secret:

Layer Control Common gap
Storage encryption at rest in etcd (EncryptionConfiguration, ideally the KMS provider; managed services offer envelope encryption with your cloud KMS key) not configured on self-managed clusters; on managed ones, the option left off
API access RBAC on secrets (get by name vs list/watch of everything) list granted widely; create pods granted, which reaches Secrets by mounting them (RBAC Review)
Node the kubelet only fetches Secrets for pods scheduled on its node (Node authorizer) a node compromise exposes every Secret of its pods
In the pod mounted files or environment variables env vars leak into crash dumps, /proc/<pid>/environ, debug endpoints; prefer files
Source external secret stores (Vault, cloud secret managers) synced by an operator or read directly with workload identity Secrets committed to Git as plain YAML

External Secrets & Sealed Secrets covers the operators; Workload Identity the alternative of not having a Secret at all.

Audit logs

The API server can record every request in an audit log, governed by an audit policy that sets a level per resource: None, Metadata (who, what, when, result), Request (plus the request body) or RequestResponse. A sensible policy logs Secrets and TokenReviews at Metadata only (bodies would copy the secrets into the log) and workload changes at Request. On managed clusters the audit log must be enabled and exported: EKS control-plane logging is off by default, AKS uses diagnostic settings, GKE writes Admin Activity audit logs always and Data Access logs only if enabled.

An audit event has, among other fields: verb, user.username and user.groups, impersonatedUser, sourceIPs, userAgent, objectRef (resource, subresource, namespace, name), responseStatus.code, and annotations such as the authorization decision and Pod Security violations.

The program applies eight detections to a synthetic slice of the lab cluster's audit log.

python · try it yourself
import json

events = [json.loads(l) for l in r"""
{"ts":"11:02:10","verb":"get","user":"system:serviceaccount:shop:web","res":"configmaps","ns":"shop","code":200}
{"ts":"11:05:44","verb":"list","user":"system:serviceaccount:shop:web","res":"secrets","ns":"shop","code":200}
{"ts":"11:05:47","verb":"list","user":"system:serviceaccount:shop:web","res":"secrets","ns":"kube-system","code":403}
{"ts":"11:06:02","verb":"create","user":"system:serviceaccount:shop:web","res":"selfsubjectrulesreviews","ns":"shop","code":201}
{"ts":"11:07:30","verb":"create","user":"alice@lab.test","res":"pods","sub":"exec","ns":"shop","name":"web-7d9","code":101,"ua":"kubectl/v1.34"}
{"ts":"11:08:15","verb":"get","user":"system:anonymous","res":"nodes","ns":"","code":403,"ip":"198.51.100.23"}
{"ts":"11:09:00","verb":"create","user":"carol@lab.test","imp":"system:masters","res":"clusterrolebindings","ns":"","name":"tmp-admin","code":201}
{"ts":"11:10:12","verb":"create","user":"system:serviceaccount:ci:deployer","res":"pods","ns":"shop","code":201,"privileged":true}
{"ts":"11:11:40","verb":"create","user":"system:serviceaccount:shop:web","res":"serviceaccounts","sub":"token","ns":"shop","name":"backup","code":201}
""".strip().splitlines()]

def is_sa(u):
    return u.startswith("system:serviceaccount:")

rules = [
    ("secrets listed by a workload", lambda e: e["res"] == "secrets" and e["verb"] in ("list", "watch") and is_sa(e["user"])),
    ("permission discovery by a workload", lambda e: e["res"] in ("selfsubjectrulesreviews", "selfsubjectaccessreviews") and is_sa(e["user"])),
    ("exec into a pod", lambda e: e.get("sub") in ("exec", "attach") and e["code"] < 400),
    ("anonymous request", lambda e: e["user"] == "system:anonymous"),
    ("impersonation", lambda e: "imp" in e),
    ("cluster-wide RBAC change", lambda e: e["res"] in ("clusterrolebindings", "clusterroles") and e["verb"] in ("create", "update", "patch")),
    ("privileged pod created", lambda e: e["res"] == "pods" and e["verb"] == "create" and e.get("privileged")),
    ("token minted for another service account", lambda e: e.get("sub") == "token" and e["user"].split(":")[-1] != e.get("name")),
]
for e in events:
    hits = [name for name, test in rules if test(e)]
    if hits:
        where = "/".join(x for x in (e["ns"], e.get("name", "")) if x)
        target = f"{e['res']}{'/' + e['sub'] if 'sub' in e else ''} {where}".strip()
        who = e["user"] + (f" as {e['imp']}" if "imp" in e else "")
        print(f"{e['ts']} [{e['code']}] {who:38} {e['verb']:6} {target:30} <- {', '.join(hits)}")
11:05:44 [200] system:serviceaccount:shop:web         list   secrets shop                   <- secrets listed by a workload
11:05:47 [403] system:serviceaccount:shop:web         list   secrets kube-system            <- secrets listed by a workload
11:06:02 [201] system:serviceaccount:shop:web         create selfsubjectrulesreviews shop   <- permission discovery by a workload
11:07:30 [101] alice@lab.test                         create pods/exec shop/web-7d9         <- exec into a pod
11:08:15 [403] system:anonymous                       get    nodes                          <- anonymous request
11:09:00 [201] carol@lab.test as system:masters       create clusterrolebindings tmp-admin  <- impersonation, cluster-wide RBAC change
11:10:12 [201] system:serviceaccount:ci:deployer      create pods shop                      <- privileged pod created
11:11:40 [201] system:serviceaccount:shop:web         create serviceaccounts/token shop/backup <- token minted for another service account

The web service account's lines tell one story: a compromised application lists the Secrets in its namespace (allowed, because its role grants list), tries kube-system (denied), asks the API what it is allowed to do (the selfsubjectrulesreviews call that kubectl auth can-i --list makes; applications never do this), and finally mints a token for the backup service account. Each step alone could be explained; together they are an intrusion. The other lines are separate findings: a human exec into production (maybe legitimate, always worth a ticket), an anonymous probe from outside, carol impersonating system:masters to create a ClusterRoleBinding, and CI creating a privileged pod.

The CIS Kubernetes Benchmark

The Center for Internet Security publishes the CIS Kubernetes Benchmark (control plane components, etcd, control plane configuration, worker nodes, policies) and provider-specific versions for EKS, AKS and GKE, which drop the controls the provider owns. Each recommendation has an audit procedure and a remediation, and is marked automated or manual. Typical items you have met in this section: anonymous auth off on API server and kubelet, Node,RBAC authorization, audit logging, encryption at rest, kubelet read-only port off, minimal cluster-admin bindings, no wildcard roles, Pod Security on all namespaces, default-deny NetworkPolicies, Secrets as files not environment variables. kube-bench runs the node and control-plane checks; posture tools and the providers' own scanners run the policy ones. Treat the benchmark as a baseline, not as a definition of "secure": it says nothing about your RBAC design or your workloads' behaviour.

Managed cluster specifics

EKS AKS GKE
Human access IAM principals mapped to Kubernetes identities: access entries (newer) or the legacy aws-auth ConfigMap Entra ID integration with Kubernetes RBAC or Azure RBAC; disable local accounts Google identities with IAM and Kubernetes RBAC
Workload cloud identity IRSA or EKS Pod Identity Workload ID (federated credentials) Workload Identity Federation for GKE
API endpoint public, private or both, with CIDR allow-lists public with authorized IP ranges, or private cluster public with authorized networks, or private endpoint
Audit logs control-plane logging, off by default, to CloudWatch Logs diagnostic settings to Log Analytics or storage Cloud Audit Logs
Node hardening managed node groups / Bottlerocket / Fargate node images, auto-upgrade channels Container-Optimized OS, Autopilot

Review points that are easy to miss: who holds cluster-admin through the cloud side (the EKS cluster creator gets admin by default unless changed; Azure Owner or Contributor on the cluster resource can fetch the cluster-admin kubeconfig while local accounts are enabled), whether local or static credentials are disabled, and whether the control-plane logs actually reach the SIEM.

Pitfalls

  • Logging Secrets at Request or RequestResponse level: the audit log becomes a second secret store.
  • Enabling audit logs and never reading them; the eight rules above are a reasonable first set.
  • Passing a CIS scan with a cluster where every developer is cluster-admin.

Practice

1. Which single RBAC change would have stopped the most steps of the web service account's story?

Removing list on Secrets from its role (keeping get on the one Secret it needs, by resourceNames) and its permission to create tokens; with automountServiceAccountToken: false it would not even have a token, if the app doesn't call the API at all.

2. Write the detection for "a workload creates a pod" and say why it is suspicious.

e["res"] == "pods" and e["verb"] == "create" and is_sa(e["user"]) and not e["user"].startswith("system:serviceaccount:kube-system:") (controllers create pods as their own service accounts in kube-system, and CI as its deployer). An application service account creating pods is a classic step to run as another identity or escape.

3. On EKS, the audit log has nothing for last week. What do you check?

Whether control-plane logging (the audit log type) is enabled for the cluster, where it is delivered (CloudWatch Logs group and retention), and whether the export to the SIEM works. Then treat last week as unmonitored in any investigation.

Test yourself

What protects Kubernetes Secrets at rest in etcd?

  1. Base64 encoding
  2. An encryption configuration (ideally the KMS provider) on the API server, or the managed service's envelope encryption
  3. RBAC alone
  4. Namespaces

At which audit level should Secrets be logged?

  1. RequestResponse
  2. Request
  3. Metadata
  4. Never log them

Which request in the log is a strong sign of a compromised workload exploring its permissions?

  1. get configmaps
  2. create selfsubjectrulesreviews by a service account
  3. alice exec
  4. anonymous get nodes

Is EKS control-plane audit logging enabled by default?

  1. Yes
  2. No, it must be turned on and delivered to CloudWatch Logs
  3. Only for private clusters
  4. It doesn't exist