Query Details

P1 04a Eks Audit Privesc Baseline

Query

// Standalone KQL for Analytic Rule: AWS SecOps P1-04a - EKS Audit Pod Exec, Privileged Workload and Cluster-Admin Escalation (Single-Source)
// Rule File: analytics/P1-04a-eks-audit-privesc-baseline.yaml | Rule ID: REPLACE_WITH_RULE_GUID | Severity: High
// Schedule: 15m / Lookback: 1h | REVIEW ONLY - Do not deploy/schedule without approval.
// 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 KQL query is designed to detect potential security risks and suspicious activities in Amazon EKS (Elastic Kubernetes Service) audit logs. Here's a simplified breakdown of what the query does:

  1. Approved Controllers List: It first retrieves a list of approved automation principals from a watchlist, filtering only those marked as verified.

  2. EKS Audit Logs: It processes EKS audit logs from AWS CloudWatch, focusing on logs generated in the last hour and ingested in the last 15 minutes. It filters for logs that are complete and successful (HTTP status codes 200-299 or 101).

  3. Filter Out System Users: It excludes logs related to system users and certain known service accounts to focus on potentially suspicious activities.

  4. Identify Risk Events: It identifies specific risk events, such as:

    • Anonymous API access attempts.
    • Interactive pod operations like exec, attach, or portforward.
    • Creation or modification of privileged pods.
    • Creation or modification of cluster-admin role bindings.
    • Service account token requests in the kube-system namespace.
    • Tampering with admission or audit controls.
  5. Bulk Secret Access: It detects bulk access to Kubernetes secrets, flagging cases where a user accesses a large number of secrets or makes numerous access attempts.

  6. Combine Results: It combines the identified risk events and bulk secret access detections into a single dataset.

  7. Output: The final output includes details such as the time of the event, cluster name, namespace, resource type, object name, account name, source IP address, user agent, and the specific risk signal detected.

This query is part of a security analytic rule designed to highlight high-severity security concerns in EKS environments. It should be reviewed and confirmed with discovery queries before deployment.