Skip to content
Path traversal Write-up Intermediate

Agent 007: Pre-Auth Takeover of Build Pipelines in GoCD

GoCD's Business Continuity add-on exposed endpoints without authentication, allowing an unauthenticated attacker to read arbitrary files and leak the encryption key and configuration file containing all pipeline secrets. This could let an attacker impersonate agents, hijack build pipelines, and access sensitive data.

sonarsource Follow

Published on blog.sonarsource.com

GoCD, written in Java, is a popular CI/CD solution with a large range of users from NGOs to Fortune 500 companies with billions of dollars in revenue. Naturally, this makes it a critical piece of infrastructure and an extremely attractive target for attackers.

Sonar (@SonarSource), on blog.sonarsource.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. 8 min read.

Context

GoCD is a Java-based CI/CD solution used by a wide range of organisations, from NGOs to Fortune 500 companies. A centralised CI/CD server has access to production environments and private source code repositories, so compromising any part of the delivery pipeline can let an attacker leak intellectual property or insert backdoors into distributed software. The SolarWinds breach is the reference example given: attackers reached the software delivery pipeline and added a backdoor to critical software.

An attack on a GoCD pipeline
An attack on a GoCD pipeline From the original on blog.sonarsource.com

GoCD uses the Spring framework and relies on FilterChainProxy to enforce authentication on its endpoints. Work is delegated from the GoCD Server to GoCD Agents, workers that poll the server for assigned work. When work exists, the server replies with the commands to run and the environment variables to apply, and those variables typically include secrets and access tokens for the services a pipeline needs. Agents authenticate to the server with an access token the server assigns to them. By default a new agent contacts the server and registers itself, and an administrator then has to enable it before it joins the workload rotation.

The report describes a broken authentication issue (CVE-2021-43287) that lets an unauthenticated attacker read arbitrary files and extract all encrypted secrets from a GoCD Server, and use them to impersonate an agent and take over pipelines. The vulnerability was found in GoCD's Java code with SonarSource's taint analysis.

Setup

No accounts, roles or special tooling are needed to reach the vulnerable endpoints. The report states that the vulnerabilities require no prior knowledge of a targeted server, work on default configurations, and can be triggered even when authentication mechanisms are deployed for the instance. The affected range is v20.6.0 to v21.2.0, that is, every instance that includes commits [redacted] and [redacted]. The fix shipped in v21.3.0. The researchers also scanned some of the most popular add-ons with SonarCloud.

Finding it

The starting point is the filter chain configuration. The following snippet shows how filters are registered for URL patterns:

server/src/main/java/com/thoughtworks/go/server/newsecurity/filterchains/AuthenticationFilterChain.java

Java
 25   @Component("authenticationFilterChain")
 26   public class AuthenticationFilterChain extends FilterChainProxy {
 27
 28      @Autowired
 29      public AuthenticationFilterChain(
 30         @Qualifier("agentAuthenticationFilter") Filter x509AuthenticationFilter,
 31         // ...
 32         @Qualifier("accessTokenAuthenticationFilter") Filter accessTokenAuthenticationFilter,
 33         @Qualifier("assumeAnonymousUserFilter") Filter assumeAnonymousUserFilter) {
 34         super(FilterChainBuilder.newInstance()
 35            // X509 for agent remoting
 36            .addFilterChain("/remoting/**", x509AuthenticationFilter)
 37
 38            // For addons
 39            .addFilterChain("/add-on/**", assumeAnonymousUserFilter)
 40
 41            // ... more filters omitted

Every request path beginning with /add-on/ is filtered with assumeAnonymousUserFilter (line 39). As the name suggests, that filter performs no authentication and lets any request through, which means endpoints exposed by add-ons have to enforce authentication and permissions themselves. The researchers checked the history and found this had not always been the case: commit [redacted] introduced the change, and before it these endpoints were reachable by authenticated users only. Because add-on developers might not be aware that responsibility had been moved to them, the researchers scanned popular add-ons and found an arbitrary file read in the Business Continuity add-on, which is installed and enabled by default since v20.6.0.

Exploitation

Step 1: read arbitrary files through the plugin endpoint

The vulnerable handler is:

server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/primary/controller/PrimaryStatusProviderController.java

Java
119   @RequestMapping(value = "/plugin", method = RequestMethod.GET)
120   public void getPluginFile(
121            @RequestParam("folderName") String folderName,
122            @RequestParam("pluginName") String pluginName,
123         HttpServletResponse response) {
124      String pluginFolderPath = isBlank(folderName) || folderName.equalsIgnoreCase("bundled") ? systemEnvironment.getBundledPluginAbsolutePath() : systemEnvironment.get
    ExternalPluginAbsolutePath();
125      File pluginFile = new File(pluginFolderPath, pluginName);
126      serveFile(pluginFile, response, "application/octet-stream");
127   }

The attacker-controlled pluginName parameter is passed straight into the constructor of a new File object, and the resulting file is read and served back in the response. Setting pluginName to a traversal sequence such as /../../../../../../../../etc/passwd reads the contents of /etc/passwd from the GoCD server. The report notes that injecting unsanitised user input into a sensitive API such as a file opener can be detected automatically with taint analysis in SonarCloud.

Step 2: steal the encryption key and the main configuration

Two further endpoints on the same controller leak sensitive information:

Java
 92   @RequestMapping(value = "/cruise_config", method = RequestMethod.GET)
 93   public void getLatestCruiseConfigXML(HttpServletResponse response) {
 94         serveFile(ConfigFileType.CRUISE_CONFIG_XML.load(systemEnvironment), respon
    se, "text/xml");
 95   }
...
102   @RequestMapping(value = "/cipher.aes", method = RequestMethod.GET)
103   public void getLatestAESCipher(HttpServletResponse response) {
104      serveFile(ConfigFileType.AES_CIPHER.load(systemEnvironment), response, "te
    xt/plain");
105   }

/cipher.aes serves the encryption key used to encrypt sensitive secrets such as access tokens. /cruise_config serves the server's main configuration file, an XML document containing all environment variables for all pipelines. Some of those variables are encrypted and hold secrets, but with the leaked AES cipher they can be decrypted. The config also contains the other sensitive data described below. In total, two requests are enough to extract every secret available to the server: one for the encryption key and one for the encrypted secrets. The arbitrary file read additionally exposes git credentials, the main database file (Hibernate is used by default) and other sensitive files.

Step 3: use the leaked secrets

The main configuration file contains, by default, values such as these:

cruise_config.xml

XML
<server
    agentAutoRegisterKey="xxx-xxx-xxx-xxx-xxx-xxx"
    webhookSecret="xxx-xxx-xxx-xxx-xxx-xxx"
    tokenGenerationKey="xxx-xxx-xxx-xxx-xxx-xxx">
  • agentAutoRegisterKey: registers new GoCD Agents without administrator approval. An attacker can register multiple malicious agents into the worker rotation, hijack build pipelines, and from an agent reach an authenticated attack surface.
  • tokenGenerationKey: previous work by Pulse Security showed this token can be used to impersonate GoCD Agents that are already in the rotation and approved by administrators.
  • webhookSecret: authenticates webhook requests from GitHub, GitLab or BitBucket. Knowing it allows an attacker to trigger pipeline runs and opens further, previously unreachable attack surfaces.

The configuration also holds authentication settings. GoCD ships with two authentication plugins by default, Password and LDAP-based. A password file configuration looks like this:

cruise_config.xml

XML
<authConfig id="file" pluginId="cd.go.authentication.passwordfile">
    <property>
        <key>PasswordFilePath</key>
        <value>/opt/godata/password.txt</value>
    </property>
</authConfig>

Here the server reads passwords from /opt/godata/password.txt, in htpasswd format with a username and a hashed password. According to the plugin's documentation the hashes are stored in SHA1, Bcrypt or PBKDF2 format. With LDAP authentication, the worst case is that the attacker leaks the LDAP password from the server and gains access to the company's LDAP.

Or watch on YouTube
From the original on blog.sonarsource.com

The exploit video shows a GoCD instance being breached remotely.

Root cause

The mistake is a transfer of authentication responsibility. Commit [redacted] changed the filter chain so that everything under /add-on/** passes through assumeAnonymousUserFilter, which performs no authentication at all. Before that commit, add-on endpoints were only reachable by authenticated users. Add-on developers may not have known that their endpoints were now exposed to anonymous callers, and the Business Continuity add-on, enabled by default since v20.6.0, did not enforce authentication or authorisation on its own handlers. The /plugin handler then compounded this by passing user input into a file path without sanitisation, giving path traversal on top of the missing authentication. The existing defence, the Spring filter chain, did not stop any of this because the chain was explicitly configured to let these paths through.

Impact

The researchers rate the issue as highly critical: an unauthenticated attacker can extract all tokens and secrets used in all build pipelines. Concretely, an attacker could leak API keys to external services such as Docker Hub and GitHub, steal private source code, gain access to production environments, and overwrite files produced as part of build processes, leading to supply-chain attacks. The report also describes using the leaked material to obtain a valid session, either as an administrator or as an agent, and says a follow-up post will detail how vulnerabilities in the authenticated attack surface led to remote code execution on the server. Although hosting CI/CD instances on an internal network is best practice, the researchers observed hundreds of instances exposed to the internet.

Fix

The GoCD Security Team released patches for both vulnerabilities two days after the report, included in v21.3.0. The issue was addressed by removing the Business Continuity add-on from the core altogether. The researchers recommend patching as soon as possible, and, where an update cannot be applied immediately, setting up firewall rules to block HTTP requests to the /add-on/** and/or /add-on/business-continuity/** endpoints.

The disclosure timeline:

Date Action
2021-10-16 Exposed add-on endpoints reported to GoCD on HackerOne
2021-10-18 Other findings reported to GoCD on HackerOne
2021-10-18 GoCD confirms all issues
2021-10-18 GoCD pushes patches for the exposed add-on endpoints and the other issues to its GitHub repository
2021-10-22 GoCD gives a heads-up about an important security fix on its public Google Forum
2021-10-24 GoCD sends the experimental installer for v21.3.0
2021-10-25 Researchers verify the new version is secured against these vulnerabilities
2021-10-25 According to GoCD, a warning is sent to the GoCD mailing list
2021-10-26 GoCD releases v21.3.0

Variants to test

  • Other add-on endpoints under /add-on/**: enumerate handlers registered by installed add-ons and request them without credentials. A positive result is a response containing data or an action that should require a session.
  • File-serving handlers that take a filename parameter: send a traversal sequence such as /../../../../../../../../etc/passwd in the parameter and check whether the response body contains the target file.
  • Configuration and key endpoints: look for handlers that serve the main config, cipher material or similar files, and check whether they respond to anonymous requests. A positive result is XML configuration or key material in the response.
  • Default-enabled components: check which add-ons or plugins ship enabled by default and test them first, since they are present on unmodified installations.
  • Filter chain changes over time: diff the authentication filter configuration between releases to find paths that moved from an authenticated filter to an anonymous one; those paths are the candidates for this class of bug.

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

What happened, in plain words

GoCD is a piece of software that companies use to build and release their own software automatically. Think of it as a robot factory line: a developer saves a change to some code, and GoCD notices, then runs a series of steps (compile the code, run tests, package it up, push it out) without anyone having to do it by hand. Because it does all this, it needs the keys and passwords to reach the company's private code, its servers and its outside services. That makes it a very valuable thing to break into.

The researchers in this report found a way for someone with no account and no password at all to walk in and take copies of the most sensitive files on a GoCD server. With two simple web requests they could grab the key that unlocks every stored secret, and the file that holds all those secrets. From there they could pretend to be one of the GoCD workers (called Agents) and take over the build pipelines, or read any file on the machine.

The problem was not a clever password guess. It was a mistake in how GoCD decided who was allowed to see certain web addresses. A part of the software called an add-on (a plug-in that adds extra features) was left reachable by anyone, and one of its features let a visitor ask for a file by name without checking the name was safe. The vulnerability was detected in GoCD's Java code with SonarSource's taint analysis, a tool that follows untrusted input through a program, and they reported it to the GoCD team, who fixed it quickly.

An attack on a GoCD pipeline
An attack on a GoCD pipeline From the original on blog.sonarsource.com

The image above is the title banner of the original article, showing the name of the research and its publication date.

The setting: what GoCD is and why it matters

GoCD is written in Java, a programming language that runs on many kinds of computers. It is a CI/CD solution. CI/CD stands for continuous integration and continuous delivery: the practice of having a machine build, test and ship software every time someone changes it, instead of a person doing it by hand. GoCD is used by a very wide range of organisations, from NGOs to Fortune 500 companies with billions of dollars in revenue.

Because it automates building and releasing, a centralised CI/CD server has access to production environments (the live systems customers use) and to private source code repositories (the private store of a company's programming code). If an attacker controls any part of that release pipeline, they can leak intellectual property or slip backdoors into the software the company distributes. A backdoor is a hidden way into a program that the attacker can use later. The report points to the SolarWinds hack as the reference example: attackers got into the software delivery pipeline and added a backdoor to critical software, which became one of the most impactful supply-chain attacks so far. A supply-chain attack is when you do not break into the victim directly, but into something the victim trusts and installs.

How GoCD is put together

GoCD uses a framework called Spring. A framework is a ready-made set of building blocks that a program is assembled from, so the developers do not have to write everything from scratch. One of Spring's jobs is to decide, for each incoming web request, which checks it must pass before it is allowed to reach the code that handles it. That mechanism is called FilterChainProxy: a chain of filters, where each filter is a checkpoint that can inspect a request and either let it through or stop it.

Work in GoCD is split between two roles. The GoCD Server is the brain: it knows about the pipelines and decides what needs doing. GoCD Agents are the workers: separate machines that regularly ask the server "is there any work for me?". When there is, the server replies with the commands to run and the environment variables to apply. Environment variables are named values a program can read while it runs, and in a build pipeline they typically hold secrets and access tokens for the services the pipeline needs to reach. An access token is a long random string that acts like a key: whoever holds it is treated as the rightful user, without needing a username and password.

Agents authenticate to the server with an access token the server assigns to them. By default, when a new agent starts up, it contacts the server and registers itself, and then an administrator has to enable it before it joins the workload rotation (the pool of workers that actually get jobs).

The report describes a broken authentication issue tracked as CVE-2021-43287. Broken authentication is a broad label for any flaw where the software fails to correctly establish who is making a request, or lets a request through that should have been challenged. CVE stands for Common Vulnerabilities and Exposures: a public catalogue where each known security flaw gets an ID so people can refer to it unambiguously. The flaw lets an unauthenticated attacker (someone with no login) read arbitrary files and extract all encrypted secrets from a GoCD Server, then use them to impersonate an agent and take over pipelines. It was found in GoCD's Java code with SonarSource's taint analysis. Taint analysis is a technique that marks certain inputs as untrusted ("tainted") and then follows them through the code to see whether they ever reach a dangerous operation, such as opening a file, without being cleaned first.

What you need to try it

Nothing special. No accounts, no roles, no special tooling are needed to reach the vulnerable endpoints. An endpoint is simply a web address on a server that does something when you request it, like a counter in a shop: you go to the right window and ask, and you get served. The report states that the vulnerabilities require no prior knowledge of a targeted server, work on default configurations (the settings a fresh installation comes with, before anyone customises them), and can be triggered even when authentication mechanisms are deployed for the instance. In other words, having a login page does not help if the sensitive addresses are not behind it.

The affected range is v20.6.0 to v21.2.0, that is, every instance that includes commits [redacted] and [redacted]. A commit is a saved change in a code repository, identified by a long fingerprint so you can point at exactly one change. The fix shipped in v21.3.0. The researchers also scanned some of the most popular add-ons with SonarCloud, a service that analyses source code for problems.

Finding it: the checkpoint that waves everyone through

The starting point is the filter chain configuration, the file where GoCD lists which checkpoints apply to which web addresses. The following snippet shows how filters are registered for URL patterns:

server/src/main/java/com/thoughtworks/go/server/newsecurity/filterchains/AuthenticationFilterChain.java

Java
 25   @Component("authenticationFilterChain")
 26   public class AuthenticationFilterChain extends FilterChainProxy {
 27
 28      @Autowired
 29      public AuthenticationFilterChain(
 30         @Qualifier("agentAuthenticationFilter") Filter x509AuthenticationFilter,
 31         // ...
 32         @Qualifier("accessTokenAuthenticationFilter") Filter accessTokenAuthenticationFilter,
 33         @Qualifier("assumeAnonymousUserFilter") Filter assumeAnonymousUserFilter) {
 34         super(FilterChainBuilder.newInstance()
 35            // X509 for agent remoting
 36            .addFilterChain("/remoting/**", x509AuthenticationFilter)
 37
 38            // For addons
 39            .addFilterChain("/add-on/**", assumeAnonymousUserFilter)
 40
 41            // ... more filters omitted

Line by line, in plain words:

  • Line 25: @Component("authenticationFilterChain") gives this class a name so the framework can find and use it automatically.
  • Line 26: the class is called AuthenticationFilterChain and it extends FilterChainProxy, meaning it is a specialised version of Spring's filter chain.
  • Lines 28 to 33: the constructor, the code that runs when this object is created. It receives several filters as arguments. x509AuthenticationFilter checks certificates (a way of proving identity with a cryptographic file), accessTokenAuthenticationFilter checks access tokens, and assumeAnonymousUserFilter is the interesting one: its name means "assume the user is anonymous", that is, treat everyone as a stranger and do not check anything.
  • Line 34: super(FilterChainBuilder.newInstance() starts building the actual chain of rules.
  • Line 36: .addFilterChain("/remoting/**", x509AuthenticationFilter) says that any address starting with /remoting/ must pass the certificate check. The ** means "anything after this".
  • Line 39: .addFilterChain("/add-on/**", assumeAnonymousUserFilter) says that any address starting with /add-on/ gets the anonymous filter, which performs no authentication and lets any request through.
  • Line 41: the comment notes that more filters were left out of the snippet.

So every request path beginning with /add-on/ is filtered with assumeAnonymousUserFilter. That means endpoints exposed by add-ons have to enforce authentication and permissions themselves. The researchers checked the history and found this had not always been the case: commit [redacted] introduced the change, and before it these endpoints were reachable by authenticated users only. Because add-on developers might not be aware that responsibility had been moved to them, the researchers scanned popular add-ons and found an arbitrary file read in the Business Continuity add-on, which is installed and enabled by default since v20.6.0. "Arbitrary file read" means exactly what it sounds like: the ability to ask the server for any file it can see, not just the ones it meant to share.

Exploitation

Step 1: read arbitrary files through the plugin endpoint

The vulnerable handler is:

server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/primary/controller/PrimaryStatusProviderController.java

Java
119   @RequestMapping(value = "/plugin", method = RequestMethod.GET)
120   public void getPluginFile(
121            @RequestParam("folderName") String folderName,
122            @RequestParam("pluginName") String pluginName,
123         HttpServletResponse response) {
124      String pluginFolderPath = isBlank(folderName) || folderName.equalsIgnoreCase("bundled") ? systemEnvironment.getBundledPluginAbsolutePath() : systemEnvironment.get
    ExternalPluginAbsolutePath();
125      File pluginFile = new File(pluginFolderPath, pluginName);
126      serveFile(pluginFile, response, "application/octet-stream");
127   }

Line by line:

  • Line 119: @RequestMapping(value = "/plugin", method = RequestMethod.GET) says this method answers web requests to the address /plugin when the request is a GET. A GET is the kind of request a browser makes when you simply open a page or click a link: you are asking to be given something, not to change something.
  • Lines 120 to 123: the method is called getPluginFile and it takes three inputs. @RequestParam("folderName") means "take the value called folderName from the request's query string", the part of a URL after the ? sign. @RequestParam("pluginName") does the same for a value called pluginName. HttpServletResponse response is the object used to send the answer back.
  • Line 124: this decides which folder to look in. If folderName is blank or equals "bundled" (ignoring case), it uses the path where bundled plug-ins live; otherwise it uses the path for external plug-ins. A path is the address of a folder or file on the computer's disk, like a postal address for files.
  • Line 125: new File(pluginFolderPath, pluginName) builds a file location by joining the folder path with the pluginName the visitor supplied. This is the crucial line: the visitor's text is glued onto a folder path with no check on what it contains.
  • Line 126: serveFile(...) reads that file and sends its contents back in the response, labelled as application/octet-stream, which just means "raw bytes, no particular format".
  • Line 127: closes the method.

The attacker-controlled pluginName parameter is passed straight into the constructor of a new File object, and the resulting file is read and served back in the response. Setting pluginName to a traversal sequence such as /../../../../../../../../etc/passwd reads the contents of /etc/passwd from the GoCD server. Path traversal works because .. means "go up one folder". If you are told to look in /opt/plugins/ and the name you are given starts with enough ../ steps, you climb out of that folder and end up at the root of the disk, then walk down into /etc/. On a Linux system, /etc/passwd is a classic file to demonstrate this with: it lists the user accounts on the machine. It does not contain passwords despite the name, but reading it proves you can read files you were never meant to see. The report notes that injecting unsanitised user input into a sensitive API such as a file opener can be detected automatically with taint analysis in SonarCloud. An API, in this context, is simply a function inside the program that other code calls to do something, like a service counter inside a building.

Step 2: steal the encryption key and the main configuration

Two further endpoints on the same controller leak sensitive information:

Java
 92   @RequestMapping(value = "/cruise_config", method = RequestMethod.GET)
 93   public void getLatestCruiseConfigXML(HttpServletResponse response) {
 94         serveFile(ConfigFileType.CRUISE_CONFIG_XML.load(systemEnvironment), respon
    se, "text/xml");
 95   }
...
102   @RequestMapping(value = "/cipher.aes", method = RequestMethod.GET)
103   public void getLatestAESCipher(HttpServletResponse response) {
104      serveFile(ConfigFileType.AES_CIPHER.load(systemEnvironment), response, "te
    xt/plain");
105   }

Line by line:

  • Line 92: this method answers GET requests to /cruise_config.
  • Lines 93 to 95: it loads the file of type CRUISE_CONFIG_XML and serves it with the label text/xml, telling the browser the content is XML. XML is a text format for structured data, using tags in angle brackets to mark up pieces of information, much like a very strict form of HTML.
  • Line 102: this method answers GET requests to /cipher.aes.
  • Lines 103 to 105: it loads the file of type AES_CIPHER and serves it as text/plain, plain text. AES is a widely used encryption algorithm; a cipher is the mathematical recipe used to scramble and unscramble data.

/cipher.aes serves the encryption key used to encrypt sensitive secrets such as access tokens. Encryption turns readable text into scrambled text; the key is the piece of information that lets you scramble and unscramble it. If you have the key, the scrambling offers no protection at all. /cruise_config serves the server's main configuration file, an XML document containing all environment variables for all pipelines. Some of those variables are encrypted and hold secrets, but with the leaked AES cipher they can be decrypted. The config also contains the other sensitive data described below. In total, two requests are enough to extract every secret available to the server: one for the encryption key and one for the encrypted secrets. The arbitrary file read additionally exposes git credentials (the username and token used to fetch code from a git repository), the main database file (Hibernate is used by default, a tool that stores the server's data in a database file) and other sensitive files.

Step 3: use the leaked secrets

The main configuration file contains, by default, values such as these:

cruise_config.xml

XML
<server
    agentAutoRegisterKey="xxx-xxx-xxx-xxx-xxx-xxx"
    webhookSecret="xxx-xxx-xxx-xxx-xxx-xxx"
    tokenGenerationKey="xxx-xxx-xxx-xxx-xxx-xxx">

This is a fragment of XML. <server opens a description of the server's settings, and each name="value" pair inside it is one setting. The xxx-xxx-... strings are placeholders where real secret values would sit. Each of the three settings is a different kind of key:

  • agentAutoRegisterKey: registers new GoCD Agents without administrator approval. An attacker can register multiple malicious agents into the worker rotation, hijack build pipelines, and from an agent reach an authenticated attack surface. "Authenticated attack surface" means the set of features that only logged-in users or agents can reach; once you are inside, there is more to attack.
  • tokenGenerationKey: previous work by Pulse Security showed this token can be used to impersonate GoCD Agents that are already in the rotation and approved by administrators. Impersonate means to convincingly pretend to be someone or something else.
  • webhookSecret: authenticates webhook requests from GitHub, GitLab or BitBucket. A webhook is an automatic message one service sends to another when something happens, for example GitHub telling GoCD that code changed. The secret proves the message really came from GitHub. Knowing it allows an attacker to trigger pipeline runs and opens further, previously unreachable attack surfaces.

The configuration also holds authentication settings. GoCD ships with two authentication plugins by default, Password and LDAP-based. A plug-in is an optional piece of software that adds a feature. LDAP is a directory service, a central list of users and passwords that many companies keep so that one login works across many systems. A password file configuration looks like this:

cruise_config.xml

XML
<authConfig id="file" pluginId="cd.go.authentication.passwordfile">
    <property>
        <key>PasswordFilePath</key>
        <value>/opt/godata/password.txt</value>
    </property>
</authConfig>

Line by line:

  • <authConfig id="file" pluginId="cd.go.authentication.passwordfile"> starts a block describing one way users can log in. Its id is "file" and it uses the password-file plug-in.
  • <property> opens a single setting for that plug-in.
  • <key>PasswordFilePath</key> names the setting: the path to the password file.
  • <value>/opt/godata/password.txt</value> gives its value: the server reads passwords from that file.
  • The closing tags end the setting and the block.

Here the server reads passwords from /opt/godata/password.txt, in htpasswd format with a username and a hashed password. A hash is the result of running a password through a one-way mathematical function: you can turn a password into a hash, but you cannot turn the hash back into the password. According to the plug-in's documentation the hashes are stored in SHA1, Bcrypt or PBKDF2 format, three different hashing recipes of varying strength. With LDAP authentication, the worst case is that the attacker leaks the LDAP password from the server and gains access to the company's LDAP.

Or watch on YouTube
From the original on blog.sonarsource.com

The video above demonstrates how a GoCD instance can be easily breached remotely.

Root cause

The mistake is a transfer of authentication responsibility. Commit [redacted] changed the filter chain so that everything under /add-on/** passes through assumeAnonymousUserFilter, which performs no authentication at all. Before that commit, add-on endpoints were only reachable by authenticated users. Add-on developers may not have known that their endpoints were now exposed to anonymous callers, and the Business Continuity add-on, enabled by default since v20.6.0, did not enforce authentication or authorisation on its own handlers. Authorisation is the second half of the question: authentication asks "who are you?", authorisation asks "are you allowed to do this?". The /plugin handler then compounded this by passing user input into a file path without sanitisation, giving path traversal on top of the missing authentication. Sanitisation means cleaning input before using it, for example by rejecting names that contain ... The existing defence, the Spring filter chain, did not stop any of this because the chain was explicitly configured to let these paths through.

Impact

The researchers rate the issue as highly critical: an unauthenticated attacker can extract all tokens and secrets used in all build pipelines. Concretely, an attacker could leak API keys to external services such as Docker Hub and GitHub, steal private source code, gain access to production environments, and overwrite files produced as part of build processes, leading to supply-chain attacks. An API key is a secret string that identifies a program to a service, like a membership card. The report also describes using the leaked material to obtain a valid session, either as an administrator or as an agent. A session is the state of being logged in: the server remembers you, usually by giving your browser a cookie, a small piece of data the browser stores and sends back with every request. The report says a follow-up post will detail how vulnerabilities in the authenticated attack surface were chained to remote code execution on the server. Remote code execution means making the server run commands of your choosing. Although hosting CI/CD instances on an internal network is best practice, the researchers observed hundreds of instances exposed to the internet.

Fix

The GoCD Security Team released patches for both vulnerabilities two days after the report, included in v21.3.0. A patch is a small update that repairs a flaw. The issue was addressed by removing the Business Continuity add-on from the core altogether, so the vulnerable code is no longer shipped. The researchers recommend patching as soon as possible, and, where an update cannot be applied immediately, setting up firewall rules to block HTTP requests to the /add-on/** and/or /add-on/business-continuity/** endpoints. A firewall is a filter on network traffic: it can drop requests to certain addresses before they ever reach the program.

The disclosure timeline:

Date Action
2021-10-16 Exposed add-on endpoints reported to GoCD on HackerOne
2021-10-18 Other findings reported to GoCD on HackerOne
2021-10-18 GoCD confirms all issues
2021-10-18 GoCD pushes patches for the exposed add-on endpoints and the other issues to its GitHub repository
2021-10-22 GoCD gives a heads-up about an important security fix on its public Google Forum
2021-10-24 GoCD sends the experimental installer for v21.3.0
2021-10-25 Researchers verify the new version is secured against these vulnerabilities
2021-10-25 According to GoCD, a warning is sent to the GoCD mailing list
2021-10-26 GoCD releases v21.3.0

HackerOne is a platform where security researchers report flaws to companies. A disclosure timeline records who did what and when, so the process is transparent.

Variants to test

If you are checking a similar system, these are the angles the report suggests:

  • Other add-on endpoints under /add-on/**: enumerate handlers registered by installed add-ons and request them without credentials. A positive result is a response containing data or an action that should require a session. Enumerate here means to list them one by one.
  • File-serving handlers that take a filename parameter: send a traversal sequence such as /../../../../../../../../etc/passwd in the parameter and check whether the response body contains the target file.
  • Configuration and key endpoints: look for handlers that serve the main config, cipher material or similar files, and check whether they respond to anonymous requests. A positive result is XML configuration or key material in the response.
  • Default-enabled components: check which add-ons or plug-ins ship enabled by default and test them first, since they are present on unmodified installations.
  • Filter chain changes over time: diff the authentication filter configuration between releases to find paths that moved from an authenticated filter to an anonymous one; those paths are the candidates for this class of bug. To diff means to compare two versions and highlight what changed.

Glossary

  • Add-on: an optional piece of software that adds features to a larger program; also called a plug-in.
  • Agent: in GoCD, a worker machine that asks the server for jobs and runs them.
  • API: a function or interface inside a program that other code calls to perform an action.
  • API key: a secret string that identifies a program to an outside service.
  • Arbitrary file read: the ability to make a server return any file it can access, not just the ones it meant to share.
  • Authentication: the process of establishing who is making a request.
  • Authorisation: the process of deciding whether an identified user is allowed to do something.
  • Backdoor: a hidden way into a program that an attacker can use later.
  • Broken authentication: a class of flaw where software fails to correctly establish identity or lets requests through that should have been challenged.
  • CI/CD: continuous integration and continuous delivery, the practice of automatically building, testing and shipping software on every change.
  • Cipher: the mathematical recipe used to scramble and unscramble data.
  • Commit: a saved change in a code repository, identified by a long fingerprint.
  • Cookie: a small piece of data a browser stores and sends back with requests, often used to remember a session.
  • CVE: Common Vulnerabilities and Exposures, a public catalogue that gives each known security flaw an ID.
  • Diff: to compare two versions of something and highlight the differences.
  • Encryption: turning readable data into scrambled data so that only someone with the key can read it.
  • Endpoint: a web address on a server that performs an action when requested.
  • Environment variable: a named value a running program can read, often used to pass secrets to a build.
  • Filter chain: a series of checkpoints a web request must pass before reaching the code that handles it.
  • Firewall: a filter on network traffic that can block requests to certain addresses.
  • Framework: a ready-made set of building blocks a program is assembled from.
  • GET: the kind of web request a browser makes when you open a page or click a link, asking to be given something.
  • Hash: the result of a one-way function applied to data, such as a password, that cannot be reversed.
  • Hibernate: a tool that stores a Java program's data in a database file.
  • htpasswd: a simple text file format listing usernames and hashed passwords.
  • Impersonate: to convincingly pretend to be another user or system.
  • LDAP: a directory service that keeps a central list of users and passwords for many systems.
  • Patch: a small software update that repairs a flaw.
  • Path: the address of a file or folder on a computer's disk.
  • Path traversal: using .. sequences in a file name to climb out of the intended folder and reach other files.
  • Plug-in: see add-on.
  • Remote code execution: making a server run commands of your choosing.
  • Sanitisation: cleaning input before using it, for example by rejecting dangerous characters.
  • Session: the state of being logged in, usually remembered by a cookie.
  • Supply-chain attack: breaking into something a victim trusts and installs, rather than the victim directly.
  • Taint analysis: a code analysis technique that marks untrusted input and follows it to see whether it reaches a dangerous operation unchecked.
  • Token: a long random string that acts like a key, granting access to whoever holds it.
  • Webhook: an automatic message one service sends to another when something happens.
  • XML: a text format for structured data using tags in angle brackets.

More by sonarsource

View all

5 more disclosed reports, best first.

More from GoCD

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Path traversal and file inclusion

The lesson behind this report.

Input that builds a file path escapes the intended folder, reading or writing files the application should never touch.