Skip to content
RCE Write-up Advanced

Send()-ing Myself Belated Christmas Gifts - GitHub.com's Environment Variables & GHES Shell

An unvalidated Ruby reflection call let an attacker invoke arbitrary zero-argument methods on a Repository object through a request parameter. By choosing a method that returns the environment of a spawned git process, the researcher disclosed all environment variables of a GitHub.com production container, including access keys and secrets, and could escalate to remote code execution on GitHub Enterprise Server.

Ngo Wei Lin Follow

Published on starlabs.sg

Earlier this year, in mid-January, you might have come across this security announcement by GitHub.

Ngo Wei Lin (@Creastery), on starlabs.sg

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

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. 13 min read.

Context

GitHub Enterprise Server (GHES) is the self-hosted edition of GitHub, and its Ruby on Rails application source is largely identical to the code running on GitHub.com. The feature at the centre of this story is the repository picker used in an organisation's Actions settings: a controller renders a component that lists repositories as checkboxes, and each checkbox carries an identifier for its repository. The identifier is normally the repository's global relay ID, but the controller lets the caller choose which method of the Repository object is used to produce that identifier.

The bug is CVE-2024-0200. It began as a one-line unsafe reflection that looked low impact, and ended up disclosing every environment variable of a production GitHub.com container, including numerous access keys and secrets. On GHES it can be escalated further to remote code execution; on GitHub.com it cannot, because the environment variable needed for that escalation is not set there.

Setup

The research was done against GHES, with the source code of GitHub Enterprise Server (GHES) 3.11.0 used to pinpoint the root cause. A local test GHES installation was used for triage and later for the RCE research, and a test organisation on the production GitHub.com server was used for one round of testing. Exploiting the vulnerability requires the organisation owner role, and it affects GitHub.com and any GHES instance with GitHub Actions enabled.

Finding it

While researching GHES in early December 2023, the researcher found a potential but likely minor bug, and only got round to triaging it the day after Christmas. A search of the codebase turned up an unvalidated Kernel#send() call in Organizations::Settings::RepositoryItemsComponent, in app/components/organizations/settings/repository_items_component.rb:

Ruby
...
class Organizations::Settings::RepositoryItemsComponent < ApplicationComponent
  def initialize(organization:, repositories:, selected_repositories:, current_page:, total_count:, data_url:, aria_id_prefix:, repository_identifier_key: :global_relay_id, form_id: nil)
    @organization = organization
    @repositories = repositories
    @selected_repositories = selected_repositories
    @show_next_page = current_page * Orgs::RepositoryItemsHelper::PER_PAGE < total_count
    @data_url = data_url
    @current_page = current_page
    @aria_id_prefix = aria_id_prefix
    @repository_identifier_key = repository_identifier_key # [2]
    @form_id = form_id
  end
  ...
  def identifier_for(repository)
    repository.send(@repository_identifier_key) # [1]
  end
  ...
end

At [1], repository.send(@repository_identifier_key) is called with no validation of @repository_identifier_key, which is set at [2]. That means any method the object can reach can be invoked, including private and protected methods and anything inherited from ancestor classes.

The identifier_for() method is used in the template app/components/organizations/settings/repository_items_component.html.erb, which is rendered into the HTTP response body, at [3]:

Ruby
<%# erblint:counter ButtonComponentMigrationCounter 1 %>
<% @repositories.each do |repository| %>
  <li <% unless first_page? %> hidden <% end %> class="css-truncate d-flex flex-items-center width-full">
    <input
      <%= "form=#{@form_id}" if @form_id.present? %>
      type="checkbox" name="repository_ids[]"
      value="<%= identifier_for(repository) %>" # [3]
      id="<%= @aria_id_prefix %>-<%= repository.id %>"
...

Backtracing further, the component is initialised in app/controllers/orgs/actions_settings/repository_items_controller.rb:

Ruby
class Orgs::ActionsSettings::RepositoryItemsController < Orgs::Controller
  ...

  def index
    ...
    respond_to do |format|
      format.html do
        render(Organizations::Settings::RepositoryItemsComponent.new(
          organization: current_organization,
          repositories: additional_repositories(selected_repository_ids),
          selected_repositories: [],
          current_page: page,
          total_count: current_organization.repositories.size,
          data_url: data_url,
          aria_id_prefix: aria_id_prefix,
          repository_identifier_key: repository_identifier_key, # [4]
          form_id: form_id
        ), layout: false)
      end
    end
  end

  ...

  def rid_key
    params[:rid_key] # [6]
  end

  ...

  def repository_identifier_key
    return :global_relay_id unless rid_key.present? # [5]
    rid_key
  end

  ...
end

At [4], the result of repository_identifier_key() is passed as the repository_identifier_key keyword argument. At [5], :global_relay_id is returned only when rid_key() is absent; otherwise the method passes on params[:rid_key] from [6]. The chain is therefore: a request parameter reaches repository.send(), giving a zero-argument arbitrary method invocation on a Repository object.

Before going further, the report gives a primer on Ruby reflection. Almost everything in Ruby is an Object, and Object mixes in the Kernel module, so Kernel#send() is available on every object:

Ruby
class HelloWorld
  def print(*args)
    puts("Hello " + args.join(' '))
  end
end

obj = HelloWorld.new()
obj.print('world') # => 'Hello World'
obj.send('print', 'world') # => 'Hello World'

With two controllable arguments, unsafe reflection is trivially code execution:

Ruby
user_input1 = 'eval'
user_input2 = 'arbitrary Ruby code here'

obj.send(user_input1, user_input2)
# is equivalent to:
obj.send('eval', 'arbitrary Ruby code here')
# which is equivalent to:
Kernel.eval('arbitrary Ruby code here')
# which has the same effect as:
eval('arbitrary Ruby code here')
# note: because everything is an object, including the current context

With more than two controllable arguments, repeated send() calls do the same:

Ruby
obj.send('send', 'send', 'send', 'send', 'eval', '1+1')
# will call:
obj.send('send', 'send', 'send', 'eval', '1+1')
# ...
obj.send('eval', '1+1')
# to finally call:
eval('1+1')

The report notes that it found no discussion of unsafe reflection with only one controllable argument:

Ruby
user_input = 'method_name_here'
obj.send(user_input)

For that single-argument case, the report lists the default Object methods that could be useful:

Ruby
# Disclosing filepaths:
obj.send('__dir__') # leak resolved absolute path to directory containing current file
obj.send('caller')  # return execution call stack, and may leak filepaths

# Disclosing class name
obj.send('class')

# Disclosing method names
obj.send('__callee__')
obj.send('__method__')
obj.send('matching_methods')
obj.send('methods') # Object#methods() returns list of public and protected methods
obj.send('private_methods')
obj.send('protected_methods')
obj.send('public_methods')
obj.send('singleton_methods')

# Disclosing variable names
obj.send('instance_variables')
obj.send('global_variables')
obj.send('local_variables')

# Stringify variable
obj.send('inspect') # calls to_s recursively
obj.send('to_s')    # string representation of the object

# Read from standard input
obj.send('gets')
obj.send('readline')
obj.send('readlines')

# Terminates process (please exercise caution)
obj.send('abort')
obj.send('fail')
obj.send('exit')
obj.send('exit!')

In GitHub's case these were not needed, because the GHES source can be audited directly.

Exploitation

Step 1: understand what "zero-argument" really allows

The report stresses a common misassumption: a zero-argument invocation does not mean only methods that take no arguments. Methods whose arguments all have default values can be called too:

Ruby
class Test
  # zero arguments required
  def zero_arg()
  end

  # 1 positional argument required
  def one_pos_arg(arg1)
  end

  # 2 positional arguments required, but second argument has default value
  def one_pos_arg_one_default_pos_arg(arg1, arg2 = 'default')
  end

  # 2 positionals argument required, but both arguments have default values
  def two_default_pos_args(arg1 = 'default', arg2 = 'default')
  end

  # 1 keyword argument (similar to positional argument) required (no default value)
  def one_keyword_arg(keyword_arg1:)
  end

  # 1 keyword argument (has default value) required
  def one_default_keyword_arg(keyword_arg1: 'default')
  end

  # 1 positional (no default value) & 1 keyword argument (has default value) required
  def one_pos_arg_one_default_keyword_arg(arg1, keyword_arg2: 'default')
  end
end

obj = Test.new()
obj.send('zero_arg')                            # => OK
obj.send('one_pos_arg')                         # => in `one_pos_arg': wrong number of arguments (given 0, expected 1) (ArgumentError)
obj.send('one_pos_arg_one_default_pos_arg')     # => in `one_pos_arg_one_default_pos_arg': wrong number of arguments (given 0, expected 1..2) (ArgumentError)
obj.send('two_default_pos_args')                # => OK
obj.send('one_keyword_arg')                     # => in `one_keyword_arg`: missing keyword: :keyword_arg1 (ArgumentError)
obj.send('one_default_keyword_arg')             # => OK
obj.send('one_pos_arg_one_default_keyword_arg') # => in `one_pos_arg_one_default_keyword_arg': wrong number of arguments (given 0, expected 1) (ArgumentError)

Step 2: enumerate candidate methods

The Rails application source image contains more than 100k files (~1.5 GB), so grepping was not practical. Instead the researcher dropped into a Rails console on a test GHES setup and used reflection:

Ruby
repo = Repository.find(1) # get first repo
methods = [ # get names of all methods accessible by Repository object
  repo.public_methods(),
  repo.private_methods(),
  repo.protected_methods(),
].flatten()

methods.length() # => 5542

The Repository object has 5542 methods, most of them generated by Rails metaprogramming. To avoid ArgumentError, the list was filtered by arity. The report shows how arity maps to the signatures:

Ruby
class Test
  # zero arguments required
  def zero_arg()
  end

  # 1 positional argument required
  def one_pos_arg(arg1)
  end

  # 2 positional arguments required, but second argument has default value
  def one_pos_arg_one_default_pos_arg(arg1, arg2 = 'default')
  end

  # 2 positionals argument required, but both arguments have default values
  def two_default_pos_args(arg1 = 'default', arg2 = 'default')
  end

  # 1 keyword argument (similar to positional argument) required (no default value)
  def one_keyword_arg(keyword_arg1:)
  end

  # 1 keyword argument (has default value) required
  def one_default_keyword_arg(keyword_arg1: 'default')
  end

  # 1 positional (no default value) & 1 keyword argument (has default value) required
  def one_pos_arg_one_default_keyword_arg(arg1, keyword_arg2: 'default')
  end
end

obj = Test.new()
obj.method('zero_arg').arity()                            # => 0
obj.method('one_pos_arg').arity()                         # => 1
obj.method('one_pos_arg_one_default_pos_arg').arity()     # => -2
obj.method('two_default_pos_args').arity()                # => -1
obj.method('one_keyword_arg').arity()                     # => 1
obj.method('one_default_keyword_arg').arity()             # => -1
obj.method('one_pos_arg_one_default_keyword_arg').arity() # => -2

Only methods with arity 0 or -1 are usable. Filtering:

Ruby
repo = Repository.find(1)  # get first repo
repo_methods = [           # get names of all methods accessible by Repository object
  repo.public_methods(),
  repo.private_methods(),
  repo.protected_methods(),
].flatten()

repo_methods.length()      # => 5542
candidate_methods = repo_methods.select() do |method_name|
  [0, -1].include?(repo.method(method_name).arity())
end
candidate_methods.length() # => 3595

That still left 3595 methods. Rather than reduce further and risk missing something useful, the researcher dumped each method's name, arity and source location:

Ruby
candidate_methods.map!() do |method_name|
  method = repo.method(method_name)
  [
    method_name,
    method.arity(),
    method.source_location()
  ]
end
puts(candidate_methods.sort())

The output is a long list of 3595 methods and their locations:

Ruby
[
  [:!, [0, nil]],
  [:Nn_, [-1, ["/github/vendor/gems/3.2.2/ruby/3.2.0/gems/fast_gettext-2.2.0/lib/fast_gettext/translation.rb", 65]]],
  [:_, [-1, ["/github/vendor/gems/3.2.2/ruby/3.2.0/gems/gettext_i18n_rails-1.8.1/lib/gettext_i18n_rails/html_safe_translations.rb", 10]]],
  [:__callbacks, [0, ["/github/vendor/gems/3.2.2/ruby/3.2.0/gems/activesupport-7.1.0.alpha.bb4dbd14f8/lib/active_support/callbacks.rb", 70]]],
  ...
  [:xcode_clone_url, [-1, ["/github/app/helpers/url_helper.rb", 218]]],
  [:xcode_project?, [0, ["/github/packages/repositories/app/models/repository/git_dependency.rb", 323]]],
  [:xcode_urls_enabled?, [0, ["/github/app/helpers/url_helper.rb", 213]]],
  [:yield_self, [0, ["<internal:kernel>", 144]]]
]

Step 3: triage, and the accidental production test

While triaging, the local test GHES installation stopped working correctly and had to be reinstalled. Most candidate methods seemed to affect only the attacker's own organisation repositories or leak information such as server file paths. Rather than wait, the researcher tested on the production GitHub.com server in their own test organisation, judging the potential impact to be low. The response that came back left them speechless:

From the original on starlabs.sg

That response body contained ~2MB worth of environment variables belonging to GitHub.com, with a massive list of access keys and secrets. Testing stopped immediately, GitHub was alerted, and a vulnerability report was submitted soon after. The report credits Simon Gerst and Jorge Rosillo for helping make contact with GitHub's Security Incident Response Team (SIRT) for the early heads-up.

Step 4: the method that leaked the environment

The dangerous method is nw_fsck() in the Repository::GitDependency module at packages/repositories/app/models/repository/git_dependency.rb:

Ruby
module Repository::GitDependency
  ...
  def nw_fsck(trust_synced: false)
    rpc.nw_fsck(trust_synced: trust_synced)
  end
  ...
end

Its keyword argument has a default, so it is callable with no arguments, and in Ruby the last evaluated line is the implicit return value. The GitRPC backend implementation is in vendor/gitrpc/lib/gitrpc/backend/nw.rb:

Ruby
module GitRPC
  class Backend
    ...
    rpc_writer :nw_fsck, output_varies: true
    def nw_fsck(trust_synced: false)
      argv = []
      argv << "--connectivity-only"
      argv << "--trust-synced" if trust_synced
      spawn_git("nw-fsck", argv) # [7]
    end
    ...
  end
end

At [7], the return value is the git process created by spawn_git(), which eventually calls and returns GitRPC::Native#spawn():

Ruby
...
module GitRPC
  ...
  class Native
    ...
    def spawn(argv, input = nil, env = {}, options = {})
      ...
      {
        # Report unhandled signals as failure
        :ok        => !!process.status.success?,
        # Report the exit status as the signal number if we have it
        :status    => process.status.exitstatus || process.status.termsig,
        :signaled  => process.status.signaled?,
        :pid       => process.status.pid,
        :out       => process.out,
        :err       => process.err,
        :argv      => argv,
        :env       => env, # [8]
        :path      => @path,
        :options   => options,
        :truncated => truncated,
      }
    end
    ...
  end
end

The returned Hash includes the environment variables passed to the git process at [8]. Those come from vendor/gitrpc/lib/gitrpc/backend.rb:

Ruby
...
module GitRPC
  ...
  class Backend
    ...
    def self.environment
      @environment ||= ENV.to_h.freeze # [10]
    end
    ...
    def native
      @native ||= GitRPC::Native.new(path, native_env, native_options)
    end
    ...
    def native_env
      env = GitRPC::Backend.environment.dup # [9]
      env.merge!(options[:env] || {})
      env.merge!(GitRPC.extra_native_env || {})
      env["GITHUB_TELEMETRY_LOGS_NOOP"] = "true"
      env["GIT_DIR"] = path
      env["GIT_LITERAL_PATHSPECS"] = "1"
      env["GIT_SOCKSTAT_VAR_via"] = "gitrpc"
      if options[:info]
        git_sockstat_var_options.each do |(prefix, sym)|
          env["GIT_SOCKSTAT_VAR_#{sym}"] = "#{prefix}#{options[:info][sym]}" if options[:info][sym]
        end
      end
      if alternates = alternate_object_paths
        env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = alternates.join(":")
      end
      env
    end
    ...
  end
end

At [9], native_env() duplicates the hash returned by GitRPC::Backend::environment() at [10], which is a copy of all environment variables passed to Rails. Because GitRPC::Native#spawn() returns that hash and Repository::GitDependency#nw_fsck() returns it to the caller, the reflection bug discloses every environment variable passed to Rails.

Step 5: the actual impact

The researcher gained access to 1220 environment variables (~2MB) containing a large number of production access keys. Testing was stopped immediately and GitHub was contacted.

Step 6: escalating to RCE on GHES

The next day, research continued on the new test GHES setup to see whether the impact could be escalated to remote code execution, deliberately not using the access keys and not touching the production GitHub.com environment further. The environment variable list included ENTERPRISE_SESSION_SECRET, which signs marshalled data stored in session cookies. As demonstrated in @iblue's earlier RCE in the GitHub Enterprise management console, knowing that secret lets an attacker sign arbitrary serialised data:

Ruby on Rails implements session storage using a cryptographically signed serialised Ruby Hash. This Hash is serialised into a cookie using Marshal.dump and subsequently deserialised using Marshal.load. If an attacker can construct a valid signature, they can create a session cookie that contains arbitrary input passed to Marshal.load. As noted by the Ruby documentation for Marshal.load, this can result in code execution:

By design, ::load can deserialise almost any class loaded into the Ruby process. In many cases this can lead to remote code execution if the Marshal data is loaded from an untrusted source.

As a result, ::load is not suitable as a general purpose serialisation format and you should never unmarshal user supplied input or other untrusted data.

This is a clear path to RCE, though the report says a few more hurdles remain, to be discussed another time. ENTERPRISE_SESSION_SECRET is not set on GitHub.com, so there is no quick route to RCE there other than using the access keys, which the researcher explicitly advises against. In short: the vulnerability chains to RCE on GHES, but GitHub.com is not affected by that escalation.

Root cause

The mistake is the unvalidated Kernel#send() in Organizations::Settings::RepositoryItemsComponent#identifier_for(), where @repository_identifier_key comes straight from the rid_key request parameter via Orgs::ActionsSettings::RepositoryItemsController#repository_identifier_key(). Nothing constrains the value to the intended identifier methods, so any reachable method of the Repository object can be invoked. The impact is amplified by Repository::GitDependency#nw_fsck(), which returns the result of spawning a git process, and by GitRPC::Native#spawn() including the process environment in that result, which is a copy of the Rails process environment. The report's suggested defence is to validate the rid_key parameter against an allowlist.

Impact

On GitHub.com, an organisation owner could disclose all environment variables of a production container, including numerous access keys and secrets: 1220 variables, about 2MB. On GHES with GitHub Actions enabled, the same bug can be chained to RCE using ENTERPRISE_SESSION_SECRET, which is not present on GitHub.com. The report notes that the vulnerability was not found to have been exploited in the wild previously, following GitHub's investigation.

Fix

GitHub hotfixed GitHub.com production servers on 2023-12-26, the same day as the disclosure and initial contact, and released a vendor patch and announcement on 2024-01-16. The report's suggested mitigations are:

  1. Validate the rid_key parameter in Orgs::ActionsSettings::RepositoryItemsController against an allowlist so only intended Repository methods can be invoked.
  2. Revoke and regenerate all secrets used in GitHub.com or any GHES instance that may have been compromised.
  3. Spawn git processes with a minimal set of environment variables instead of the 1220 currently passed on GitHub.com.

For detection, the report suggests checking access logs for requests to /orgainzations/<organisation_name>/settings/actions/repository_items with an abnormal rid_key value, noting that Rails also accepts rid_key in the request body.

Variants to test

  1. Look for other controllers that pass a request parameter into send() on a model, for example identifier or key selection parameters. A positive result is a parameter value that changes which method is called and returns data unrelated to the rendered page.
  2. Enumerate methods with arity 0 or -1 on objects reachable from such sinks, as done here with public_methods, private_methods and protected_methods. A positive result is a method whose return value appears in the response body.
  3. Look for methods that wrap process spawning or RPC calls and return their result, especially ones with defaulted keyword arguments. A positive result is a response containing process output or environment data.
  4. Check whether process-spawning wrappers include the full parent environment. A positive result is a returned hash containing variables that belong to the application server rather than the spawned tool.
  5. On Rails applications, check whether a leaked signing secret for session cookies allows forging a Marshal-serialised session. A positive result is a forged cookie that is accepted and deserialised.

Timeline

  • 2023-12-26 Vendor Disclosure
  • 2023-12-26 Initial Vendor Contact
  • 2023-12-26 Hotfixed on Github.com Production Servers
  • 2023-12-28 Sent RCE Report to Vendor
  • 2024-01-16 Vendor Patch & Announcement Release
  • 2024-05-06 Public Release

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. 29 min read.

What happened, in plain words

GitHub is a website where people store and share computer code. Besides the public website, GitHub sells a version that companies can install on their own computers, called GitHub Enterprise Server (GHES). The code inside both versions is mostly the same.

In December 2023 a security researcher was looking at the GHES code. He found a small mistake in a page that lets an organisation pick which repositories a setting applies to. That page took a value from the visitor's request and used it to decide which internal function to run. Because the value was never checked, a visitor could ask the server to run almost any function it knew about.

He expected this to be a minor bug. Then, while testing on the real GitHub.com site, the server sent back about 2 megabytes of data: the complete list of environment variables of a production server, including many access keys and secrets. Environment variables are the settings a program reads when it starts, and they often hold passwords and keys.

He stopped testing at once, warned GitHub, and wrote a report. The next day he showed that on GHES the same bug can be pushed further, to running his own code on the server (remote code execution, or RCE). On GitHub.com that last step is not possible, because the particular secret it needs is not set there.

The bug is tracked as CVE-2024-0200. GitHub fixed GitHub.com the same day it was told, and released a patch and an announcement on 16 January 2024.

Background: what GitHub Enterprise Server and the repository picker are

GitHub Enterprise Server is software a company installs on its own machines. It is written in a programming language called Ruby, using a framework called Ruby on Rails. A framework is a ready-made set of building blocks that saves programmers from writing everything from scratch. Rails applications are organised into controllers (code that handles an incoming request) and views or templates (code that produces the page sent back).

The feature involved here is the repository picker in an organisation's Actions settings. GitHub Actions is GitHub's system for running automated tasks. In the settings page, an organisation owner sees a list of repositories with a checkbox next to each one. Each checkbox needs a value that identifies its repository, and that value is produced by calling a function on the repository.

Normally the identifier is the repository's global relay ID, an internal number used to refer to the repository. The problem is that the controller lets the person making the request choose which function of the repository object is used to produce that identifier.

A short introduction to Ruby reflection

Before the bug makes sense, you need one idea: reflection.

In Ruby, almost everything is an object: a number, a piece of text, a repository record. All objects share a set of built-in abilities, because they all include a common module called Kernel. One of those abilities is send(). send() takes the name of a function as text and runs that function on the object. This is called reflection, or indirect invocation: you do not write the function name in your code, you pass it as data at runtime.

A simple everyday comparison: normally you press a button labelled "Print". With reflection, you hand someone a piece of paper with a button name written on it, and they press whichever button the paper names. If you can write anything on the paper, you can make them press any button in the room.

Here is the report's example:

Ruby
class HelloWorld
  def print(*args)
    puts("Hello " + args.join(' '))
  end
end

obj = HelloWorld.new()
obj.print('world') # => 'Hello World'
obj.send('print', 'world') # => 'Hello World'

Line by line:

  • class HelloWorld starts the definition of a new kind of object called HelloWorld.
  • def print(*args) defines a function named print that accepts any number of arguments and collects them in a list called args.
  • puts("Hello " + args.join(' ')) prints the word Hello followed by the arguments joined with spaces.
  • end closes the function, and the second end closes the class.
  • obj = HelloWorld.new() creates one such object and stores it in obj.
  • obj.print('world') calls the function directly and prints Hello World.
  • obj.send('print', 'world') does exactly the same thing, but the function name is given as text. That is reflection.

Why does this matter for security? Because if a program lets a visitor supply the text that goes into send(), the visitor decides which function runs. That is called an unsafe reflection, and it is a classic place to look for bugs.

With two values under the attacker's control, unsafe reflection becomes code execution almost immediately:

Ruby
user_input1 = 'eval'
user_input2 = 'arbitrary Ruby code here'

obj.send(user_input1, user_input2)
# is equivalent to:
obj.send('eval', 'arbitrary Ruby code here')
# which is equivalent to:
Kernel.eval('arbitrary Ruby code here')
# which has the same effect as:
eval('arbitrary Ruby code here')
# note: because everything is an object, including the current context

Line by line:

  • The first two lines store two pieces of text: a function name, eval, and some Ruby source code.
  • obj.send(user_input1, user_input2) runs the function named in the first variable, passing the second variable as its argument.
  • The comments spell out the chain: send with eval means "run this text as Ruby code". eval is Ruby's built-in function for executing a string as code.
  • The last comment notes that even the current context is an object, so eval is reachable from anywhere.

If the attacker controls more than two values, repeated send() calls reach the same place:

Ruby
obj.send('send', 'send', 'send', 'send', 'eval', '1+1')
# will call:
obj.send('send', 'send', 'send', 'eval', '1+1')
# ...
obj.send('eval', '1+1')
# to finally call:
eval('1+1')

Line by line:

  • The first call runs the function named send, passing the remaining values along.
  • Each nested send peels off one layer, until only eval and 1+1 remain.
  • The final call evaluates 1+1 as code. The same trick would run any code the attacker likes.

The report notes that it found no discussion of the case with only one controllable value:

Ruby
user_input = 'method_name_here'
obj.send(user_input)

Line by line:

  • user_input holds a function name chosen by the attacker.
  • obj.send(user_input) runs that function on the object, with no arguments.

At first glance this looks weak: you can only run functions that need no arguments. The report lists the built-in functions that could still be useful in that situation:

Ruby
# Disclosing filepaths:
obj.send('__dir__') # leak resolved absolute path to directory containing current file
obj.send('caller')  # return execution call stack, and may leak filepaths

# Disclosing class name
obj.send('class')

# Disclosing method names
obj.send('__callee__')
obj.send('__method__')
obj.send('matching_methods')
obj.send('methods') # Object#methods() returns list of public and protected methods
obj.send('private_methods')
obj.send('protected_methods')
obj.send('public_methods')
obj.send('singleton_methods')

# Disclosing variable names
obj.send('instance_variables')
obj.send('global_variables')
obj.send('local_variables')

# Stringify variable
obj.send('inspect') # calls to_s recursively
obj.send('to_s')    # string representation of the object

# Read from standard input
obj.send('gets')
obj.send('readline')
obj.send('readlines')

# Terminates process (please exercise caution)
obj.send('abort')
obj.send('fail')
obj.send('exit')
obj.send('exit!')

Line by line, grouped by the comments:

  • __dir__ returns the folder the current file lives in, which reveals the server's folder layout. caller returns the list of functions that led to this point, which can also reveal file paths.
  • class returns the name of the object's type.
  • __callee__, __method__, matching_methods, methods, private_methods, protected_methods, public_methods and singleton_methods all return names of functions the object knows. Knowing the names is the first step to finding a dangerous one.
  • instance_variables, global_variables and local_variables return names of stored values.
  • inspect and to_s turn the object into text, which may contain useful data.
  • gets, readline and readlines read input from the program's standard input, the stream a program normally reads typed input from.
  • abort, fail, exit and exit! stop the program. The report marks these with 'please exercise caution'.

In GitHub's case none of this was needed, because the GHES source code can be read directly. That is a big advantage: instead of guessing, the researcher could look at the code and see exactly what was reachable.

Finding the vulnerability

The source code examined was from GitHub Enterprise Server (GHES) 3.11.0. A search of the codebase found an unchecked Kernel#send() call in a class called Organizations::Settings::RepositoryItemsComponent, in the file app/components/organizations/settings/repository_items_component.rb:

Ruby
...
class Organizations::Settings::RepositoryItemsComponent < ApplicationComponent
  def initialize(organization:, repositories:, selected_repositories:, current_page:, total_count:, data_url:, aria_id_prefix:, repository_identifier_key: :global_relay_id, form_id: nil)
    @organization = organization
    @repositories = repositories
    @selected_repositories = selected_repositories
    @show_next_page = current_page * Orgs::RepositoryItemsHelper::PER_PAGE < total_count
    @data_url = data_url
    @current_page = current_page
    @aria_id_prefix = aria_id_prefix
    @repository_identifier_key = repository_identifier_key # [2]
    @form_id = form_id
  end
  ...
  def identifier_for(repository)
    repository.send(@repository_identifier_key) # [1]
  end
  ...
end

Line by line:

  • class Organizations::Settings::RepositoryItemsComponent < ApplicationComponent defines a component, a reusable piece of a web page. The < ApplicationComponent part means it inherits from a general component class.
  • def initialize(...) is the setup function that runs when a new component is created. The long list of names are the values it needs, such as the organisation, the repositories, the current page and so on.
  • Each line starting with @ stores one of those values on the object. In Ruby, a name starting with @ is an instance variable, a value that belongs to that particular object and can be used by its other functions.
  • @repository_identifier_key = repository_identifier_key # [2] stores the chosen identifier function name. The default is :global_relay_id, but the caller can supply something else. The # [2] is a marker the report uses to refer back to this line.
  • def identifier_for(repository) defines a function that, given a repository, returns its identifier.
  • repository.send(@repository_identifier_key) # [1] is the bug. It runs whatever function name is stored in @repository_identifier_key on the repository object. Nothing checks that the name is one of the intended identifier functions. The # [1] marker refers back to this line.

Because there is no check, any function the repository object can reach can be run, including private and protected ones and anything inherited from parent classes. Private and protected are Ruby's labels for functions that are meant to be used only inside the object or its family, not by outsiders.

The identifier_for() function is used in the page template app/components/organizations/settings/repository_items_component.html.erb, which is turned into the HTML sent back to the browser, at marker [3]:

Ruby
<%# erblint:counter ButtonComponentMigrationCounter 1 %>
<% @repositories.each do |repository| %>
  <li <% unless first_page? %> hidden <% end %> class="css-truncate d-flex flex-items-center width-full">
    <input
      <%= "form=#{@form_id}" if @form_id.present? %>
      type="checkbox" name="repository_ids[]"
      value="<%= identifier_for(repository) %>" # [3]
      id="<%= @aria_id_prefix %>-<%= repository.id %>"
...

Line by line:

  • The first line is a comment for a code-checking tool, not part of the page.
  • <% @repositories.each do |repository| %> starts a loop over every repository in the list.
  • The <li ...> line opens a list item. The <% unless first_page? %> hidden <% end %> part adds the word hidden unless this is the first page, so later pages start hidden.
  • <input starts an HTML input element, here a checkbox.
  • The line with form=#{@form_id} adds a form attribute only if a form ID is present.
  • type="checkbox" name="repository_ids[]" makes it a checkbox whose name is repository_ids[], so the browser sends the ticked values under that name.
  • value="<%= identifier_for(repository) %>" # [3] is where the bug's result appears. The identifier produced by the vulnerable function becomes the checkbox's value, which is sent back to the server when the form is submitted. The # [3] marker refers to this line.
  • The id= line builds a unique HTML ID from a prefix and the repository's own ID.

Following the chain backwards, the component is created in app/controllers/orgs/actions_settings/repository_items_controller.rb:

Ruby
class Orgs::ActionsSettings::RepositoryItemsController < Orgs::Controller
  ...

  def index
    ...
    respond_to do |format|
      format.html do
        render(Organizations::Settings::RepositoryItemsComponent.new(
          organization: current_organization,
          repositories: additional_repositories(selected_repository_ids),
          selected_repositories: [],
          current_page: page,
          total_count: current_organization.repositories.size,
          data_url: data_url,
          aria_id_prefix: aria_id_prefix,
          repository_identifier_key: repository_identifier_key, # [4]
          form_id: form_id
        ), layout: false)
      end
    end
  end

  ...

  def rid_key
    params[:rid_key] # [6]
  end

  ...

  def repository_identifier_key
    return :global_relay_id unless rid_key.present? # [5]
    rid_key
  end

  ...
end

Line by line:

  • class Orgs::ActionsSettings::RepositoryItemsController < Orgs::Controller defines the controller that handles requests for this settings page.
  • def index is the function that runs when the page is requested.
  • respond_to do |format| and format.html do say: if the browser asks for an HTML page, do the following.
  • render(Organizations::Settings::RepositoryItemsComponent.new(...)) creates the component and renders it as the response.
  • Inside the list of values, repository_identifier_key: repository_identifier_key, # [4] passes the result of the repository_identifier_key() function into the component. The # [4] marker refers to this line.
  • def rid_key defines a small helper. params[:rid_key] # [6] reads the value named rid_key from the request. params is Rails' name for the collection of values sent by the browser, whether in the URL or in the body of the request. The # [6] marker refers to this line.
  • def repository_identifier_key decides which identifier function to use. return :global_relay_id unless rid_key.present? # [5] means: if the request did not include rid_key, use the normal identifier. The # [5] marker refers to this line.
  • rid_key on the last line returns the value from the request when it is present.

Putting it together: a value typed into the request, rid_key, travels through repository_identifier_key() into the component, and from there into repository.send(). The result is that a visitor can run an arbitrary function with no arguments on a repository object.

In search of impact

This is the one-argument case from the introduction. None of the built-in functions listed earlier helped here: the information they return was either already known or not useful. So the question became: what else can a repository object do?

First, the report clears up a common misunderstanding. "Zero-argument invocation" does not mean only functions that take no arguments at all. Functions whose arguments all have default values can also be called with nothing. A default value is a fallback the programmer writes into the function definition, used when the caller does not supply that argument.

Ruby
class Test
  # zero arguments required
  def zero_arg()
  end

  # 1 positional argument required
  def one_pos_arg(arg1)
  end

  # 2 positional arguments required, but second argument has default value
  def one_pos_arg_one_default_pos_arg(arg1, arg2 = 'default')
  end

  # 2 positionals argument required, but both arguments have default values
  def two_default_pos_args(arg1 = 'default', arg2 = 'default')
  end

  # 1 keyword argument (similar to positional argument) required (no default value)
  def one_keyword_arg(keyword_arg1:)
  end

  # 1 keyword argument (has default value) required
  def one_default_keyword_arg(keyword_arg1: 'default')
  end

  # 1 positional (no default value) & 1 keyword argument (has default value) required
  def one_pos_arg_one_default_keyword_arg(arg1, keyword_arg2: 'default')
  end
end

obj = Test.new()
obj.send('zero_arg')                            # => OK
obj.send('one_pos_arg')                         # => in `one_pos_arg': wrong number of arguments (given 0, expected 1) (ArgumentError)
obj.send('one_pos_arg_one_default_pos_arg')     # => in `one_pos_arg_one_default_pos_arg': wrong number of arguments (given 0, expected 1..2) (ArgumentError)
obj.send('two_default_pos_args')                # => OK
obj.send('one_keyword_arg')                     # => in `one_keyword_arg`: missing keyword: :keyword_arg1 (ArgumentError)
obj.send('one_default_keyword_arg')             # => OK
obj.send('one_pos_arg_one_default_keyword_arg') # => in `one_pos_arg_one_default_keyword_arg': wrong number of arguments (given 0, expected 1) (ArgumentError)

Line by line:

  • The class Test defines seven functions to show different argument styles. A positional argument is one passed by position, like the first or second item in a list. A keyword argument is one passed by name, like keyword_arg1: 'default'.
  • zero_arg takes nothing.
  • one_pos_arg(arg1) needs one positional argument.
  • one_pos_arg_one_default_pos_arg(arg1, arg2 = 'default') needs one, and the second falls back to 'default'.
  • two_default_pos_args(arg1 = 'default', arg2 = 'default') can be called with nothing at all.
  • one_keyword_arg(keyword_arg1:) needs a keyword argument and has no fallback.
  • one_default_keyword_arg(keyword_arg1: 'default') has a fallback, so it can be called with nothing.
  • one_pos_arg_one_default_keyword_arg(arg1, keyword_arg2: 'default') still needs the first positional argument, so it cannot be called with nothing.
  • The obj.send(...) lines try each one. The ones marked OK ran; the others raised ArgumentError, Ruby's error for the wrong number of arguments.

So the attacker can call any function whose required arguments are all optional. That widens the search a lot.

Triaging candidate methods

How do you find a useful function among thousands? Searching the source with grep, a command-line text search tool, was not practical: the main Docker image holding the Rails application source contains more than 100k files (~1.5 GB). A Docker image is a packaged bundle of software and its files.

Instead, the researcher opened a Rails console on a test GHES installation. A Rails console is an interactive prompt where you can run Ruby code inside the running application, which makes it easy to ask the application about itself. Using reflection, the list of functions a repository object knows was collected:

Ruby
repo = Repository.find(1) # get first repo
methods = [ # get names of all methods accessible by Repository object
  repo.public_methods(),
  repo.private_methods(),
  repo.protected_methods(),
].flatten()

methods.length() # => 5542

Line by line:

  • repo = Repository.find(1) loads the first repository record and stores it in repo.
  • The list collects three groups of function names: public (callable from outside), private (meant for internal use) and protected (meant for the object's family).
  • .flatten() turns the three lists into one flat list.
  • methods.length() counts the entries. The answer is 5542.

5542 functions on one object is a lot. Most come from Rails generating getter and setter functions automatically. A getter reads a stored value, a setter writes one. This automatic generation is called metaprogramming: code that writes code.

To cut the list down, the researcher filtered by arity. Arity is the number of arguments a function expects. The report shows how arity numbers map to the signatures:

Ruby
class Test
  # zero arguments required
  def zero_arg()
  end

  # 1 positional argument required
  def one_pos_arg(arg1)
  end

  # 2 positional arguments required, but second argument has default value
  def one_pos_arg_one_default_pos_arg(arg1, arg2 = 'default')
  end

  # 2 positionals argument required, but both arguments have default values
  def two_default_pos_args(arg1 = 'default', arg2 = 'default')
  end

  # 1 keyword argument (similar to positional argument) required (no default value)
  def one_keyword_arg(keyword_arg1:)
  end

  # 1 keyword argument (has default value) required
  def one_default_keyword_arg(keyword_arg1: 'default')
  end

  # 1 positional (no default value) & 1 keyword argument (has default value) required
  def one_pos_arg_one_default_keyword_arg(arg1, keyword_arg2: 'default')
  end
end

obj = Test.new()
obj.method('zero_arg').arity()                            # => 0
obj.method('one_pos_arg').arity()                         # => 1
obj.method('one_pos_arg_one_default_pos_arg').arity()     # => -2
obj.method('two_default_pos_args').arity()                # => -1
obj.method('one_keyword_arg').arity()                     # => 1
obj.method('one_default_keyword_arg').arity()             # => -1
obj.method('one_pos_arg_one_default_keyword_arg').arity() # => -2

Line by line:

  • The class is the same as before, so the same seven functions are available.
  • obj.method('name') looks up a function by name, and .arity() reports how many arguments it expects.
  • 0 means no arguments needed.
  • 1 means exactly one required argument.
  • -1 means the function can be called with no arguments because everything has a default.
  • -2 means at least one argument is still required, so it cannot be called with nothing.

Only functions with arity 0 or -1 are usable here. Filtering the list:

Ruby
repo = Repository.find(1)  # get first repo
repo_methods = [           # get names of all methods accessible by Repository object
  repo.public_methods(),
  repo.private_methods(),
  repo.protected_methods(),
].flatten()

repo_methods.length()      # => 5542
candidate_methods = repo_methods.select() do |method_name|
  [0, -1].include?(repo.method(method_name).arity())
end
candidate_methods.length() # => 3595

Line by line:

  • The first block is the same as before: load a repository and collect all its function names, 5542 of them.
  • repo_methods.select() do |method_name| keeps only the names for which the block returns true.
  • [0, -1].include?(repo.method(method_name).arity()) checks whether the function's arity is 0 or -1.
  • candidate_methods.length() counts what survived: 3595.

That is still a lot. Rather than filter further and risk missing something useful, the researcher printed each function's name, arity and source location. The source location is the file and line where the function is defined, which tells you which part of the application it belongs to.

Ruby
candidate_methods.map!() do |method_name|
  method = repo.method(method_name)
  [
    method_name,
    method.arity(),
    method.source_location()
  ]
end
puts(candidate_methods.sort())

Line by line:

  • candidate_methods.map!() do |method_name| replaces each name in the list with a richer entry.
  • method = repo.method(method_name) looks up the function object.
  • The three-element list holds the name, the arity and the source location.
  • puts(candidate_methods.sort()) prints the sorted list.

The output is a long list of 3595 entries:

Ruby
[
  [:!, [0, nil]],
  [:Nn_, [-1, ["/github/vendor/gems/3.2.2/ruby/3.2.0/gems/fast_gettext-2.2.0/lib/fast_gettext/translation.rb", 65]]],
  [:_, [-1, ["/github/vendor/gems/3.2.2/ruby/3.2.0/gems/gettext_i18n_rails-1.8.1/lib/gettext_i18n_rails/html_safe_translations.rb", 10]]],
  [:__callbacks, [0, ["/github/vendor/gems/3.2.2/ruby/3.2.0/gems/activesupport-7.1.0.alpha.bb4dbd14f8/lib/active_support/callbacks.rb", 70]]],
  ...
  [:xcode_clone_url, [-1, ["/github/app/helpers/url_helper.rb", 218]]],
  [:xcode_project?, [0, ["/github/packages/repositories/app/models/repository/git_dependency.rb", 323]]],
  [:xcode_urls_enabled?, [0, ["/github/app/helpers/url_helper.rb", 213]]],
  [:yield_self, [0, ["<internal:kernel>", 144]]]
]

Line by line:

  • Each entry is a pair: the function name, then a pair of arity and source location.
  • [:!, [0, nil]] is the ! function, arity 0, with no source location because it is built in.
  • The entries with paths under /github/vendor/gems/... come from third-party libraries bundled with the application.
  • The entries with paths under /github/app/... and /github/packages/... are GitHub's own code. These are the interesting ones, because they are more likely to do something specific to GitHub.
  • [:xcode_project?, [0, ["/github/packages/repositories/app/models/repository/git_dependency.rb", 323]]] is one of them, and it points at the file that later turns out to contain the dangerous function.

Getting the environment variables

While triaging, the local test GHES installation stopped working correctly and had to be reinstalled. Most candidate functions seemed to affect only the attacker's own organisation repositories, or to leak information such as file paths on the server, which might be useful later but was not dramatic. Rather than sit idle, the researcher decided to test on the production GitHub.com server, in their own test organisation, judging the likely impact to be low.

That judgement was wrong. The response that came back left them speechless:

From the original on starlabs.sg

The response body contained ~2MB worth of environment variables belonging to GitHub.com, containing a massive list of access keys and secrets. An access key is a secret string that lets a program prove its identity to another service, much like a password. Testing stopped immediately, GitHub was alerted, and a vulnerability report was submitted soon after. The report credits Simon Gerst and Jorge Rosillo for helping make contact with GitHub's Security Incident Response Team (SIRT), the group that handles security incidents, so the warning arrived early.

How did secrets end up in a web page? The answer is the function nw_fsck() in the Repository::GitDependency module, at packages/repositories/app/models/repository/git_dependency.rb:

Ruby
module Repository::GitDependency
  ...
  def nw_fsck(trust_synced: false)
    rpc.nw_fsck(trust_synced: trust_synced)
  end
  ...
end

Line by line:

  • module Repository::GitDependency defines a module, a bundle of functions that can be mixed into a class. Here it is mixed into the repository object.
  • def nw_fsck(trust_synced: false) defines a function with one keyword argument that has a default of false. Because of that default, it can be called with no arguments, which is exactly what the bug allows.
  • rpc.nw_fsck(trust_synced: trust_synced) passes the call on to another object called rpc, which stands for remote procedure call, a way of asking another part of the system to do work.
  • In Ruby, the last evaluated line of a function is its implicit return value. So whatever rpc.nw_fsck(...) returns is what the caller receives.

The GitRPC backend implementation is in vendor/gitrpc/lib/gitrpc/backend/nw.rb:

Ruby
module GitRPC
  class Backend
    ...
    rpc_writer :nw_fsck, output_varies: true
    def nw_fsck(trust_synced: false)
      argv = []
      argv << "--connectivity-only"
      argv << "--trust-synced" if trust_synced
      spawn_git("nw-fsck", argv) # [7]
    end
    ...
  end
end

Line by line:

  • module GitRPC and class Backend define the part of the system that talks to git, the version-control program underneath GitHub.
  • rpc_writer :nw_fsck, output_varies: true registers this function as one that can be called remotely, and notes that its output varies.
  • def nw_fsck(trust_synced: false) is the backend version of the same function.
  • argv = [] starts an empty list of command-line arguments.
  • argv << "--connectivity-only" adds a flag that tells git to check connectivity only.
  • argv << "--trust-synced" if trust_synced adds another flag only when the argument is true.
  • spawn_git("nw-fsck", argv) # [7] starts a git process with those arguments. The # [7] marker refers to this line. The return value of this line is what the function returns.

At [7], the return value is the git process created by spawn_git(), which eventually calls and returns GitRPC::Native#spawn():

Ruby
...
module GitRPC
  ...
  class Native
    ...
    def spawn(argv, input = nil, env = {}, options = {})
      ...
      {
        # Report unhandled signals as failure
        :ok        => !!process.status.success?,
        # Report the exit status as the signal number if we have it
        :status    => process.status.exitstatus || process.status.termsig,
        :signaled  => process.status.signaled?,
        :pid       => process.status.pid,
        :out       => process.out,
        :err       => process.err,
        :argv      => argv,
        :env       => env, # [8]
        :path      => @path,
        :options   => options,
        :truncated => truncated,
      }
    end
    ...
  end
end

Line by line:

  • def spawn(argv, input = nil, env = {}, options = {}) defines the function that actually starts a process. All its arguments have defaults, so it can be called with nothing.
  • The { ... } block builds a hash, which is Ruby's name for a collection of labelled values, like a form with named fields.
  • :ok records whether the process succeeded.
  • :status records the exit status, or the signal number if the process was killed by a signal.
  • :signaled records whether a signal was involved.
  • :pid records the process ID, the number the operating system gives each running program.
  • :out and :err record the process's normal output and error output.
  • :argv records the command-line arguments.
  • :env => env, # [8] records the environment variables passed to the process. The # [8] marker refers to this line. This is the field that later turns out to hold the secrets.
  • :path, :options and :truncated record the path, the options and whether output was cut short.

So the returned hash includes the environment variables passed to the git process at [8]. Where do those come from? From vendor/gitrpc/lib/gitrpc/backend.rb:

Ruby
...
module GitRPC
  ...
  class Backend
    ...
    def self.environment
      @environment ||= ENV.to_h.freeze # [10]
    end
    ...
    def native
      @native ||= GitRPC::Native.new(path, native_env, native_options)
    end
    ...
    def native_env
      env = GitRPC::Backend.environment.dup # [9]
      env.merge!(options[:env] || {})
      env.merge!(GitRPC.extra_native_env || {})
      env["GITHUB_TELEMETRY_LOGS_NOOP"] = "true"
      env["GIT_DIR"] = path
      env["GIT_LITERAL_PATHSPECS"] = "1"
      env["GIT_SOCKSTAT_VAR_via"] = "gitrpc"
      if options[:info]
        git_sockstat_var_options.each do |(prefix, sym)|
          env["GIT_SOCKSTAT_VAR_#{sym}"] = "#{prefix}#{options[:info][sym]}" if options[:info][sym]
        end
      end
      if alternates = alternate_object_paths
        env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = alternates.join(":")
      end
      env
    end
    ...
  end
end

Line by line:

  • def self.environment defines a function on the class itself. @environment ||= ENV.to_h.freeze # [10] stores a frozen copy of ENV, the collection of all environment variables the Rails application received when it started. ||= means "only compute this the first time". freeze prevents later changes. The # [10] marker refers to this line.
  • def native creates the object that starts processes, passing it the environment from native_env.
  • def native_env builds the environment for the child process.
  • env = GitRPC::Backend.environment.dup # [9] makes a copy of the full application environment. The # [9] marker refers to this line.
  • env.merge!(options[:env] || {}) adds any extra variables supplied in the options.
  • env.merge!(GitRPC.extra_native_env || {}) adds any extra variables configured for GitRPC.
  • The next four lines set git-specific variables: a telemetry flag, the repository directory, a path-matching flag and a marker saying the call came via gitrpc.
  • The if options[:info] block adds more variables when info options are present.
  • The if alternates = alternate_object_paths block adds a list of alternate object directories, joined with colons.
  • env on the last line returns the finished hash.

At [9], native_env() copies the hash returned by GitRPC::Backend::environment() at [10], which is a copy of all environment variables passed to Rails. Because GitRPC::Native#spawn() returns that hash and Repository::GitDependency#nw_fsck() returns it to the caller, the reflection bug discloses every environment variable passed to Rails.

In plain terms: the attacker asked the repository object to run nw_fsck. That function started a git process and returned a description of it. The description included the environment variables given to the process, and those were copied from the whole application. The description was then placed into the checkbox value on the page, and sent back to the browser.

The actual impact

The researcher gained access to 1220 environment variables (~2MB) containing a large number of production access keys. Testing was stopped immediately and GitHub was contacted.

Getting remote code execution (RCE)

The next day, research continued on the new test GHES setup to see whether the impact could be escalated to remote code execution. RCE means running your own commands on someone else's server. The researcher deliberately did not use the access keys and did not touch the production GitHub.com environment again.

The environment variable list included ENTERPRISE_SESSION_SECRET. A secret in this context is a long random string used to sign data so that it cannot be forged. This particular one signs the data stored in session cookies. A cookie is a small piece of data a website asks your browser to keep and send back with each request, which is how a site remembers that you are logged in. A session cookie holds your session data, and the server signs it so it can tell whether the data was changed.

As demonstrated in @iblue's earlier RCE in the GitHub Enterprise management console, knowing that secret lets an attacker sign arbitrary serialised data. Serialised means turned into a stream of bytes for storage or transport.

Ruby on Rails implements session storage using a cryptographically signed serialised Ruby Hash. This Hash is serialised into a cookie using Marshal.dump and subsequently deserialised using Marshal.load. If an attacker can construct a valid signature, they can create a session cookie that contains arbitrary input passed to Marshal.load. As noted by the Ruby documentation for Marshal.load, this can result in code execution:

By design, ::load can deserialise almost any class loaded into the Ruby process. In many cases this can lead to remote code execution if the Marshal data is loaded from an untrusted source.

As a result, ::load is not suitable as a general purpose serialisation format and you should never unmarshal user supplied input or other untrusted data.

In plain words: Rails stores your session as a Ruby hash, turns it into bytes with Marshal.dump, and puts it in a cookie. When the cookie comes back, Rails turns the bytes back into a hash with Marshal.load. The cookie is signed so that only the server can produce a valid one. If an attacker knows the signing secret, they can produce a valid cookie containing any bytes they like, and Marshal.load will happily rebuild whatever those bytes describe. The Ruby documentation warns that this can run code, because Marshal.load can recreate almost any class loaded in the process.

This is a clear path to RCE, though the report says a few more hurdles remain, to be discussed another time. ENTERPRISE_SESSION_SECRET is not set on GitHub.com, so there is no quick route to RCE there other than using the access keys, which the researcher explicitly advises against. In short: the vulnerability chains to RCE on GHES, but GitHub.com is not affected by that escalation.

Exploit conditions

The vulnerability affects GitHub.com and any GitHub Enterprise Server with GitHub Actions enabled. An attacker also needs to have the organisation owner role. An attacker also needs to have the organisation owner role, so this is not something any random visitor could do.

Suggested mitigations

A mitigation is a change that removes or reduces the risk. The report suggests three:

  1. Validate the rid_key parameter in the Orgs::ActionsSettings::RepositoryItemsController class against an allowlist to ensure that only intended methods of the Repository class can be invoked. An allowlist is a list of things that are permitted, with everything else refused.
  2. Revoke and regenerate all secrets used in GitHub.com / any GitHub Enterprise Server that may have been compromised. Revoking means cancelling a secret so it no longer works; regenerating means creating a new one.
  3. Consider spawning git processes with a minimal set of environment variables required for functioning instead. Currently, a total of 1220 environment variables is being passed to the git process on GitHub.com.

Detection guidance

It is possible to detect the exploitation of this vulnerability by checking the server's access logs for all requests made to /orgainzations/<organisation_name>/settings/actions/repository_items with an abnormal rid_key parameter value set. Access logs are the records a web server keeps of every request it receives. However, it is worthwhile to note that Rails accepts rid_key parameter supplied within the request body as well, so checking only the URL is not enough.

Timeline

  • 2023-12-26 Vendor Disclosure
  • 2023-12-26 Initial Vendor Contact
  • 2023-12-26 Hotfixed on Github.com Production Servers
  • 2023-12-28 Sent RCE Report to Vendor
  • 2024-01-16 Vendor Patch & Announcement Release
  • 2024-05-06 Public Release

A hotfix is an urgent fix applied directly to running servers, usually before a full release is ready.

Closing thoughts

Regrettably, this vulnerability was discovered and exploited at a really inopportune time (day after Christmas). The researcher expresses sincere apologies and gratitude to all Hubbers involved and working during the Christmas/New Year festive period, since the amount of work created for the Hubbers as a consequence of this bug report must have been insanely huge. It is, however, incredibly impressive to see them get this vulnerability patched quickly, rotate all secrets (an awfully painful process), as well as running and concluding a full investigation to confirm that this vulnerability had not been exploited in-the-wild previously.

Glossary

  • Access key: a secret string that lets a program prove its identity to another service, like a password for software.
  • Allowlist: a list of permitted values or actions; anything not on the list is refused.
  • Arity: the number of arguments a function expects. In Ruby, 0 means none needed, -1 means all are optional, and -2 means at least one is still required.
  • Argument: a value passed into a function when it is called.
  • Checkbox: an HTML input element that can be ticked or unticked, whose value is sent with the form.
  • Component: a reusable piece of a web page, often with its own setup and template.
  • Controller: the part of a Rails application that handles an incoming request and decides what to send back.
  • Cookie: a small piece of data a website asks the browser to store and send back with later requests.
  • CVE: a public identifier for a known security vulnerability, here CVE-2024-0200.
  • Default value: a fallback a programmer writes into a function definition, used when the caller does not supply that argument.
  • Docker image: a packaged bundle of software and its files, used to run an application consistently.
  • Environment variable: a named setting a program reads when it starts, often holding configuration and secrets.
  • Framework: a ready-made set of building blocks for building software, such as Ruby on Rails.
  • Getter / setter: a function that reads or writes a stored value.
  • GHES: GitHub Enterprise Server, the self-hosted edition of GitHub.
  • Git: the version-control program that stores and tracks changes to code.
  • GitHub Actions: GitHub's system for running automated tasks.
  • Global relay ID: an internal identifier GitHub uses to refer to a repository.
  • Hash: Ruby's collection of labelled values, like a form with named fields.
  • Hotfix: an urgent fix applied directly to running servers.
  • Instance variable: in Ruby, a value that belongs to a particular object, written with a leading @.
  • Keyword argument: an argument passed by name rather than by position.
  • Marshal: Ruby's built-in format for turning objects into bytes and back.
  • Metaprogramming: code that writes or generates other code, as Rails does for getters and setters.
  • Mitigation: a change that removes or reduces a risk.
  • Module: a bundle of functions that can be mixed into classes.
  • Object: in Ruby, almost everything is an object: a value with its own functions and stored data.
  • Organisation owner: the highest permission role inside a GitHub organisation.
  • Parameter: a value sent by the browser in a request, available in Rails through params.
  • Positional argument: an argument passed by its position in the list.
  • Private / protected method: Ruby labels for functions meant for internal use rather than outside callers.
  • Process: a running program on a computer.
  • RCE (remote code execution): running your own commands on someone else's server.
  • Reflection: running a function by naming it as data at runtime, rather than writing its name in the code.
  • Rails console: an interactive prompt where you can run Ruby code inside a running Rails application.
  • Revoke / regenerate: cancel a secret so it no longer works, and create a new one.
  • Ruby on Rails: a framework for building web applications in the Ruby language.
  • Secret: a long random string used to sign or protect data, kept private.
  • Serialise / deserialise: turn an object into bytes for storage or transport, and turn those bytes back into an object.
  • Session: the server's memory of who you are across multiple requests, usually kept in a cookie.
  • SIRT: Security Incident Response Team, the group that handles security incidents.
  • Source location: the file and line where a function is defined.
  • Template: a file that describes a page and is filled in with data to produce HTML.
  • Unsafe reflection: reflection where an attacker controls the function name, so they can run functions the programmer did not intend.
  • Vulnerability: a mistake in software that lets someone make it behave in a way its authors did not intend.

More by Ngo Wei Lin

View all

3 more disclosed reports, best first.

More from GitHub

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.