Git flag injection leading to file overwrite and potential remote code execution
The Commits API did not sanitise the ref_name parameter, so a value beginning with -- was passed to git as a command-line flag. An attacker could use this to overwrite or truncate arbitrary files on the server, causing denial of service and potentially escalating privileges.
- Triaged in 3 hours
- Fixed in 30 days
- Paid in 30 days
- Disclosed after 5 months
Summary
The ref_name in the Commits API is not sanitized, allowing for a ref starting with -- to be provided causing git to interpret it as a flag instead of as a ref.
If a ref_name such as --output=/tmp/some_file is used then the following command is executed by gitaly in find_commits.go:
/opt/gitlab/embedded/bin/git --git-dir /var/opt/gitlab/git-data/repositories/@hashed/ef/2d/ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d.git log --format=format:%H --max-count=20 --follow --output=/tmp/some_file -- .
followed by
/opt/gitlab/embedded/bin/git --git-dir /var/opt/gitlab/git-data/repositories/@hashed/ef/2d/ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d.git rev-list --count --output=/tmp/some_file -- .
This first writes the list of commits to the file, but then the rev-list command fails but not before truncating the file.
Steps to reproduce
- Create a repo and add a file
- Use the commit api and pass in a
ref_namesuch as--output=/tmp/written:
curl 'http://4290d4225642/api/v4/projects/5/repository/commits?path=.&ref_name=--output=/tmp/written'
- See that the file has been created:
# ls -asl /tmp/written
0 -rw-r--r-- 1 git git 0 Jul 22 14:56 /tmp/written
Impact
The bug allows for arbitrary files to be briefly replaced with a known commit (or a list) and then truncated be empty, easily causing denial of service by replacing important files.
One attack scenario I thought of would be to truncate /var/opt/gitlab/gitlab-rails/etc/gitlab_shell_secret, which almost worked but ended up failing due to authenticate_by_gitlab_shell_token checking the token with unauthorized! unless Devise.secure_compare(secret_token, input) which fails if either are blank.
This method could potentially still work if a large number of requests were spammed, waiting until the unicorn restarts (eg for an upgrade). So long as a git log happens last before the server shuts down then the file will stay with the commit and not get truncated. I was able to reproduce this with around 32 connections then restarting:
# gitlab-ctl restart unicorn
ok: run: unicorn: (pid 46755) 1s
root@4290d4225642:/var/opt/gitlab/gitlab-rails/etc# cat gitlab_shell_secret
████████
``
This then allows for use of the internal api:
curl -s 'http://4290d4225642/api/v4/internal/check?secret_token=██████████' {"api_version":"v4","gitlab_version":"12.0.3","gitlab_rev":"08a51a9db93","redis":true}
curl -s 'http://4290d4225642/api/v4/internal/discover?secret_token=███&user_id=1' {"id":1,"name":"Administrator","username":"root"}
### What is the current *bug* behavior?
The `ref_name` is not sanitized
### What is the expected *correct* behavior?
The `ref_name` should be sanitized to prevent it being used as git command flags.
#### Results of GitLab environment info
System information
System:
Current User: git
Using RVM: no
Ruby Version: 2.6.3p62
Gem Version: 2.7.9
Bundler Version:1.17.3
Rake Version: 12.3.2
Redis Version: 3.2.12
Git Version: 2.21.0
Sidekiq Version:5.2.7
Go Version: unknown
GitLab information
Version: 12.0.3
Revision: 08a51a9db93
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 10.7
URL: http://4290d4225642
HTTP Clone URL: http://4290d4225642/some-group/some-project.git
SSH Clone URL: git@4290d4225642:some-group/some-project.git
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 9.3.0
Repository storage paths:
- default: /var/opt/gitlab/git-data/repositories
GitLab Shell path: /opt/gitlab/embedded/service/gitlab-shell
Git: /opt/gitlab/embedded/bin/git
## Impact
Truncating arbitrary files and potentially replacing them with known content. This can lead to denial of service, loss of important data, and potential privilege escalation.
Context
GitLab exposes a Commits API under /api/v4/projects/:id/repository/commits. One of its parameters is ref_name, which tells GitLab which branch, tag or other ref to list commits from. Internally, GitLab does not run git itself: it asks Gitaly, the Git RPC service, to perform the operation. For this endpoint Gitaly builds a git log command and a git rev-list command from the supplied ref.
The report is about that parameter not being sanitised. A ref_name beginning with -- is passed to git in a position where git treats it as an option rather than as a ref. Git accepts options such as --output=<file>, so the value controls where git writes.
Setup
The report includes GitLab environment info for version 12.0.3 (revision 08a51a9db93), with GitLab Shell 9.3.0, Ruby 2.6.3p62, Redis 3.2.12, PostgreSQL 10.7 and Git 2.21.0. The git binary in use is /opt/gitlab/embedded/bin/git, and repositories live under /var/opt/gitlab/git-data/repositories.
The reproduction needs a project with at least one commit and a file in it, plus the ability to call the Commits API on that project. The reproduction request uses project id 5 on http://4290d4225642.
Finding it
The starting observation is that ref_name reaches git without sanitisation. Because git parses anything that looks like an option before it parses the ref, a value such as --output=/tmp/some_file is not a ref at all: it is an instruction to git to write its output to that path.
Gitaly's find_commits.go runs two commands for this request. The first is:
/opt/gitlab/embedded/bin/git --git-dir /var/opt/gitlab/git-data/repositories/@hashed/ef/2d/[redacted].git log --format=format:%H --max-count=20 --follow --output=/tmp/some_file -- .
and the second is:
/opt/gitlab/embedded/bin/git --git-dir /var/opt/gitlab/git-data/repositories/@hashed/ef/2d/[redacted].git rev-list --count --output=/tmp/some_file -- .
The injected --output=/tmp/some_file sits where the ref would normally be. The -- before the final . is meant to stop option parsing, but it comes after the injected value, so it does not help.
The two commands interact in a way that matters for exploitation. The log command succeeds and writes the list of commits to the file. The rev-list command then fails, but before failing it truncates the file. The net effect on an existing file is that it is briefly replaced with commit data and then left empty.
Exploitation
Step 1: create a repository with a file
Create a project and add a file so that there is at least one commit for the API to operate on. The example uses project id 5.
Step 2: call the Commits API with a flag as ref_name
Send the request with ref_name set to an --output= flag pointing at a path the git user can write to:
curl 'http://4290d4225642/api/v4/projects/5/repository/commits?path=.&ref_name=--output=/tmp/written'
The ref_name value is the payload: it is passed through to git as an option, so git writes the commit list to /tmp/written during the log call and then truncates it during the failed rev-list call.
Step 3: confirm the file was created
# ls -asl /tmp/written
0 -rw-r--r-- 1 git git 0 Jul 22 14:56 /tmp/written
The file exists, is owned by git, and is zero bytes, which matches the log-then-truncate sequence described above.
Step 4: target a file that matters
The researcher considered truncating /var/opt/gitlab/gitlab-rails/etc/gitlab_shell_secret. That attempt almost worked but failed because authenticate_by_gitlab_shell_token checks the token with unauthorized! unless Devise.secure_compare(secret_token, input), and that comparison fails when either value is blank. An empty secret therefore does not authenticate.
The idea could still work with a different timing: spam a large number of requests and wait until Unicorn restarts, for example during an upgrade. If a git log runs last before the server shuts down, the file keeps the commit content instead of being truncated. The researcher reproduced this with around 32 connections followed by a restart:
# gitlab-ctl restart unicorn
ok: run: unicorn: (pid 46755) 1s
root@4290d4225642:/var/opt/gitlab/gitlab-rails/etc# cat gitlab_shell_secret
████████
With the secret file holding commit content at the moment of shutdown, the value can be read and used against the internal API:
curl -s 'http://4290d4225642/api/v4/internal/check?secret_token=██████████'
{"api_version":"v4","gitlab_version":"12.0.3","gitlab_rev":"08a51a9db93","redis":true}
curl -s 'http://4290d4225642/api/v4/internal/discover?secret_token=███&user_id=1'
{"id":1,"name":"Administrator","username":"root"}
The first call returns version and revision information from the internal API. The second resolves user id 1 to the root administrator account.
Root cause
The Commits API does not sanitise ref_name, and Gitaly places the value directly into the argument list of git log and git rev-list without a preceding --. Git's option parser therefore treats a value starting with -- as a flag. The -- that Gitaly does include comes after the injected value, so it cannot protect it.
The --output flag lets the value control where git writes. The follow-up rev-list call fails, but its failure happens after it has already truncated the target file, which turns a write primitive into a destructive one.
The gitlab_shell_secret path was blocked only by an incidental property of Devise.secure_compare: a blank secret does not match. That is a defence that happens to hold for an empty file, not a defence against the injection itself.
Impact
An attacker who can call the Commits API can truncate arbitrary files writable by the git user, and can briefly replace them with a known commit or a list of commits. The report describes this as denial of service, loss of important data and potential privilege escalation.
The concrete escalation path shown is the gitlab_shell_secret file. Truncating it does not by itself grant access because of the blank-token check, but the timing approach, spamming requests and waiting for a Unicorn restart so that a git log is the last command to touch the file, can leave the file containing commit data. That data can then be used as the internal API secret, which the researcher demonstrated by calling /api/v4/internal/check and /api/v4/internal/discover and resolving the root administrator. The report presents this as a potential path rather than a guaranteed one.
Fix
The report states the expected behaviour plainly: ref_name should be sanitised so that it cannot be used as git command flags. The report does not describe a specific patch or code change.
- Other API parameters that end up as git refs or revisions, such as compare, blame, diff or tree endpoints. A positive result is a request that causes git to write to a path you choose, or an error that reveals the injected flag was parsed as an option.
- Other git flags that write files or change behaviour, for example flags that redirect output or read configuration. A positive result is a file appearing at a path you control, or a change in command output that only the flag could cause.
- Ref values that begin with a single
-as well as--. A positive result is the same write or truncation behaviour with a shorter payload. - Timing the truncation against service restarts, as the researcher did with around 32 connections and a Unicorn restart. A positive result is a sensitive file left holding commit content rather than being empty.
This class of bug hides wherever user input is passed to a command-line tool as an argument without a -- separator, especially in services that wrap git, such as Gitaly. During recon, look for API parameters named after refs, revisions, branches or paths, and for error messages that echo the underlying command. The signal that a target is vulnerable is that a value starting with -- changes the command's behaviour rather than producing a normal "unknown revision" error.
To show enough impact, demonstrate a concrete file write or truncation on a path that matters, then connect it to a security boundary. Here the researcher did not stop at creating /tmp/written: they identified gitlab_shell_secret, explained why the simple truncation failed, and showed a timing-based route to reading the secret and using it against the internal API to reach the root administrator. That chain, with the requests and responses, is what turns a file-write primitive into a critical finding.
One limit to keep in mind when reproducing: the blank-token check means an empty secret file is not useful on its own, so the timing approach is the part that carries the escalation.
What happened, in plain words
GitLab is a website where teams keep and share computer code. One of its features is an API: a way for programs (or people using a tool like curl) to ask GitLab for information over the web, instead of clicking around in a browser. Think of an API as a service counter: you hand over a request with a few labelled details, and you get an answer back.
One of those counters is the Commits API. You give it a project and it gives you back the list of commits, which are the saved snapshots of changes in that project. To know which line of history you want, you pass a parameter called ref_name, which normally names a branch or a tag.
Behind the scenes GitLab does not do the git work itself. It asks a separate helper program called Gitaly to run the real git command. The problem in this report is that the ref_name value is handed to git without being checked. If the value starts with --, git does not read it as a branch name at all: it reads it as an instruction, an option. One such option, --output=<file>, tells git to write its results into a file of your choosing. So a value meant to be a branch name ends up controlling where git writes on the server's disk.
This kind of bug is called command injection: user input slips into a command line and is treated as part of the command rather than as plain data. The result here is that an attacker can create files, overwrite files and empty files that the git user is allowed to touch. That can break the service (denial of service), destroy data, and in the right timing even hand over an administrator secret.
Context
GitLab exposes a Commits API under /api/v4/projects/:id/repository/commits. The :id part is the project's number. One of the parameters this endpoint accepts is ref_name, which tells GitLab which branch, tag or other ref to list commits from. A ref is simply a name that points at a commit, like main or v1.0.
Internally, GitLab does not run git itself: it asks Gitaly, the Git RPC service, to perform the operation. RPC here means one program asking another to do a job, like phoning a colleague instead of doing the task yourself. For this endpoint Gitaly builds a git log command and a git rev-list command from the supplied ref. git log lists commits; git rev-list is a lower-level command that walks the same history, often just to count commits.
The report is about that parameter not being sanitised. Sanitising means cleaning input so it can only be used for its intended purpose. A ref_name beginning with -- is passed to git in a position where git treats it as an option rather than as a ref. Git accepts options such as --output=<file>, so the value controls where git writes.
Setup
The report includes GitLab environment info for version 12.0.3 (revision 08a51a9db93), with GitLab Shell 9.3.0, Ruby 2.6.3p62, Redis 3.2.12, PostgreSQL 10.7 and Git 2.21.0. These are the pieces of software the test server was built from; the versions matter because behaviour can differ between releases. The git binary in use is /opt/gitlab/embedded/bin/git, and repositories live under /var/opt/gitlab/git-data/repositories.
The reproduction needs a project with at least one commit and a file in it, plus the ability to call the Commits API on that project. The reproduction request uses project id 5 on http://4290d4225642.
Finding it
The starting observation is that ref_name reaches git without sanitisation. Because git parses anything that looks like an option before it parses the ref, a value such as --output=/tmp/some_file is not a ref at all: it is an instruction to git to write its output to that path. A useful comparison is a form where one field is meant for your name, but you write "and also send a copy to this address" and the clerk follows it as an instruction.
Gitaly's find_commits.go runs two commands for this request. The first is:
/opt/gitlab/embedded/bin/git --git-dir /var/opt/gitlab/git-data/repositories/@hashed/ef/2d/[redacted].git log --format=format:%H --max-count=20 --follow --output=/tmp/some_file -- .
Line by line:
/opt/gitlab/embedded/bin/gitis the full path to the git program being run.--git-dir /var/opt/gitlab/git-data/repositories/@hashed/ef/2d/[redacted].gittells git where the repository's internal data lives. The long hashed folder name is how GitLab stores each project on disk.logis the subcommand that lists commits.--format=format:%Hsays to print only the full commit hash, the long identifier of each commit.--max-count=20limits the list to 20 commits.--followasks git to follow a file's history across renames.--output=/tmp/some_fileis the injected part: it tells git to write the result into that file instead of printing it.--is meant to mark the end of options, so that anything after it is treated as a plain name..is the path being asked about, here the current directory of the repository.
and the second is:
/opt/gitlab/embedded/bin/git --git-dir /var/opt/gitlab/git-data/repositories/@hashed/ef/2d/[redacted].git rev-list --count --output=/tmp/some_file -- .
Line by line:
- The first two parts are the same git binary and the same repository location as before.
rev-listis the subcommand that walks the commit history.--countasks it to print only how many commits there are.--output=/tmp/some_fileis again the injected option, pointing at the same file.-- .again tries to end options and name the path.
The injected --output=/tmp/some_file sits where the ref would normally be. The -- before the final . is meant to stop option parsing, but it comes after the injected value, so it does not help. Picture a queue where the guard who checks tickets stands at the back: anyone who walks in before him is already inside.
The two commands interact in a way that matters for exploitation. The log command succeeds and writes the list of commits to the file. The rev-list command then fails, but before failing it truncates the file. Truncating means cutting it down to zero length. The net effect on an existing file is that it is briefly replaced with commit data and then left empty.
Exploitation
Step 1: create a repository with a file
Create a project and add a file so that there is at least one commit for the API to operate on. The example uses project id 5. Without a commit there is nothing for the API to list, so this step gives the attack something to work with.
Step 2: call the Commits API with a flag as ref_name
Send the request with ref_name set to an --output= flag pointing at a path the git user can write to:
curl 'http://4290d4225642/api/v4/projects/5/repository/commits?path=.&ref_name=--output=/tmp/written'
Line by line:
curlis a command-line tool for sending web requests; it is the browser equivalent of typing a URL and pressing enter, but it shows you the raw answer.http://4290d4225642is the address of the test GitLab server./api/v4/projects/5/repository/commitsis the Commits API endpoint for project5.?starts the list of parameters.path=.is the normal path filter for the endpoint, here the repository root.&separates parameters.ref_name=--output=/tmp/writtenis the payload: the value that should be a branch name is instead a git option telling git to write to/tmp/written.
The path=. parameter is the normal path filter for the endpoint. The ref_name value is the payload: it is passed through to git as an option, so git writes the commit list to /tmp/written during the log call and then truncates it during the failed rev-list call.
Step 3: confirm the file was created
# ls -asl /tmp/written
0 -rw-r--r-- 1 git git 0 Jul 22 14:56 /tmp/written
Line by line:
#is the shell prompt, showing this is a command typed on the server.ls -asl /tmp/writtenlists details about the file/tmp/written.0is the size in blocks, so effectively empty.-rw-r--r--are the permissions: the owner can read and write, everyone else can only read.git gitare the owner and group, meaning the git user created it.0is the size in bytes.Jul 22 14:56is the creation time./tmp/writtenis the file name.
The file exists, is owned by git, and is zero bytes, which matches the log-then-truncate sequence described above.
Step 4: target a file that matters
The researcher considered truncating /var/opt/gitlab/gitlab-rails/etc/gitlab_shell_secret. If an outsider learns it, they can pretend to be that trusted part. That attempt almost worked but failed because authenticate_by_gitlab_shell_token checks the token with unauthorized! unless Devise.secure_compare(secret_token, input), and that comparison fails when either value is blank. In plain terms: the check compares the stored secret with the one you present, and if the stored secret is empty the comparison does not pass. An empty secret therefore does not authenticate.
The idea could still work with a different timing: spam a large number of requests and wait until Unicorn restarts, for example during an upgrade. If a git log runs last before the server shuts down, the file keeps the commit content instead of being truncated. The researcher reproduced this with around 32 connections followed by a restart:
# gitlab-ctl restart unicorn
ok: run: unicorn: (pid 46755) 1s
root@4290d4225642:/var/opt/gitlab/gitlab-rails/etc# cat gitlab_shell_secret
████████
Line by line:
# gitlab-ctl restart unicornrestarts the Unicorn web server using GitLab's control tool.ok: run: unicorn: (pid 46755) 1sis the tool's confirmation that Unicorn is running again, with its process id and how long it has been up.root@4290d4225642:/var/opt/gitlab/gitlab-rails/etc#is the prompt, showing the command is run asrootin the directory holding the secret file.cat gitlab_shell_secretprints the contents of the secret file.████████is the value found there, redacted here.
With the secret file holding commit content at the moment of shutdown, the value can be read and used against the internal API:
curl -s 'http://4290d4225642/api/v4/internal/check?secret_token=██████████'
{"api_version":"v4","gitlab_version":"12.0.3","gitlab_rev":"08a51a9db93","redis":true}
curl -s 'http://4290d4225642/api/v4/internal/discover?secret_token=███&user_id=1'
{"id":1,"name":"Administrator","username":"root"}
Line by line:
curl -ssends a request quietly, without progress noise.http://4290d4225642/api/v4/internal/checkis an internal API endpoint that checks whether a token is valid.?secret_token=██████████passes the stolen secret as a parameter.- The reply
{"api_version":"v4","gitlab_version":"12.0.3","gitlab_rev":"08a51a9db93","redis":true}is JSON, a structured text format, confirming the token was accepted and reporting the GitLab version and revision. - The second
curlcalls/api/v4/internal/discoverwith the secret anduser_id=1. - The reply
{"id":1,"name":"Administrator","username":"root"}shows that user id1is therootadministrator account.
The first call returns version and revision information from the internal API. The second resolves user id 1 to the root administrator account.
Root cause
The Commits API does not sanitise ref_name, and Gitaly places the value directly into the argument list of git log and git rev-list without a preceding --. Git's option parser therefore treats a value starting with -- as a flag. The -- that Gitaly does include comes after the injected value, so it cannot protect it.
The --output flag lets the value control where git writes. The follow-up rev-list call fails, but its failure happens after it has already truncated the target file, which turns a write primitive into a destructive one. A write primitive is simply the ability to write somewhere you should not; destructive means it can also erase.
The gitlab_shell_secret path was blocked only by an incidental property of Devise.secure_compare: a blank secret does not match. That is a defence that happens to hold for an empty file, not a defence against the injection itself.
Impact
An attacker who can call the Commits API can truncate arbitrary files writable by the git user, and can briefly replace them with a known commit or a list of commits. The report describes this as denial of service, loss of important data and potential privilege escalation. Denial of service means making the service unusable; privilege escalation means gaining more rights than you should have.
The concrete escalation path shown is the gitlab_shell_secret file. Truncating it does not by itself grant access because of the blank-token check, but the timing approach, spamming requests and waiting for a Unicorn restart so that a git log is the last command to touch the file, can leave the file containing commit data. That data can then be used as the internal API secret, which the researcher demonstrated by calling /api/v4/internal/check and /api/v4/internal/discover and resolving the root administrator. The report presents this as a potential path rather than a guaranteed one.
Fix
The report states the expected behaviour plainly: ref_name should be sanitised so that it cannot be used as git command flags. The report does not describe a specific patch or code change.
- Other API parameters that end up as git refs or revisions, such as compare, blame, diff or tree endpoints. A positive result is a request that causes git to write to a path you choose, or an error that reveals the injected flag was parsed as an option.
- Other git flags that write files or change behaviour, for example flags that redirect output or read configuration. A positive result is a file appearing at a path you control, or a change in command output that only the flag could cause.
- Ref values that begin with a single
-as well as--. A positive result is the same write or truncation behaviour with a shorter payload. - Timing the truncation against service restarts, as the researcher did with around 32 connections and a Unicorn restart. A positive result is a sensitive file left holding commit content rather than being empty.
This class of bug hides wherever user input is passed to a command-line tool as an argument without a -- separator, especially in services that wrap git, such as Gitaly. During recon, look for API parameters named after refs, revisions, branches or paths, and for error messages that echo the underlying command. Recon means the early exploration of a target to see what it exposes. The signal that a target is vulnerable is that a value starting with -- changes the command's behaviour rather than producing a normal "unknown revision" error.
To show enough impact, demonstrate a concrete file write or truncation on a path that matters, then connect it to a security boundary. Here the researcher did not stop at creating /tmp/written: they identified gitlab_shell_secret, explained why the simple truncation failed, and showed a timing-based route to reading the secret and using it against the internal API to reach the root administrator. That chain, with the requests and responses, is what turns a file-write primitive into a critical finding.
One limit to keep in mind when reproducing: the blank-token check means an empty secret file is not useful on its own, so the timing approach is the part that carries the escalation.
Glossary
- API: a way for programs to talk to a service over the web, sending labelled requests and getting structured answers.
- Parameter: a named value attached to a request, such as
ref_nameorpath. - Endpoint: a specific address on a service that performs one job, such as listing commits.
- Commit: a saved snapshot of changes in a code repository, identified by a long hash.
- Ref: a name that points at a commit, such as a branch or tag.
- Branch: a named line of development in a repository.
- Tag: a fixed name attached to a particular commit, often a release.
- Git: the version-control program that stores and walks commit history.
- Gitaly: GitLab's helper service that runs git commands on its behalf.
- RPC: a way for one program to ask another to perform an operation, as if calling a function remotely.
- Sanitise: clean input so it can only be used for its intended purpose.
- Command injection: a bug where user input is treated as part of a command rather than as plain data.
- Flag / option: a word starting with
-or--that changes how a command behaves. --separator: a marker telling a command that everything after it is a plain name, not an option.--output: a git option that writes command output to a named file.- Truncate: cut a file down to zero length, erasing its contents.
- Write primitive: the ability to write to a location you should not be able to reach.
- Denial of service: making a service unusable for its normal users.
- Privilege escalation: gaining more rights or access than you are supposed to have.
- Token / secret: a long random string used to prove a request comes from a trusted party.
- Unicorn: the web server process that runs GitLab's main application.
- JSON: a structured text format for data, made of keys and values.
- curl: a command-line tool for sending web requests and showing the raw response.
- Recon: the early exploration of a target to learn what it exposes.
- Race condition: a situation where the result depends on which of two events happens first.