CVE-2022-29184 (Java, published 2022-05-20T20:15Z)
Description: value: GoCD is a continuous delivery server. In GoCD versions prior to 22.1.0, it is possible for existing authenticated users who have permissions to edit or create pipeline materials or pipeline configuration repositories to get remote code execution capability on the GoCD server via configuring a malicious branch name which abuses Mercurial hooks/aliases to exploit a command injection weakness. An attacker would require access to an account with existing GoCD administration permissions to either create/edit (`hg`-based) configuration repositories; create/edit pipelines and their (`hg`-based) materials; or, where "pipelines-as-code" configuration repositories are used, to commit malicious configuration to such an external repository which will be automatically parsed into a pipeline configuration and (`hg`) material definition by the GoCD server. This issue is fixed in GoCD 22.1.0. As a workaround, users who do not use/rely upon Mercurial materials can uninstall/remove the `hg`/Mercurial binary from the underlying GoCD Server operating system or Docker image.
Severity: MEDIUM (CVSS v3 base score: 8.8)
Weakness: CWE-77 \u2014 Improper Neutralization of Special Elements used in a Command ('Command Injection')
The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
Repository: https://github.com/gocd/gocd
Files changed:
common/src/test/java/com/thoughtworks/go/domain/materials/mercurial/HgCommandTest.java
domain/src/main/java/com/thoughtworks/go/domain/materials/mercurial/HgCommand.java
Commit message: Improve escaping of arguments when constructing Hg command calls


Vulnerable code:
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
    private static final String REVISION_0 = "b61d12de515d82d3a377ae3aae6e8abe516a2651";
    private static final String REVISION_1 = "35ff2159f303ecf986b3650fc4299a6ffe5a14e1";
    private static final String REVISION_2 = "ca3ebb67f527c0ad7ed26b789056823d8b9af23f";
        clientRepo =  TempDirUtils.createTempDirectoryIn(tempDir, "testHgClientRepo").toFile();
        secondBranchWorkingCopy =  TempDirUtils.createTempDirectoryIn(tempDir, "second").toFile();
        assertThat(clientRepo.listFiles().length > 0, is(true));
    public void shouldGetLatestModifications() throws Exception {
    public void shouldNotIncludeCommitFromAnotherBranchInGetLatestModifications() throws Exception {
    public void shouldNotGetModificationsFromOtherBranches() throws Exception {
    public void shouldThrowExceptionIfUpdateFails() throws Exception {
                .isExactlyInstanceOf(RuntimeException.class);
    public void shouldThrowExceptionForBadConnection() throws Exception {
import java.io.UnsupportedEncodingException;

    private boolean pull(ConsoleOutputStreamConsumer outputStreamConsumer) {
        CommandLine hg = hg("pull", "-b", branch, "--config", String.format("paths.default=%s", url));
        return execute(hg, outputStreamConsumer) == 0;
    }

        CommandLine hg = createCommandLine("hg").withArgs("version").withEncoding("utf-8");

        CommandLine hg = createCommandLine("hg").withArgs("clone").withArg("-b").withArg(branch).withArg(repositoryUrl)
                .withArg(workingDir.getAbsolutePath()).withNonArgSecrets(secrets).withEncoding("utf-8");
        execute(createCommandLine("hg").withArgs("id", "--id").withArg(repositoryURL).withNonArgSecrets(secrets).withEncoding("utf-8"), new NamedProcessTag(repositoryURL.forDisplay()));
    private String templatePath() {
        if (templatePath == null) {
            String file = HgCommand.class.getResource("/hg.template").getFile();
            try {
                templatePath = URLDecoder.decode(new File(file).getAbsolutePath(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                templatePath = URLDecoder.decode(new File(file).getAbsolutePath());
            }
        }
        return templatePath;
    }

    List<Modification> findRecentModifications(int count) {
        CommandLine hg = hg("log", "--limit", String.valueOf(count), "-b", branch, "--style", templatePath());
        CommandLine hg = hg("log",
                "-r", "tip:" + revision.getRevision(),
                "-b", branch,
                "--style", templatePath());

Fixed code:
import static org.hamcrest.Matchers.*;

    private static final String REVISION_0 = "b61d12de515d82d3a377ae3aae6e8abe516a2651";
    private static final String REVISION_1 = "35ff2159f303ecf986b3650fc4299a6ffe5a14e1";
    private static final String REVISION_2 = "ca3ebb67f527c0ad7ed26b789056823d8b9af23f";

        clientRepo = TempDirUtils.createTempDirectoryIn(tempDir, "testHgClientRepo").toFile();
        secondBranchWorkingCopy = TempDirUtils.createTempDirectoryIn(tempDir, "second").toFile();
        assertThat(clientRepo.listFiles().length, is(2));
    }

    @Test
    public void shouldCloneWithEscapedRepoUrl() {
        hgCommand.clone(outputStreamConsumer, new UrlArgument(echoingAliasFor("clone")));
        assertNoUnescapedEcho();
    public void shouldCloneWithEscapedBranch() {
        hgCommand = new HgCommand(null, workingDirectory, echoingAliasFor("clone"), serverRepo.getAbsolutePath(), null);
        hgCommand.clone(outputStreamConsumer, new UrlArgument(serverRepo.getAbsolutePath()));
        assertNoUnescapedEcho();
    }

    private String echoingAliasFor(String command) {
        return String.format("--config=alias.%s=!echo hello world", command);
    }

    private void assertNoUnescapedEcho() {
        assertThat(outputStreamConsumer.getAllOutput(), not(containsString("\nhello world\n")));
    }

    @Test
    public void shouldGetLatestModifications() {
    public void shouldNotIncludeCommitFromAnotherBranchInGetLatestModifications() {
    public void shouldNotGetModificationsFromOtherBranches() {
    public void shouldThrowExceptionIfUpdateFails() {
                .isExactlyInstanceOf(RuntimeException.class)
                .hasMessageContaining("Unable to update to revision [StringRevision[tip]]");
    public void shouldCheckConnection() {
        hgCommand.checkConnection(new UrlArgument(serverRepo.getAbsolutePath()));
    }

    @Test
    public void shouldCheckConnectionWithEscapedRepoUrl() {
        assertThatThrownBy(() -> hgCommand.checkConnection(new UrlArgument(echoingAliasFor("id"))))
                .isExactlyInstanceOf(CommandLineException.class)
                .hasMessageContaining("repository --config")
                .hasMessageContaining("not found");
    }

    @Test
    public void shouldThrowExceptionForBadConnection() {
import java.nio.charset.StandardCharsets;
        CommandLine hg = createCommandLine("hg").withArgs("version").withEncoding("UTF-8");
        CommandLine hg = createCommandLine("hg")
                .withArgs("clone")
                .withArg(branchArg())
                .withArg("--")
                .withArg(repositoryUrl)
                .withArg(workingDir.getAbsolutePath())
                .withNonArgSecrets(secrets)
                .withEncoding("UTF-8");
        CommandLine hg = createCommandLine("hg")
                .withArgs("id", "--id", "--")
                .withArg(repositoryURL)
                .withNonArgSecrets(secrets)
                .withEncoding("UTF-8");
        execute(hg, new NamedProcessTag(repositoryURL.forDisplay()));
    private boolean pull(ConsoleOutputStreamConsumer outputStreamConsumer) {
        CommandLine hg = hg("pull", branchArg(), "--config", String.format("paths.default=%s", url));
        return execute(hg, outputStreamConsumer) == 0;
    }

    private List<Modification> findRecentModifications(int count) {
        CommandLine hg = hg("log", "--limit", String.valueOf(count), branchArg(), "--style", templatePath());
        CommandLine hg = hg("log", "-r", "tip:" + revision.getRevision(), branchArg(), "--style", templatePath());
    private String templatePath() {
        if (templatePath == null) {
            String file = HgCommand.class.getResource("/hg.template").getFile();
            templatePath = URLDecoder.decode(new File(file).getAbsolutePath(), StandardCharsets.UTF_8);
        }
        return templatePath;
    }

    private String branchArg() {
        return "--branch=" + branch;
    }