Query Details

AWS SecOps P1-04a - EKS Audit Pod Exec, Privileged Workload and Cluster-Admin Escalation (Single-Source)

P1 04a Eks Audit Privesc Baseline

Query

// REVIEW ONLY. Run discovery/D07-eks-audit-discovery.kql FIRST to confirm whether EKS audit logs
// land in AWSCloudWatch (JSON in Message) or a custom *_CL table.
let ApprovedControllers = _GetWatchlist('AWS_ApprovedAutomationPrincipals')
| where tolower(tostring(column_ifexists("Verified", ""))) == "true"
| project tolower(tostring(column_ifexists("PrincipalArnPattern", "")));
let EksAudit = materialize(
    AWSCloudWatch
    | where TimeGenerated > ago(1h) and ingestion_time() > ago(15m)
    | where Message has "\"kind\":\"Event\"" and Message has "audit.k8s.io/"
    | extend Audit = parse_json(Message)
    | where tostring(Audit.stage) == "ResponseComplete"
    | extend ResponseCode = toint(Audit.responseStatus.code)
    | where ResponseCode between (200 .. 299) or ResponseCode == 101
    | extend Username = tostring(Audit.user.username),
        Verb = tostring(Audit.verb),
        Resource = tostring(Audit.objectRef.resource),
        Subresource = tostring(Audit.objectRef.subresource),
        Namespace = coalesce(tostring(Audit.objectRef.namespace), "cluster-scoped"),
        ObjectName = tostring(Audit.objectRef.name),
        SourceIp = tostring(Audit.sourceIPs[0]),
        UserAgent = tostring(Audit.userAgent),
        RequestUri = tostring(Audit.requestURI),
        ClusterName = coalesce(tostring(Audit.annotations["arn.amazonaws.com/cluster-name"]), extract(@"/aws/eks/([^/]+)/cluster", 1, Message), "UnknownCluster"),
        ReqText = tostring(Audit.requestObject)
    | where not(Username startswith "system:node:" or Username startswith "system:kube-"
        or Username in ("system:apiserver", "eks:addon-manager", "eks:node-manager", "eks:fargate-manager"))
    | where tolower(Username) !in (ApprovedControllers)
);
let AtomicRiskEvents = EksAudit
| extend EksSignal = case(
    Username == "system:anonymous" and not(RequestUri in ("/healthz", "/livez", "/readyz")),
        "AnonymousApiAccessSucceeded",
    Resource == "pods" and Subresource in ("exec", "attach", "portforward") and Verb in ("create", "get", "connect"),
        strcat("InteractivePodSubresource:", Subresource),
    Resource == "pods" and Verb in ("create", "update", "patch") and ReqText matches regex @"(?i)(""privileged""\s*:\s*true|""hostNetwork""\s*:\s*true|""hostPID""\s*:\s*true|""hostIPC""\s*:\s*true|""hostPath""\s*:)",
        "PrivilegedOrHostNamespacePodSpec",
    Resource in ("clusterrolebindings", "rolebindings") and Verb in ("create", "update", "patch") and ReqText matches regex @"(?i)(cluster-admin|system:masters|escalate|bind)",
        "ClusterAdminBindingCreated",
    Resource == "serviceaccounts" and Subresource == "token" and Verb == "create" and Namespace == "kube-system",
        "KubeSystemServiceAccountTokenRequest",
    Resource in ("mutatingwebhookconfigurations", "validatingwebhookconfigurations", "auditsinks") and Verb in ("create", "update", "patch", "delete"),
        "AdmissionOrAuditControlTampering",
    "")
| where isnotempty(EksSignal)
| project TimeGenerated, ClusterName, Namespace, Resource, ObjectName, Username, SourceIp, UserAgent, EksSignal;
let BulkSecretReads = EksAudit
| where Resource == "secrets" and Verb in ("get", "list", "watch")
| summarize TimeGenerated=min(TimeGenerated), SecretTouches=count(), DistinctSecrets=dcount(ObjectName), SampleSecret=take_any(ObjectName)
    by ClusterName, Namespace, Username, SourceIp, UserAgent
| where DistinctSecrets >= 5 or SecretTouches >= 15
| project TimeGenerated, ClusterName, Namespace, Resource="secrets", ObjectName=SampleSecret,
    Username, SourceIp, UserAgent, EksSignal=strcat("BulkSecretAccess(Distinct=", DistinctSecrets, ")");
union AtomicRiskEvents, BulkSecretReads
| project TimeGenerated, ClusterName, Namespace, Resource, ObjectName, AccountName=Username,
    SourceIpAddress=SourceIp, UserAgent, EksSignal

Explanation

This query is designed to monitor and detect potentially suspicious activities in Amazon EKS (Elastic Kubernetes Service) environments by analyzing audit logs. Here's a simplified breakdown of what it does:

  1. Purpose: The query aims to identify security-related events in EKS, such as unauthorized access, privilege escalation, and tampering with configurations.

  2. Data Source: It uses audit logs from AWS CloudWatch, specifically looking for Kubernetes audit events.

  3. Detection Criteria:

    • Interactive Pod Actions: Detects actions like executing commands in pods, attaching to pods, or port forwarding.
    • Privileged Pod Creation: Looks for the creation of pods with elevated privileges or access to the host network.
    • Cluster-Admin Role Escalation: Identifies the creation of role bindings that grant cluster-admin privileges.
    • Bulk Secret Access: Flags when a user accesses a large number of secrets (5 or more) in a short period.
    • Anonymous Access: Detects unauthorized access by anonymous users to endpoints other than health checks.
    • Configuration Tampering: Monitors for changes to webhook configurations or audit sinks.
  4. Exclusions: Known system accounts and approved automation principals are excluded from triggering alerts.

  5. Alerting: If any of these suspicious activities are detected, an alert is generated. The query runs every 15 minutes and looks back over the past hour.

  6. Incident Management: When an alert is triggered, it creates an incident and groups related alerts by account and cluster name for easier management.

  7. Severity: The severity of these alerts is marked as high, indicating the potential for significant security risks.

Overall, this query is part of a security monitoring strategy to ensure the integrity and security of Kubernetes clusters running on AWS.