Mastering the art of Attacking and Defending a Kubernetes Cluster

Sanjeev Mahajan (IT Security Professional)

BSides Canberra VII (2024) · Day 3 · Main Track

Overview

In his compelling talk at BSides Canberra, Sanjeev Mahajan, a Principal Security Engineer with over 15 years in the industry, including a decade focused on security, provided a deep dive into the practicalities of both exploiting and securing Kubernetes clusters. Mahajan, who has spent years immersed in Kubernetes as both an attacker and a defender, aimed to demystify the complexities of Kubernetes security. The session cut through common misconceptions, presenting real-world attack chains observed in mature, production environments, and subsequently outlined a robust defense-in-depth strategy.

Watch on YouTube

Visual summary for Mastering the art of Attacking and Defending a Kubernetes Cluster by Sanjeev Mahajan
Visual summary for Mastering the art of Attacking and Defending a Kubernetes Cluster by Sanjeev Mahajan

Key moments

  1. 0:00 Introduction, speaker background, and talk agenda
  2. 3:45 Debunking Kubernetes security myths and shared responsibility
  3. 7:00 Attack chain 1: CI/CD misconfiguration to cluster admin
  4. 12:30 Attack chain 2: Unrevoked temporary access to storage
  5. 15:00 Attack chain 3: Container escape to host shell
  6. 19:00 Defense in depth strategy (Build, Deploy, Run)
  7. 22:00 Key takeaways for attackers, defenders, and organizations

Mastering the Art of Attacking and Defending a Kubernetes Cluster

Speakers: Sanjeev Mahajan, Principal Security Engineer, Cyber Services

Conference: BSides Canberra

YouTube: https://www.youtube.com/watch?v=GAWRqCSX5tE

Overview

In his compelling talk at BSides Canberra, Sanjeev Mahajan, a Principal Security Engineer with over 15 years in the industry, including a decade focused on security, provided a deep dive into the practicalities of both exploiting and securing Kubernetes clusters. Mahajan, who has spent years immersed in Kubernetes as both an attacker and a defender, aimed to demystify the complexities of Kubernetes security. The session cut through common misconceptions, presenting real-world attack chains observed in mature, production environments, and subsequently outlined a robust defense-in-depth strategy.

The core premise of Mahajan's presentation centered on challenging the pervasive myths surrounding Kubernetes security, particularly the notion that it is "secure by design" or solely the responsibility of cloud service providers. He underscored the critical importance of understanding the shared responsibility model and highlighted that a staggering 90% of security findings in Kubernetes environments stem from misconfigurations. This talk is essential for anyone involved in cloud-native development, operations, or security, offering invaluable insights into the specific vulnerabilities that can be exploited and the actionable controls necessary to build resilient Kubernetes defenses.

Mahajan’s talk is significant because it moves beyond theoretical vulnerabilities, presenting actual attack narratives from engagements with tier-one organizations. These case studies illustrate how subtle misconfigurations, often overlooked, can lead to complete cluster compromise, data exfiltration, and even host-level access. By detailing these sophisticated attack paths and coupling them with a comprehensive defense strategy, Mahajan empowers both offensive and defensive security professionals to better secure their Kubernetes deployments against increasingly sophisticated threats.

Background

▶ Watch: Introduction, speaker background, and talk agenda (0:00)

Kubernetes, often described as a container orchestration tool, serves as a complex party planner for software, managing the deployment, scaling, and operation of containerized applications. While it offers immense benefits in terms of efficiency and scalability, its complexity introduces significant security challenges that are frequently underestimated. A prevalent myth Mahajan addressed is the belief that Kubernetes is inherently "secure by design" or that its security is entirely handled by the cloud service provider (CSP). This misunderstanding often leads to critical security gaps.

Mahajan clarified that Kubernetes security operates under a shared responsibility model. Cloud providers like Amazon or Google are primarily responsible for the security of the cloud – encompassing the physical infrastructure, data centers, and the underlying hypervisor. However, the customer is responsible for security in the cloud. This includes the configuration of the Kubernetes cluster itself, such as network policies, Identity and Access Management (IAM) controls, and data storage. Based on extensive research and engagements, Mahajan revealed that a staggering 90% of security findings in Kubernetes environments are attributable to customer-side misconfigurations, not inherent flaws in Kubernetes or the CSP's infrastructure. This statistic powerfully debunks the "secure by design" myth and underscores the critical need for proactive security measures and offensive security assessments, which many organizations erroneously believe add no value.

The speaker's insights into the prevailing confusions highlight a gap in understanding among development and operations teams. The assumption that Kubernetes is secure by default or that someone else is handling all aspects of its security exposes organizations to significant risk. This talk aimed to bridge that gap by illustrating the real-world consequences of these assumptions and providing a clear roadmap for mitigating them.

Key Findings

▶ Watch: Attack chain 1: CI/CD misconfiguration to cluster admin (7:00)

Sanjeev Mahajan presented three detailed attack chains, all originating from real-world engagements with tier-one organizations that boasted "mature practices" and "locked-down" Kubernetes clusters. These were not theoretical lab exercises but practical demonstrations of how determined attackers can exploit subtle misconfigurations to achieve significant compromise. The overarching theme of these findings is that even in seemingly secure environments, minor oversights in configuration can cascade into critical vulnerabilities.

The primary discoveries centered on:

  1. Lateral Movement via CI/CD Misconfiguration: Demonstrating how a read-only user, through exploiting a misconfigured CI/CD pipeline, could gain cluster admin privileges and compromise an entire Kubernetes cluster. This highlighted the often-overlooked attack surface presented by integrated development tools.
  2. Cluster Breakout to Sensitive Data Exfiltration: Illustrating how an attacker could move from within the Kubernetes cluster to gain read and write access to sensitive storage buckets in the broader cloud environment, leveraging unrevoked temporary permissions.
  3. Container Escape to Host Compromise: Showcasing a complete escape from a containerized workload to obtain a working shell on the underlying worker node, effectively compromising the host system and all other containers running on it, by abusing a privileged pod.

These findings collectively emphasize that effective Kubernetes security requires a holistic view, extending beyond the cluster itself to encompass integrated systems and the broader cloud infrastructure. The talk served as a stark reminder that the devil is in the details of configuration, and continuous vigilance is paramount.

Technical Deep Dive

▶ Watch: Attack chain 2: Unrevoked temporary access to storage (12:30)

Mahajan’s presentation meticulously detailed three real-world attack chains, each revealing a different vector for compromising Kubernetes environments. These attacks were executed against "mature and locked-down" clusters, underscoring the subtle nature of the exploited vulnerabilities.

Attack Chain 1: Read-Only User to Cluster Admin via CI/CD Misconfiguration

The first scenario began with the challenge of a read-only user in a Kubernetes cluster, with the client specifically requesting findings only from production environments. Initial reconnaissance revealed an exceptionally well-configured Kubernetes cluster, seemingly impenetrable. However, a deep dive into the cluster's sprawling environment uncovered a critical anomaly: a single pod running with cluster admin privileges. The credentials for this highly privileged pod were known to reside in its container's memory, making it a prime target.

Since direct access to this pod was impossible, the attackers shifted focus to integrating assets, specifically CI/CD pipelines responsible for provisioning cloud assets into the cluster. Within these pipelines, a misconfigured CI Runner caught their attention. This runner possessed a dangerous permission: get Secrets. Mahajan explained the crucial distinction here: list Secrets allows viewing only metadata (like secret names), while get Secrets grants access to the actual secret values. The development team had mistakenly granted get Secrets instead of list Secrets due to a naming convention confusion.

To exploit this, the attackers identified the repository associated with the misconfigured runner. Another critical misconfiguration allowed any user on the network to create feature branches on this repository. Exploiting this, a simple Python script was crafted to extract the runner's access token by querying the metadata APIs. With the runner's access token in hand, the attackers were able to replay it, retrieve the secrets for the cluster admin pod, and subsequently gain full cluster admin privileges, compromising the entire Kubernetes cluster. This attack highlighted how a seemingly minor misconfiguration in a CI/CD pipeline, coupled with a misunderstanding of IAM permissions, can lead to complete cluster compromise from an initial low-privilege foothold.

Attack Chain 2: Cluster Breakout to Storage Bucket Compromise

The second attack aimed to break out of the Kubernetes cluster and gain read/write access to sensitive storage buckets. Again, initial reconnaissance showed a secure setup, with no apparent direct access from the non-production cluster to production storage buckets. The breakthrough came from meticulously examining the configurations of all pods and service accounts.

Among thousands of pods, one was identified with storage admin permissions. Crucially, this pod had these elevated rights not only for non-production but also for production storage buckets. The attackers obtained exec access to this pod, which conveniently provided a shell and the curl utility. Using curl, they called the cloud provider's metadata APIs to extract the pod's access token. This token, with its unrevoked storage admin permissions, granted full read and write access to the production storage buckets, allowing sensitive data exfiltration or manipulation.

The root cause of this vulnerability was a classic operational oversight: during a production incident, temporary storage admin access was granted to the pod. However, the engineering team failed to revoke these credentials after the incident was resolved, leaving a persistent backdoor that was eventually exploited. This scenario emphasized the critical importance of rigorous IAM control review and timely revocation of temporary permissions.

Attack Chain 3: Container Escape to Host Shell

The third attack chain focused on the elusive goal of container escape – breaking out of a container to gain access to the underlying host system. The task was to access the host file system and obtain a working shell on the worker node hosting the containers. As with previous scenarios, the cluster initially appeared robust.

Reconnaissance within the cluster led to the discovery of a privileged pod. This particular pod was a security tool designed to collect metrics, and thus legitimately required elevated permissions. The attackers gained a shell on this privileged pod. A critical misconfiguration was then identified: the pod was configured to mount the host file system onto the container. This allowed the attackers to pull the entire host file system into the compromised container, giving them extensive visibility into the node.

Initially, the client did not consider host file system access alone as a "working shell" on the node. Undeterred, the attackers delved deeper into the extracted host file system. They discovered and captured numerous Kubernetes Service Account (KSA) tokens. Among these, one KSA token had permissions to create pods. This was the game-changer. The attackers leveraged this KSA token to create their own malicious pod – described by Mahajan as a "suicidal bomb" – deliberately configured with all possible misconfigurations to facilitate a complete container breakout. This custom-crafted pod provided a working shell on the worker node, effectively compromising the host and granting access to all other pods and containers running on that node. This attack highlighted the dangers of overly permissive privileged pods and the critical impact of unmanaged KSA tokens found on the host file system.

Demo / Proof of Concept

▶ Watch: Defense in depth strategy (Build, Deploy, Run) (19:00)

While Sanjeev Mahajan did not conduct live demonstrations during his talk, he explicitly stated that the detailed attack chains presented were themselves the proof-of-concept. These were not theoretical exercises but rather scenarios encountered and exploited in real-world engagements with tier-one clients. Mahajan noted the inherent difficulty and risk of replicating such complex, real-world environments for live demos, and acknowledged past experiences where live demos had gone awry. Therefore, the comprehensive descriptions of the attack steps, misconfigurations, and exploitation techniques served as the practical demonstration of the vulnerabilities and their impact.

Defensive Implications

▶ Watch: Key takeaways for attackers, defenders, and organizations (22:00)

To counter the sophisticated attack vectors demonstrated, Sanjeev Mahajan advocated for a robust defense-in-depth strategy tailored to an organization's specific risk appetite. He segmented the application lifecycle within Kubernetes into three critical stages: Build, Deployment, and Run, outlining key security controls and tools for each.

Build Stage

The Build stage focuses on securing the creation and storage of container images. This is the foundation of container security.

  • Scan Base Images: Always scan your base images for vulnerabilities before they are used. These images form the bedrock of your containers, and any flaw here propagates throughout your application.
  • Sign Images: Implement digital signing for your container images. This ensures their integrity and authenticity, preventing tampering.
  • Trusted Container Registry: Push only verified, signed, and vulnerability-checked images to a trusted container registry.
  • Tools: Mahajan recommended tools like Trivy and Clair for vulnerability scanning, and Notary or Harbor for image signing and managing trusted registries.

Deployment Stage

The Deployment stage addresses how the cluster itself is provisioned, along with its associated IAM roles and secrets. This stage is frequently a source of misconfigurations exploited by attackers.

  • Secrets Management: Implement robust secrets management solutions. As demonstrated in the attack chains, attackers relentlessly target secrets within the cluster. Centralized and secure management of sensitive data is paramount.
  • IAM Controls: Continuously review and refine IAM controls. Mahajan stressed that IAM is complex ("a beast") and rarely configured perfectly on day one. Regular audits are essential to prevent over-privileging and unrevoked temporary access.
  • Network Policies: Enforce granular network policies to segment your cluster. This limits lateral movement even if a pod is compromised, reducing the blast radius.
  • Tools: Solutions like HashiCorp Vault or cloud provider KMS (Key Management Service) are critical for secrets management. Open Policy Agent (OPA) can help enforce IAM and other configurations as code. Calico and Cilium are powerful tools for implementing advanced network policies.

Runtime Stage

The Runtime stage focuses on securing applications as they are actively running within the containerized workloads.

  • Periodic Security Assessments: Conduct periodic and regular security assessments. These are crucial for identifying new vulnerabilities and misconfigurations that may emerge as the environment evolves.
  • Security Policies (Enforced Mode): Implement security policies in enforced mode, not merely audit mode. Mahajan explicitly warned against the common practice of putting policies in audit mode, which provides no real protection. Policies must actively block or prevent non-compliant actions.
  • Runtime Threat Detection: Deploy runtime threat detection tools within containers. These tools monitor container behavior in real-time to detect and respond to active attacks, such as container escapes or unauthorized process execution.
  • Tools: Twistlock, Falco, and Sysdig were mentioned as effective tools for runtime threat detection and enforcement.

By integrating these controls across the entire lifecycle, organizations can build a resilient defense posture that can withstand the types of attacks demonstrated, significantly reducing their attack surface and improving their overall security posture.

Key Takeaways

  • Kubernetes is NOT Secure by Design/Default: Organizations must abandon the myth that Kubernetes is inherently secure. The vast majority (90%) of security findings stem from misconfigurations, not platform flaws.
  • Shared Responsibility is Critical: Understand and actively manage your responsibilities in the shared security model. While CSPs secure the underlying infrastructure, customers are accountable for cluster configuration, IAM, network policies, and data security.
  • Integrating Assets are High-Value Targets: Attackers will look beyond the Kubernetes cluster itself. CI/CD pipelines, source code repositories, and other integrated cloud assets are often softer targets that can provide a path to cluster compromise.
  • Minor Misconfigurations Have Major Impact: Seemingly small configuration errors, like confusing get Secrets with list Secrets or failing to revoke temporary IAM permissions, can lead to complete cluster compromise or sensitive data exfiltration.
  • Defense-in-Depth is Essential: Implement a comprehensive defense-in-depth strategy across the Build, Deployment, and Runtime stages. This includes image scanning, robust secrets management, strict IAM, granular network policies, and runtime threat detection.
  • Regular Assessments are Non-Negotiable: Conduct frequent offensive and defensive security assessments by trained professionals. These external perspectives are crucial for identifying blind spots and validating the effectiveness of security controls in complex Kubernetes environments.

About the Speaker(s)

Sanjeev Mahajan is a Principal Security Engineer with Cyber Services. He brings over 15 years of industry experience, with the last decade dedicated specifically to the field of security. Mahajan began his career as a system administrator before transitioning into security. For several years, he has been heavily involved in the world of Kubernetes, gaining extensive experience from both an attacker's and a defender's perspective. His deep understanding of Kubernetes vulnerabilities and defense strategies stems from hands-on work in real-world engagements, making him a knowledgeable and practical voice in cloud-native security.

Reviews

→ Top-rated talks at BSides Canberra VII (2024)

All talks from BSides Canberra VII (2024)