Skip to content
Access control Write-up Advanced

Google Cloud Build — under the hood

The researcher found that Cloud Build VMs could communicate with each other over IPv4, and that the ALTS/gRPC control plane session could be relayed to another VM, potentially allowing a malicious build to hijack a neighbour's control plane session. However, no direct exploitation was achieved, and Google later blocked inter-VM communication.

Imre Rad Follow

Published on irsl.medium.com

This story began shortly after I published an advisory about a DHCP related flaw that affected Google’s Compute Engine. Dávid Schütz reached out and kindly asked me to review whether my finding affects Cloud Build or not: IPv4 network communication between VMs created for the Cloud Build jobs was not restricted at all.

Imre Rad, on irsl.medium.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. 12 min read.

Context

Cloud Build is Google's managed build service. When you submit a build, the control plane creates a VM for the job and dispatches work to a process called worker_main running on that VM. The worker process listens on port 1232 and speaks gRPC over ALTS (Application Layer Transport Security), Google's alternative to TLS. The control plane's identity is [redacted], and the worker runs as cloudbuild-untrusted@ on each host. The security boundary is meant to be at the VM level: running arbitrary code inside the build container is expected, but one build's VM should not be able to affect another's.

This research started after the author published an advisory about a DHCP-related flaw in Compute Engine. Dávid Schütz asked whether that finding affected Cloud Build, noting that IPv4 communication between Cloud Build VMs was not restricted at all. The author confirmed that the IPv4 stack is configured by systemd's DHCP client, not ISC's, though ISC's dhclient was also started but limited to IPv6. After reviewing DHCPv6 and the ISC implementation, the author found that direct IPv6 packets between Cloud Build hosts are not delivered, so that avenue was abandoned. (IPv6 support is not available to customers in Google's VPC, at least at the time of writing.)

Setup

The researcher used two Cloud Build VMs in two different projects, kept recreating them until they landed on the same subnet, and used a set of custom tools:

The worker process runs as cloudbuild-untrusted@ and the control plane's identity is [redacted]. The worker listens on port 1232 for gRPC over ALTS. The worker also listens on port 8081, and frontend_main is started with --worker_url http://[redacted]:8081.

Finding it

The control plane communicates with the worker binary on port 1232. A netstat-style line showed:

Text
tcp ESTAB 0 0 [[redacted]::]:1232
 [[redacted]]:45738

This is a gRPC service protected by ALTS. The researcher captured packets on Cloud Build and dissected the bytes with protoc, comparing two handshake pairs. The client init messages differed in one field:

Text
root@f4297f8cd9e5:/data/alts/gorpc/grpc-go/examples/route_guide# diff
 /data/alts/lo1-clientinit.bin.decoded
 /data/alts/lo2-clientinit.bin.decoded
 1c1
 < 1: "\222\310>\307,\000\3773\014\003H\033@X\326Cq\242\236Y@{\237\256\177\207k\232\334\024\316y"
 — -
 > 1: "ma@\333\224\215/\367\221\022\2477\231O\246\027lw&\370\265\275f\006\250\324\206%\366\266E\001"

Similarly, the server init messages differed only in tag 1:

Text
root@f4297f8cd9e5:/data/alts/gorpc/grpc-go/examples/route_guide# diff
 /data/alts/lo1-serverinit.decoded /data/alts/lo2-serverinit.decoded
 1c1
 < 1: "\240\1770>\373\026_q\302\027\224\253W(]\372>K\210\247<\221\027\\\355\021\357\205\314%\222~"
 — -
 > 1: "\302m SF\367\267r\304.\275\353j\377+2\257\266\221x\005E\267\310\267\343}Jw\242T="

Since the documentation mentions a DH handshake and the blobs are 32 bytes long, the researcher initially suspected these were DH public keys and that the protocol might be vulnerable to a man-in-the-middle attack. Later he realised the fields are session IDs (ClientSessionID, ServerSessionID), and the DH private key is static and assigned to the certificate itself, with the metadata server doing lookups in the background. This matches the documentation and explains why perfect forward secrecy is not enabled by default. That line of inquiry was dropped.

With ALTS tooling in hand, the researcher found that the worker process runs as cloudbuild-untrusted@ and the control plane's identity is [redacted]. A handshaker server log showed a successful handshake:

Text
root@worker-f7bca60b-52af-4bac-96c7-e197984ab699:/tmp#
 ./handshakerserver -l [redacted]:1232
 <97984ab699:/tmp# ./handshakerserver -l [redacted]:1232
 2021/07/08 15:03:17 helo
 2021/07/08 15:03:17 Listening on [redacted]:1232
 2021/07/08 15:03:18 ClientInit received: 1394
 2021/07/08 15:03:18 initial handshake with the handshaker service has succeded
 2021/07/08 15:03:18 length of ServerInit+ServerFinished OutFrames: 570
 2021/07/08 15:03:18 Sending 570 bytes to the upstream service
 2021/07/08 15:03:18 Received 74 bytes from the upstreamServiceConn
 service — probably ServerInit+ServerFinished
 2021/07/08 15:03:18 ApplicationProtocol: grpc
 2021/07/08 15:03:18 RecordProtocol: ALTSRP_GCM_AES128_REKEY
 2021/07/08 15:03:18 SecurityLevel: INTEGRITY_AND_PRIVACY
 2021/07/08 15:03:18 PeerServiceAccount: [redacted]
 2021/07/08 15:03:18 LocalServiceAccount:
 [redacted]
 2021/07/08 15:03:18 PeerRPCVersions: max_rpc_version:{major:2
 minor:1} min_rpc_version:{major:2 minor:1}
 0 50 52 49 20 2A 20 48 54 54 50 2F 32 2E 30 0D 0A PRI * HTTP/2.0..
 16 0D 0A 53 4D 0D 0A 0D 0A ..SM….
 0 00 00 06 04 00 00 00 00 00 00 06 02 00 00 00 ……………

The handshake succeeds to another Cloud Build host with the cloudbuild-untrusted@ identity (for example [redacted]). The researcher built an ALTS proxy that terminates an ALTS session, deciphers the data, and forwards it to an upstream ALTS server. He wanted to see whether gRPC method calls are accepted if the client is the untrusted identity. They were rejected: the TCP session was aborted around the PRI message.

Exploitation

Step 1: Tunnel the TCP channel

The next idea was to tunnel the whole TCP channel to another host without modification. The handshake must succeed because the protocol verifies identities, not where the workload is running, and the target ALTS server would see the peer's identity as the expected cloud-build-argo-foreman@.... The open question was whether there are gRPC-level checks on the VM's identity.

The researcher spun up two Cloud Build VMs in two different projects on the same subnet. As the first step of a build job, he killed the real worker process and started a socat proxy to the other VM he controlled. He watched netstat and the worker logfile /argologs/worker. The TCP connection from the socat tunnel established successfully and stayed alive for a long time, so the real worker process was happy with the session and did not terminate it. Nothing interesting was emitted to the logfile.

The motivation for this attack was one of the following:

  • On the gcloud client side, seeing some lines of the output of the job running on the target (neighbour) VM.
  • The control plane dispatching the next step of the build job to the target (neighbour) VM instead of the expected one.

Step 2: Reconstruct the proto definitions

To understand the gRPC protocol, the researcher built go-reproto to extract proto definitions from Go binaries. The reconstructed worker.proto is shown in the report (the report does not reproduce its contents in text).

Step 3: Patch the authorization check

The main attack idea was to abuse ALTS and forward a legitimate session to a victim machine, tricking the control plane into redispatching the job. ALTS alone would not prevent this. The researcher improved his older InsecureSkipVerify patching project so it could patch running binaries on the fly. This was needed because restarting worker_main shut down the VM almost immediately. He developed a patch for worker_main to disable the authorization check, so gRPC methods could be called even as cloudbuild-untrusted@. The patch targets void google3/third_party/golang/grpc/credentials/alts/alts.ClientAuthorizationCheck(void):

Bash
./mempatcher $(pidof worker_main) 20000f85ac000000 2000e9ad00000090

With the patch, he could inspect the methods of the Worker gRPC service in worker_main. He was able to call:

  • BuildStatus
  • WorkerStatus
  • BuildLog
  • BuildSummary
  • CancelBuild
  • Diagnostics

He also crashed worker_main by sending a malformed gRPC message to SubmitBuild:

Text
google3/cloud/build/vm/agents/worker/pkg/worker.(*Worker).ValidateBuild(0xc00030cd00,
 0x0, 0x1, 0x1)
 cloud/build/vm/agents/worker/pkg/worker.go:334 +0x28

This was not interesting on its own, because the authorization layer would normally prevent malicious parties from sending such a request.

Step 4: Relay a control plane session to a victim

The researcher built a toolpack that:

  1. Launches two builds in two different projects (victim and attacker), recreating them until they are on the same subnet.
  2. Patches worker_main on the victim and sleeps.
  3. Kills worker_main on the attacker machine and starts a special ALTS/gRPC server in relayer mode, which terminates ALTS and relays communication to an upstream ALTS server (the victim).

This let him inspect how a victim worker_main would respond to a hijacked or redirected control plane session. The result: nothing special. The control plane sends only BuildStatus and WorkerStatus messages, each with a single integer status field. At the end of a build, both WorkerStatus.Status and BuildStatus.Status are 3. (The enum definitions are documented officially.)

He built another ALTS/gRPC server to respond with arbitrary (Worker|Build)Status messages, hoping the control plane would fall back to an early init phase on values like 0, 1, or -1 and then call BuildLog or SubmitBuild. It did not care at all.

He noticed that sending a malformed gRPC response to either BuildLog or WorkerLog makes the control plane initiate the tier-down process of the VM, the same as at build timeouts. This chain invokes BuildSummary, Diagnostics, then google.bytestream.ByteStream/Read with three files: startup, worker, and docker.log. He thinks (but did not verify) this is the best he could accomplish with the original attack idea: reading those three files from a victim VM. Since they would show up only in the control plane, he believed Google would not be interested, so he did not implement this attack.

He verified that ByteStream/Read gRPC methods could be called as the untrusted user, but the interceptor responsible for authorizing the worker methods is the same, so such calls are rejected the same way.

Step 5: Review how source artifacts are fetched

Besides ALTS, the researcher reviewed how source artifacts are fetched by Cloud Build VMs, which all run as cloudbuild-untrusted@. The design trick is as follows:

When you invoke the Cloud Build submit API, the control plane registers the job along with the service account to be used. This defaults to [PROJECT-ID]@cloudbuild.gserviceaccount.com, created when the API was activated, but can be overridden in the same submit call. A VM is created for the build job, running as cloudbuild-untrusted with empty OAuth scopes. The control plane then invokes the ALTS/gRPC server listening on port 1232 in worker_main over IPv6, and calls Worker.SetToken() with an access token created for the desired service account. worker_main fetches the fake metadata server Docker image, then sends a POST request to the /token URI with the same token, so the fake metadata server starts serving it through the standard locations. Then the control plane invokes another gRPC method of worker_main (still port 1232), Worker.SubmitBuild, which contains the build steps (which Docker image to run, what commands to execute, etc.). These containers are created in the same Docker virtual network namespace as the fake metadata server, along with a host alias, so any standard tool obtaining an access token from the metadata server through the standard hostnames (metadata.[redacted]) is routed to the fake one. From the end user's point of view, everything just works. The researcher found no security concerns here.

Step 6: The SetToken DoS idea

Weeks later, the researcher started building an attack that abuses the SetToken gRPC method, which is invoked every hour if the build runs long enough. The idea was to forward that particular request to a neighbour VM, causing a DoS because the victim would not be able to upload artifacts with the unexpected access token. Since SetToken is wrapped with aggressive retry logic, this would have allowed an attacker to take down the whole Cloud Build plant easily. While everything was prepared and he started launching the attack against another VM he controlled, he found that VMs could no longer communicate with each other: Google had changed something recently. He also checked the WorkPool feature, which allows attaching these VMs to a VPC of yours, and the same network-level change had been applied there: VMs cannot see each other anymore.

Step 7: Inspecting gRPC at the HTTP/2 layer

The researcher built golang-http2debug-onthefly to inspect gRPC calls at the HTTP/2 layer. An example log:

The DirectPath header suggests this technology is used for other Google products as well.

Step 8: Port 8081

The worker_main process also listens on port 8081. frontend_main is started with --worker_url http://[redacted]:8081. Sending any HTTP request to this port interrupts the TCP connection immediately without returning any HTTP response. Nothing is logged in the worker_main logfiles. The researcher looked into reversing the binaries with Ghidra, but analysing large Go binaries is not easy, and the strings were generic, so he could not find the reason for the connection termination in a reasonable amount of time.

Root cause

The core issue is that ALTS authenticates identities, not the location of the workload. The handshake verifies that the peer is [redacted], but it does not verify that the peer is running on the expected VM. If an attacker can tunnel a TCP connection from the control plane to a different VM, the target ALTS server will accept the session because the peer's identity is correct. The gRPC-level authorization check (ClientAuthorizationCheck) rejected calls from the untrusted identity, and it could be bypassed by patching the running binary. The researcher found that VMs could no longer communicate with each other: Google had changed something recently.

Impact

The researcher relayed a control plane session to a victim VM and saw nothing special: the control plane only sends BuildStatus and WorkerStatus messages. The SetToken DoS idea could have allowed an attacker to take down the whole Cloud Build plant easily, but while he started launching the attack he found VMs could no longer communicate with each other. The ByteStream/Read chain could have allowed reading three log files from a victim VM, but the researcher did not implement it because he believed Google would not be interested. The SubmitBuild crash was not interesting because the authorization layer would normally prevent it. Overall, the research yielded one VRP submission for a missing protection in another Google product, but its triage was still in progress at the time of writing, so no details are shared. The researcher also found that discovery documents of services hosted via googleapis.com are not necessarily in line with the API methods they actually expose, and a promising follow-up research is in progress.

Fix

The researcher found that Cloud Build VMs could no longer communicate with each other, and the same network-level change had been applied to the WorkPool feature. The researcher did not identify a code fix for the ALTS or gRPC layers; the network-level isolation is the effective mitigation.

Variants to test

  • On other Google products that use ALTS and DirectPath, check whether VMs or workloads can still reach each other on the internal network. A positive result is a successful TCP connection between two workloads that should be isolated.
  • Test whether the ClientAuthorizationCheck can be bypassed by patching the running binary, as done here with mempatcher. A positive result is a successful gRPC call from an untrusted identity.
  • Look for gRPC services that rely on ALTS identity alone without additional VM-level checks. A positive result is a relayed session being accepted by the target.
  • Check whether SetToken or similar token-refresh methods are invoked periodically and whether they can be redirected. A positive result is a victim failing to upload artifacts.
  • Compare discovery documents with actual API methods. A positive result is a method that is exposed but not documented, or vice versa.

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. 26 min read.

What happened, in plain words

This is the story of a security researcher poking at Google Cloud Build, a service that builds software for you in the cloud. He did not publish a single dramatic bug that let him break into other people's data. What he did find was a lot of interesting detail about how the service works internally, a few weaknesses, and one change Google made to its network that stopped his later attack. He also built several free tools along the way and published them.

To follow the story you only need a browser and some patience. I will explain every technical word the first time it appears, and I will show the exact commands and outputs from the research, then walk through them line by line.

A few ideas to have in your head before we start:

  • A server is just a computer somewhere that answers requests from other computers. When you open a website, your browser is the client and the website's computer is the server.
  • A virtual machine (VM) is a computer simulated inside a bigger computer. Google rents out thousands of these. Each one behaves like a separate machine with its own network address.
  • A network address (IP address) is like a postal address for a computer. There are two common versions: IPv4 (shorter, like [redacted]) and IPv6 (longer, like 2600:2d00:4001:...).
  • A port is like an apartment number at that address. One machine can run many services, each listening on a different port number.
  • A protocol is an agreed set of rules for how two computers talk. Like agreeing whether to speak English or French on the phone before you start.
  • An API (Application Programming Interface) is a menu of actions one program offers to another. Instead of a human clicking buttons, one program sends a named request ("start a build", "give me the status") and gets a structured answer back.
  • gRPC is a popular way for programs to call each other's APIs. It is efficient and structured, and it is what Cloud Build uses internally.
  • TLS is the encryption that puts the padlock in your browser. It scrambles traffic so eavesdroppers cannot read it and also proves the server's identity.
  • ALTS (Application Layer Transport Security) is Google's own alternative to TLS, used inside its data centres. It does the same two jobs: encrypt the traffic and prove who is on each end.
  • A token is a short-lived password-like string that proves you are allowed to do something. Like a wristband at a festival that gets you into the VIP area for the evening.
  • A service account is a robot user account, not tied to a human. Programs log in as service accounts the same way people log in as themselves.
  • A man-in-the-middle (MitM) attack is when an attacker secretly sits between two parties and relays their conversation, possibly reading or altering it. Like a postal worker who opens your letters, copies them, and reseals them before delivery.
  • A denial of service (DoS) is an attack that does not steal data but stops a service from working. Like blocking the entrance to a shop so customers cannot get in.

The starting point: a question from a colleague

The story began shortly after the researcher published an advisory about a flaw related to DHCP in Google's Compute Engine. DHCP is the system that hands a computer its network address automatically when it joins a network, like a hotel reception assigning you a room number when you check in. His earlier finding was about that hand-out process.

A colleague, Dávid Schütz, got in touch and asked a simple question: does that finding also affect Cloud Build? He had noticed something relevant: the IPv4 network communication between the VMs created for Cloud Build jobs was not restricted at all. In other words, one build's machine could talk freely to another build's machine over the older IPv4 addressing scheme.

The researcher was quick to add context. Running arbitrary code on the host level of these VMs is not a big deal, because the Docker socket is available by design. Docker is the tool that runs the build containers, and the socket is the control channel to it. So the security boundary is meant to be at the VM level: it is fine for code inside a build to do whatever it likes inside its own machine, but one build's VM should not be able to affect another's.

He then checked how the network was actually configured. It turned out that the IPv4 stack is configured by systemd's DHCP client, not by the older ISC one. Systemd is a common Linux program that starts and manages other programs; ISC is the organisation behind a classic DHCP client called dhclient. ISC's dhclient was also started, but limited to IPv6 only.

Since he did not have much experience with DHCPv6, he went back to the relevant RFCs (the official documents that define internet protocols), took some packet captures (recordings of network traffic), and looked into the ISC implementation, especially how it validates DUIDs. A DUID is a unique identifier a machine presents when asking for an IPv6 address, a bit like showing ID at reception. He wanted to know whether his earlier exploit could be ported to DHCPv6.

He believed it should work with DHCPv6 as well, but he also found in the meantime that direct IPv6 packets between Cloud Build hosts are not delivered. So he had to give up on that avenue. He added a note: IPv6 support is not available for customers in Google's VPC (Virtual Private Cloud, Google's private network for your resources), at least at the time of writing.

Looking around Cloud Build

Even though the DHCP angle was closed, Cloud Build was now on his list, so he decided to prioritise it and started looking around.

The first thing he noticed was the control plane talking to the worker binary on port 1232. The control plane is the part of the service that makes decisions and hands out work; the worker is the part that actually does the work on each machine. He guessed this is how jobs are dispatched. A netstat-style line showed the connection:

Text
tcp ESTAB 0 0 [[redacted]::]:1232
 [[redacted]]:45738

Line by line:

  • tcp means this is a TCP connection. TCP is the reliable delivery protocol underneath most internet traffic: it makes sure bytes arrive in order, like a courier who numbers every parcel.
  • ESTAB means the connection is established and currently open.
  • The two 0 0 are queue sizes, not important here.
  • [[redacted]::]:1232 is one end: an IPv6 address in square brackets, then a colon, then port 1232. This is the worker side, listening on port 1232.
  • [[redacted]]:45738 is the other end: the control plane's IPv6 address, connecting from port 45738. The high, random-looking port number is typical for the side that starts a connection.

This line belongs to a gRPC service protected by ALTS. The researcher was unfamiliar with ALTS too, so he started looking into it. He did some real packet captures on Cloud Build and dissected the bytes on the wire using protoc, the compiler for protobuf. Protobuf is a compact way of encoding structured data; protoc can decode it back into readable form. He compared a couple of message pairs.

First, the client init messages (the first message the client sends during the handshake):

Text
root@f4297f8cd9e5:/data/alts/gorpc/grpc-go/examples/route_guide# diff
 /data/alts/lo1-clientinit.bin.decoded
 /data/alts/lo2-clientinit.bin.decoded
 1c1
 < 1: "\222\310>\307,\000\3773\014\003H\033@X\326Cq\242\236Y@{\237\256\177\207k\232\334\024\316y"
 — -
 > 1: "ma@\333\224\215/\367\221\022\2477\231O\246\027lw&\370\265\275f\006\250\324\206%\366\266E\001"

Line by line:

  • The first line is a shell prompt: root@f4297f8cd9e5 means the user is root (the administrator) on a machine named f4297f8cd9e5, and the # shows a command follows. The path is just where he was working.
  • diff is a standard tool that compares two files and shows the differences.
  • The two files are two decoded client init messages, lo1 and lo2, from two different captures.
  • 1c1 is diff's way of saying "line 1 of the first file should be changed to line 1 of the second file".
  • The < line is what was in the first file: field 1 holding a 32-byte blob, shown with escape codes because the bytes are not printable text.
  • The — - line is just a separator.
  • The > line is what was in the second file: the same field 1, but a different 32-byte blob.

So the only difference between the two client init messages is that one field.

Similarly, the server init messages differ in tag 1 only:

Text
root@f4297f8cd9e5:/data/alts/gorpc/grpc-go/examples/route_guide# diff
 /data/alts/lo1-serverinit.decoded /data/alts/lo2-serverinit.decoded
 1c1
 < 1: "\240\1770>\373\026_q\302\027\224\253W(]\372>K\210\247<\221\027\\\355\021\357\205\314%\222~"
 — -
 > 1: "\302m SF\367\267r\304.\275\353j\377+2\257\266\221x\005E\267\310\267\343}Jw\242T="

This is the same kind of comparison, but for the server's first message. Again, only field 1 differs, and again it is a 32-byte blob.

Since the documentation talks about a DH handshake, and since these blobs are 32 bytes long, he concluded that this must be a DH "pubkey". DH stands for Diffie-Hellman, a clever mathematical trick that lets two parties agree on a shared secret over an open channel, like two people mixing paint in public and ending up with the same colour without anyone else being able to reproduce it. A "pubkey" is the public half of that exchange. If the only thing that changes between sessions is a public key, he started suspecting the protocol might be vulnerable to a man-in-the-middle attack.

It did not feel right, given the protocol had been reviewed formally. Still, this is business as usual in security research, so he kept digging, even though he felt it would be a waste of effort. Later he realised why the white paper says perfect forward secrecy is not enabled by default. Perfect forward secrecy is a property where even if an attacker steals the long-term secret key later, they still cannot decrypt past conversations. The fields above are not public keys at all: they are some kind of session IDs (ClientSessionID, ServerSessionID), and the DH private key is actually static and assigned to the certificate itself, with the metadata server doing some magic lookups in the background. The metadata server is a special internal service that hands out information to VMs, including credentials. This explanation matches the documentation and makes much more sense overall, so he gave up on that line too.

Getting a foothold with ALTS tooling

By this point he already had a bunch of ALTS-related tools. He found that the worker process runs as the identity cloudbuild-untrusted@ on each Cloud Build host, and the control plane's identity is [redacted]. An identity here is like a name badge: ALTS checks it during the handshake.

He ran his own handshaker server to see what a real handshake looks like from the worker's side:

Text
root@worker-f7bca60b-52af-4bac-96c7-e197984ab699:/tmp#
 ./handshakerserver -l [redacted]:1232
 <97984ab699:/tmp# ./handshakerserver -l [redacted]:1232
 2021/07/08 15:03:17 helo
 2021/07/08 15:03:17 Listening on [redacted]:1232
 2021/07/08 15:03:18 ClientInit received: 1394
 2021/07/08 15:03:18 initial handshake with the handshaker service has succeded
 2021/07/08 15:03:18 length of ServerInit+ServerFinished OutFrames: 570
 2021/07/08 15:03:18 Sending 570 bytes to the upstream service
 2021/07/08 15:03:18 Received 74 bytes from the upstreamServiceConn
 service — probably ServerInit+ServerFinished
 2021/07/08 15:03:18 ApplicationProtocol: grpc
 2021/07/08 15:03:18 RecordProtocol: ALTSRP_GCM_AES128_REKEY
 2021/07/08 15:03:18 SecurityLevel: INTEGRITY_AND_PRIVACY
 2021/07/08 15:03:18 PeerServiceAccount: [redacted]
 2021/07/08 15:03:18 LocalServiceAccount:
 [redacted]
 2021/07/08 15:03:18 PeerRPCVersions: max_rpc_version:{major:2
 minor:1} min_rpc_version:{major:2 minor:1}
 0 50 52 49 20 2A 20 48 54 54 50 2F 32 2E 30 0D 0A PRI * HTTP/2.0..
 16 0D 0A 53 4D 0D 0A 0D 0A ..SM….
 0 00 00 06 04 00 00 00 00 00 00 06 02 00 00 00 ……………

Line by line:

  • The first two lines are the shell prompt and the command. ./handshakerserver runs his own program; -l [redacted]:1232 tells it to listen on all network interfaces on port 1232. The <97984ab699:/tmp# is just a slightly garbled repeat of the prompt in the captured output.
  • helo is a greeting printed by his tool.
  • Listening on [redacted]:1232 confirms it is now waiting for connections.
  • ClientInit received: 1394 means the client sent its first handshake message, 1394 bytes long.
  • initial handshake with the handshaker service has succeded means his tool talked to Google's handshaker service (the helper that performs the cryptographic part of ALTS) and the first step worked.
  • length of ServerInit+ServerFinished OutFrames: 570 and Sending 570 bytes to the upstream service mean the server's reply is 570 bytes and was forwarded.
  • Received 74 bytes from the upstreamServiceConn service — probably ServerInit+ServerFinished means the other side sent back 74 bytes, likely the final part of the handshake.
  • ApplicationProtocol: grpc says the agreed application protocol is gRPC.
  • RecordProtocol: ALTSRP_GCM_AES128_REKEY names the encryption scheme used for the records (the actual data). GCM is a common authenticated encryption mode; AES128 is the key size; REKEY means keys are refreshed.
  • SecurityLevel: INTEGRITY_AND_PRIVACY means the connection is both tamper-proof (integrity) and encrypted (privacy).
  • PeerServiceAccount: [redacted] is the identity of the other end, the control plane.
  • LocalServiceAccount: [redacted] is the identity of his own side, the worker.
  • PeerRPCVersions: max_rpc_version:{major:2 minor:1} min_rpc_version:{major:2 minor:1} says both sides support RPC version 2.1.
  • The last three lines are the first bytes of the actual application data, shown in hex and as text. PRI * HTTP/2.0 is the standard opening of an HTTP/2 connection. HTTP/2 is the modern version of the protocol your browser uses; gRPC runs on top of it. The SM and the following bytes are the start of HTTP/2's settings frame.

This opens a couple of attack vectors. Using another tool of his, he noted that the handshake succeeds to another Cloud Build host with his cloudbuild-untrusted@ identity (for example [redacted]). In other words, a worker can complete an ALTS handshake with another Cloud Build host using its own worker identity.

Since the underlying protocol was unknown at this point, he built an ALTS proxy tool that can terminate an ALTS session, decipher the data, and forward it to an upstream ALTS server. Think of it as a translator standing between two people: it listens to one, decrypts what it hears, and re-encrypts it for the other side. He wanted to verify whether gRPC method calls are accepted if the client is the "untrusted" identity. They were rejected: the TCP session was aborted around the PRI message. So the server rejected the calls even though the identity was valid.

The main attack idea: relaying a session

His next idea was simpler and more promising. Instead of trying to call methods himself, he would simply tunnel the whole TCP channel to another host without any modifications. The handshake must succeed, because the protocol was designed to verify identities only, not where the workload is running. The target ALTS server would see the peer's identity as the expected one (cloud-build-argo-foreman@...). The open question was whether there are any gRPC-level checks to verify the VM's identity somehow.

To test this, he put together some tooling to spin up two Cloud Build VMs (using two different projects) that are on the same subnet, so the two hosts could communicate. A subnet is a slice of a network where machines can reach each other directly, like houses on the same street.

As the first step of a build job, he killed the real worker process and started a socat proxy instead, pointing to the other VM he controlled. socat is a general-purpose tool that connects two data streams together, like a pipe joining two hoses. He was watching netstat output and the logfile of the worker at /argologs/worker.

The TCP connection from his socat tunnel established successfully and was kept alive for a long time. He concluded that the "real" worker process was happy with this session and did not terminate it. Unfortunately nothing interesting was emitted to the logfile.

The motivation for this attack was one of the following:

  • On the "gcloud client side", seeing some lines of the output of the job that is running on the target ("neighbour") VM. gcloud is Google's command-line tool; the client side is where the user watches their build.
  • The control plane dispatching the next step of the build job to the target ("neighbour") VM instead of the expected one.

Reconstructing the protocol definition

As a next step, he started focusing on understanding the underlying gRPC protocol. Since he plans to work on Google targets in the future, and this is a recurring topic (he mentions he is going to publish another write-up about findings at the Cloud SQL product), he decided to build a tool to extract proto definitions from Go binaries. Go is a programming language; a binary is the compiled program. Proto definitions are the descriptions of what messages and methods an API has, like a menu. He published the tool here: https://github.com/irsl/go-reproto

It is far away from perfect, but it is definitely exciting from a security research point of view. The worker.proto file reconstructed by the tool is shown in the report.

Patching the running program

Remember, his main attack idea was to abuse ALTS and forward a legitimate session to a victim machine. He wanted to trick the control plane into redispatching the job, hoping to achieve code execution that way. ALTS alone would not prevent this.

He also improved an older project of his (which was created to turn on InsecureSkipVerify, a setting that tells a program to skip checking the other side's certificate) so that it is now capable of patching running binaries on the fly. This was needed because he could not restart worker_main; if he did so, it shut down the VM almost immediately.

He developed a patch for worker_main to disable the authorization check, so he could call gRPC methods even as cloudbuild-untrusted@. The patch targets void google3/third_party/golang/grpc/credentials/alts/alts.ClientAuthorizationCheck(void). That long name is just the internal function that decides whether a caller is allowed. Disabling it is like removing the bouncer from the door.

Bash
./mempatcher $(pidof worker_main) 20000f85ac000000 2000e9ad00000090

Line by line:

  • ./mempatcher runs his patching tool.
  • $(pidof worker_main) runs the pidof command first, which prints the process ID (a number the operating system uses to identify a running program) of worker_main. The $(...) syntax substitutes that number into the command. So the tool knows which running program to modify.
  • 20000f85ac000000 is the original sequence of bytes in memory that the tool should look for.
  • 2000e9ad00000090 is the replacement sequence. In machine code, these bytes change the instructions so the authorization check no longer blocks the call.

This way, he was able to inspect the methods of the Worker gRPC service of worker_main. He was able to call the following methods:

  • BuildStatus
  • WorkerStatus
  • BuildLog
  • BuildSummary
  • CancelBuild
  • Diagnostics

These names are self-explanatory: they report status, fetch logs, summarise a build, cancel it, or run diagnostics.

He managed to crash worker_main by sending a malformed gRPC message to SubmitBuild:

Text
google3/cloud/build/vm/agents/worker/pkg/worker.(*Worker).ValidateBuild(0xc00030cd00,
 0x0, 0x1, 0x1)
 cloud/build/vm/agents/worker/pkg/worker.go:334 +0x28

Line by line:

  • The first line is a stack trace entry: it names the function ValidateBuild on the Worker type, in the package worker, and shows the arguments it was called with (0xc00030cd00, 0x0, 0x1, 0x1). A stack trace is the list of function calls that led to a crash, like a receipt showing every step.
  • The second line points to the source file worker.go, line 334, plus an offset +0x28 into the compiled code.

This was not an interesting bug on its own, because the authorization layer would normally prevent malicious parties from sending such a request.

Relaying a control plane session to a victim

He built a toolpack which does the following:

  1. Launches two builds in two different projects (victim and attacker), and keeps recreating them until they are on the same subnet.
  2. Patches worker_main on the victim and sleeps.
  3. Kills worker_main on the attacker machine and starts a special ALTS/gRPC server in relayer mode, which terminates ALTS and relays communication to an upstream ALTS server (the victim).

This attack allowed him to inspect how a victim worker_main process would respond if it got a hijacked or redirected control plane session. In short: he saw nothing special. He learned the control plane sends BuildStatus and WorkerStatus messages only. Both of them have only one field defined, an integer status. At the end of a build, both WorkerStatus.Status and BuildStatus.Status are 3. Later he found the definition of these enums documented officially.

He built another ALTS/gRPC server to respond with arbitrary (Worker|Build)Status messages. He was hoping the control plane would fall back to an early init phase if it received 0, 1, -1 or a similar special value, and would then call BuildLog or SubmitBuild, but it did not care at all.

He noticed that by sending a malformed gRPC response to either BuildLog or WorkerLog, the control plane initiates the tier-down process of the VM, which is effectively the same as at build timeouts. This is a chain of invoking the following methods: BuildSummary, Diagnostics, then google.bytestream.ByteStream/Read with 3 files: startup, worker and docker.log. He thinks (but did not verify) this is the best he could accomplish by mounting the original attack idea: reading out these 3 files of a victim VM. Still, since they would show up only in the control plane, he believes Google would not be interested, so he decided not to implement this attack.

He verified if these ByteStream/Read gRPC methods could be called as the untrusted user, but the interceptor responsible for authorization of the worker methods is the same, so such calls are rejected the same way.

How source code gets into the build

Besides ALTS, he also reviewed how the source artifacts are fetched by the Cloud Build VMs. They are all running as cloudbuild-untrusted@, so what is the design trick that prevents access to files of another project's buckets? A bucket is a storage container in the cloud, like a folder with permissions.

After putting together the pieces (the SetToken gRPC method and the fake metadata server), he realised he could not find any security concerns. Here is how it works, in his words:

When you invoke the Cloud Build submit API, the control plane registers the job along with the service account to be used. This defaults to the one that was created when you activated the API on your project, [PROJECT-ID]@cloudbuild.gserviceaccount.com, but can be overridden in the same submit API call. Then a VM is created for your build job, running as cloudbuild-untrusted with empty OAuth scopes. OAuth scopes are a list of permissions attached to a credential; empty means the credential itself can do almost nothing.

The control plane then invokes the ALTS/gRPC server listening on port 1232, implemented in the worker_main process, through the IPv6 network, and invokes the Worker.SetToken() gRPC method with an access token that was created for the desired service account the job is going to be running as. The worker_main process in turn fetches the fake metadata server Docker image, then sends a POST request to the /token URI along with the same token, so the fake metadata server starts serving that through the standard locations. A POST request is one of the basic HTTP methods, used to send data to a server. A URI is a path on a server, like /token.

Then the control plane invokes another gRPC method of worker_main (port 1232 still), that is Worker.SubmitBuild, which actually contains the build steps (which Docker image to run, what commands to execute, etc.). These Docker containers are created in the same Docker virtual network namespace as the fake metadata server, along with a host alias, so any standard tools that obtain an access token from the metadata server through the standard hostnames (metadata.[redacted]) are actually routed to the fake one. A network namespace is an isolated private network inside a machine; a host alias is a nickname that points to a particular address. From the end user's point of view, everything just works.

The SetToken denial-of-service idea

A few weeks later, driven by a new idea, he started putting together an attack that abuses the SetToken gRPC method on Cloud Build, which is invoked every hour if the build is running for long enough. The idea was to forward that particular request to a neighbour VM, effectively causing a DoS, because the victim would not be able to upload artifacts with the "unexpected" access token. Artifacts are the files a build produces and uploads at the end.

Given the SetToken method is wrapped with an aggressive retry logic, this would have allowed an attacker to take down the whole Cloud Build plant easily. Retry logic means the program automatically tries again when something fails; aggressive retries can amplify a problem.

While everything was prepared and he started launching the attack against another VM he controlled, he found that VMs can no longer communicate with each other: Google had changed something recently. He also checked their WorkPool feature, which allows attaching these VMs to a VPC of yours, and they had applied the same network-level change there as well: VMs cannot see each other anymore.

Inspecting gRPC at the HTTP/2 layer

He built one more open source tool during this research: https://github.com/irsl/golang-http2debug-onthefly

This let him inspect the gRPC calls via the HTTP/2 layer, like this:

Line by line, the important parts:

  • Each line starts with a timestamp, then http2: and the tool's name for the connection (Framer 0xc0005767e0). A framer is the part of HTTP/2 that splits data into frames, the small packets HTTP/2 uses.
  • read HEADERS flags=END_HEADERS stream=49 len=282 means a HEADERS frame arrived on stream 49. In HTTP/2, a stream is one conversation inside a shared connection; many streams can run at once. END_HEADERS means this frame contains the complete set of headers.
  • decoded hpack field header field means the tool decoded the headers. HPACK is HTTP/2's compression scheme for headers, so they are not sent as plain text.
  • ":method" = "POST" is the HTTP method: POST, used to send data.
  • ":scheme" = "http" says the logical scheme is http (the encryption is handled by ALTS underneath).
  • ":path" = "/cloud.build.proto.worker.Worker/SetToken" is the API method being called: SetToken on the Worker service.
  • ":authority" = "[[redacted]]:1232" is the destination: an IPv6 address and port 1232.
  • "content-type" = "application/grpc" says the body is gRPC.
  • "user-agent" = "grpc-go/1.41.0-dev" identifies the client software and version.
  • "te" = "trailers" says the client understands trailers, which are headers sent after the body.
  • "grpc-timeout" = "59999924u" is the deadline for the call, in microseconds.
  • The x-goog-ext-...-bin headers are Google-specific extensions; the values are encoded, and one of them decodes to a service account name.
  • "ssa-operation-client" = "DirectPath:Go" mentions DirectPath, Google's technology for routing traffic directly to its services.
  • "ssa-rpc-method" and "ssa-rpc-id" repeat the method name and give a unique ID for this call.
  • "grpc-tags-bin" and "grpc-trace-bin" carry tracing information, used to follow a request through systems.
  • The final line is a DATA frame: the actual message body, 1150 bytes, shown as escaped bytes with 894 bytes omitted for brevity.

Given the name "DirectPath" in the headers, this implies the technology is in use for other Google products as well. If you are aware of any products with a similar security architecture, feel free to apply the takeaways.

The mysterious port 8081

There is one more attack vector. The worker_main process is also listening on port 8081. The frontend_main process is started with a command line argument: --worker_url http://[redacted]:8081. [redacted] is the special address that always means "this same machine", so this tells the frontend to talk to the worker locally.

Still, sending any HTTP requests to this port interrupts the TCP connection immediately without returning any HTTP response. Nothing is logged in the logfiles of the worker_main process. He looked into reversing the binaries themselves with Ghidra, a free tool for taking compiled programs apart to see what they do, but analysing huge Go binaries is not easy at all and the strings were also quite generic, so he could not find anything in a reasonable amount of time about the reason for terminating the connection.

Wrapping up

To summarise, he put a lot of effort into this research altogether, which is fine given he thinks this is a high value target. He usually does not publish an article when he does not have findings. Still, since the tools he built for this research are cool (at least in his opinion), he wanted to endorse them via this write-up. Also, ALTS and Cloud Build internals are not really well covered yet, so hopefully you find these lines useful.

While verifying one of the security measures around Cloud Build, he cross-checked the same at other Google products as well. He found one where the protection was missing, even though it should have been present to work securely. So his efforts at Cloud Build still yielded one VRP submission after all. VRP stands for Vulnerability Reward Program, Google's bug bounty scheme. Its triage was still in progress, so he could not share any details yet. It was identified to be an "abuse risk" surprisingly, even though he thinks its impact is much higher than the Nomulus one he reported earlier.

Additionally, he also found that the discovery document of services hosted via googleapis.com are not necessarily in line with the API methods they actually expose. A discovery document is a machine-readable description of an API, like a menu. If the menu does not match what the kitchen actually serves, that is worth investigating. A promising follow-up research is in progress.

Glossary

  • ALTS (Application Layer Transport Security): Google's internal alternative to TLS; encrypts traffic and proves the identity of each end.
  • API (Application Programming Interface): a menu of actions one program offers to another.
  • Artifact: a file produced by a build and uploaded at the end.
  • Bucket: a cloud storage container, like a folder with permissions.
  • Control plane: the part of a service that makes decisions and dispatches work.
  • DH (Diffie-Hellman): a mathematical method for two parties to agree on a shared secret over an open channel.
  • DHCP: the system that automatically assigns network addresses to computers joining a network.
  • Discovery document: a machine-readable description of an API's methods.
  • DoS (Denial of Service): an attack that stops a service from working rather than stealing data.
  • DUID: a unique identifier a machine presents when requesting an IPv6 address.
  • Docker: a tool for running isolated containers; the Docker socket is its control channel.
  • Framer: the part of HTTP/2 that splits data into frames.
  • gRPC: a structured way for programs to call each other's APIs, running on HTTP/2.
  • Ghidra: a free tool for taking compiled programs apart.
  • Go: a programming language; a Go binary is a compiled Go program.
  • HPACK: HTTP/2's header compression scheme.
  • HTTP/2: the modern version of the web's request protocol; gRPC runs on top of it.
  • Identity: the name badge a program presents during a handshake, such as a service account.
  • IPv4 / IPv6: the two common versions of network addresses; IPv4 is shorter, IPv6 longer.
  • ISC: the organisation behind the classic dhclient DHCP client.
  • Man-in-the-middle (MitM): an attacker secretly relaying a conversation between two parties.
  • Metadata server: an internal service that hands out information and credentials to VMs.
  • Network namespace: an isolated private network inside a machine.
  • OAuth scopes: a list of permissions attached to a credential.
  • Perfect forward secrecy: a property where stealing the long-term key later does not decrypt past conversations.
  • Port: an apartment number at a network address, identifying a particular service.
  • POST request: an HTTP method used to send data to a server.
  • Protobuf: a compact way of encoding structured data; protoc is its compiler.
  • Relayer: a program that terminates one connection and forwards the traffic to another server.
  • Retry logic: automatic re-attempts when something fails.
  • RFC: an official document defining an internet protocol.
  • Service account: a robot user account used by programs.
  • Session ID: an identifier for a particular conversation.
  • socat: a general-purpose tool that connects two data streams together.
  • Stack trace: the list of function calls that led to a crash.
  • Stream: one conversation inside a shared HTTP/2 connection.
  • Subnet: a slice of a network where machines can reach each other directly.
  • systemd: a common Linux program that starts and manages other programs.
  • TCP: the reliable delivery protocol underneath most internet traffic.
  • TLS: the encryption that puts the padlock in your browser.
  • Token: a short-lived password-like string proving you are allowed to do something.
  • URI: a path on a server, like /token.
  • Virtual machine (VM): a computer simulated inside a bigger computer.
  • VPC (Virtual Private Cloud): Google's private network for your resources.
  • VRP (Vulnerability Reward Program): Google's bug bounty scheme.
  • Worker: the part of a service that actually does the work on each machine.

More by Imre Rad

View all

2 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.

Broken access control

The lesson behind this report.

A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.