Skip to content
Crypto Disclosed report Advanced

Gem signature forgery

The gem package manager processes duplicate entries in a gem's tar container inconsistently: signature verification uses the last entry with a given name, while file extraction uses the first. An attacker can prepend a malicious data.tar.gz to a legitimately signed gem, so the forged gem installs arbitrary files while still passing signature checks under HighSecurity.

b9629eebd06fb8f0680ecbdef829e Follow

Originally disclosed on HackerOne

Bounty$1,000 Medium 5.5 View original
  • Triaged in 4 months
  • Fixed in 8 months
  • Paid in 5 months
  • Disclosed after 10 months

Summary

Inconsistencies in how gem processes gem files make it possible to reuse a signature from an existing signed gem and apply it to arbitrary contents. The forged gem will install even with -P HighSecurity.

The attached file multi_json-1.12.2.gem is a forged version of the genuine multi_json-1.12.2.gem gem with faked contents (just a single text file called HACKED). Here is how to check it. You must first trust the original developer's public key.

$ gem --version
2.5.2
$ wget https://raw.githubusercontent.com/intridea/multi_json/master/certs/rwz.pem
$ gem cert --add rwz.pem
Added '/CN=pavel/DC=pravosud/DC=com'
$ gem install --install-dir install -P HighSecurity multi_json-1.12.2.gem
Successfully installed multi_json-1.12.2
1 gem installed
$ ls install/gems/multi_json-1.12.2/
HACKED

Details

The vulnerability stems from inconsistencies in how gem interprets the entries of the tar container. A tar file may contain multiple entries with the same name. When there are two data.tar.gz entries, for example, gem will honor the second one when verifying the signature, but the first one when installing files. The proof of concept gem uses this trick: it prepends an additional data.tar.gz entry to the genuine multi_json-1.12.2.gem. (The attached forge-gem.sh script was used to make it.)

$ tar tvf multi_json-1.12.2.gem
-r--r--r-- wheel/wheel     163 2017-10-05 16:05 data.tar.gz
-r--r--r-- wheel/wheel    1840 2017-09-04 21:51 metadata.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 metadata.gz.sig
-r--r--r-- wheel/wheel   16908 2017-09-04 21:51 data.tar.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 data.tar.gz.sig
-r--r--r-- wheel/wheel     270 2017-09-04 21:51 checksums.yaml.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 checksums.yaml.gz.sig

A similar bug affects checksums.yaml.gz: checksums are read from the first such entry, while the signature is verified on the last. This table summarizes the inconsistencies:

file extract_files uses verify uses
data.tar.gz first last
checksums.yaml.gz first last
metadata.gz last last

Source code references

Here are the pieces of code that are responsible for the inconsistencies in processing.

extract_files takes the first data.tar.gz entry:

  def extract_files destination_dir, pattern = "*"
    verify unless @spec

    FileUtils.mkdir_p destination_dir

    @gem.with_read_io do |io|
      reader = Gem::Package::TarReader.new io

      reader.each do |entry|
        next unless entry.full_name == 'data.tar.gz'

        extract_tar_gz entry, destination_dir, pattern

        return # ignore further entries
      end
    end
  end

read_checksums seeks to the first checksums.yaml.gz entry:

  def read_checksums gem
    Gem.load_yaml

    @checksums = gem.seek 'checksums.yaml.gz' do |entry|
      Zlib::GzipReader.wrap entry do |gz_io|
        YAML.load gz_io.read
      end
    end
  end

verify_files and verify_entry iterate over all entries in the tar file, filling in @signatures and @digests. In the case of entries with duplicate names, it overwrites previous values, meaning that the last result wins. verify_entry also handles metadata.gz, calling load_spec afresh each time:

  def verify_entry entry
    file_name = entry.full_name
    @files << file_name

    case file_name
    when /\.sig$/ then
      @signatures[$`] = entry.read if @security_policy
      return
    else
      digest entry
    end

    case file_name
    when /^metadata(.gz)?$/ then
      load_spec entry
    when 'data.tar.gz' then
      verify_gz entry
    end
  rescue => e
    message = "package is corrupt, exception while verifying: " +
              "#{e.message} (#{e.class})"
    raise Gem::Package::FormatError.new message, @gem
  end

verify_checksums and verify_signatures operate only on the precomputed @checksums, @signatures, and @digests.

Incidentally, get_metadata, used by the unpack command, has its own extractor for metadata.gz, but it happens to grab the last entry, just like verify_files.

Mitigation

The attached patch 0001-Add-tests-that-Gem-Package-verify-checks-duplicate-f.patch adds two new tests (both currently failing) that check signature verification when bogus files come before or after the genuine files.

The essential mitigation is to ensure that there is no ambiguity when processing a tar file that has multiple entries for the same file name. E.g., "data.tar.gz" must refer to one and only one entry in the tar file. One way to do it would be to set a policy in the code: e.g., last entry always wins (which would be consistent with the tar command). But that would be hard to enforce, especially in new code going forward. Another way would be not to permit duplicate entries; e.g., verify_entry could check whenever it is about to overwrite something in @signatures, @digests, or @spec, and return an error. This needs some care, as metadata and metadata.gz are both processed equivalently. It is possible, using symlinks, to create entries that effectively point to the same file, even though the paths differ; e.g.:

data.tar.gz
dir/ -> ..
dir/data.tar.gz

But this shouldn't be a problem for gem, as long as it continues to use strict string equality with unadorned paths like "data.tar.gz".

Even when this bug is fixed, a weaker form of signature forgery is possible. There is nothing in a gem file that binds data.tar.gz and metadata.gz together: they are signed independently. It is possible to mix and match files from different signed gems. Suppose a signed gem example-1.0 has a security vulnerability, and the authors release a new signed update example-1.1. Someone (perhaps a malicious rubygems.org admin) could forge a gem containing data.tar.gz from example-1.0 and metadata.gz from example-1.1. Users would think they are running the updated code, but they are still running the old vulnerable code. Fixing this weaker form of forgery seems like it would require a redesign of the signature format. Ideally, the signature would be over the entire gem, and verified before any unpacking.

It seems that not many people are sign their gems or verify signatures. For most users the possibility of signature forgery doesn't put them at additional risk beyond the (already risky) status quo. The flaw affects only those users who use the MediumSecurity or HighSecurity profiles.

Attachments

  • multi_json-1.12.2.gem is a gem with a forged signature.
  • 0001-Add-tests-that-Gem-Package-verify-checks-duplicate-f.patch adds tests for specific instances of gem files that contain multiple entries with the same name.
  • forge-gem.sh takes an existing signed gem and produces a forged gem containing an arbitrary data.tar.gz file.

How to run forge-gem.sh:

$ gem fetch multi_json
$ mkdir orig
$ mv multi_json-1.12.2.gem orig/
$ echo hacked > HACKED
$ tar czf data.tar.gz HACKED
$ ./forge-gem.sh orig/multi_json-1.12.2.gem data.tar.gz forged.gem

Be aware that if the original multi_json-1.12.2.gem and the new forged.gem are both in the same directory, then gem install ./forged.gem will—for some reason—install multi_json-1.12.2.gem instead. You have to hide the original file in another directory first.

The original report as published on HackerOne, by b9629eebd06fb8f0680ecbdef829e. 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. 8 min read.

Context

RubyGems is the package manager for the Ruby ecosystem, and the gem command is the client that fetches, verifies and installs .gem files. A .gem file is a tar archive that carries the package payload (data.tar.gz), the gemspec (metadata.gz), a checksum manifest (checksums.yaml.gz), and detached signatures for each of those (.sig entries). When a user installs with a security policy such as -P HighSecurity, the client is supposed to verify those signatures against trusted certificates before any files are unpacked.

The report describes a way to take a signature from an existing signed gem and apply it to arbitrary contents, producing a forged gem that installs successfully even under HighSecurity. The affected code is the RubyGems client in https://github.com/rubygems/rubygems.

Setup

The proof of concept uses RubyGems 2.5.2 and requires the original developer's public key to be trusted first. The forged file is multi_json-1.12.2.gem, a modified copy of the genuine multi_json-1.12.2.gem whose payload has been replaced with a single text file called HACKED.

The researcher also provides three attachments:

  • multi_json-1.12.2.gem, the gem with the forged signature.
  • 0001-Add-tests-that-Gem-Package-verify-checks-duplicate-f.patch, which adds tests for gem files containing multiple entries with the same name.
  • forge-gem.sh, which takes an existing signed gem and produces a forged gem containing an arbitrary data.tar.gz.

Finding it

The issue is an inconsistency in how gem interprets entries of the tar container. A tar file may contain multiple entries with the same name, and different parts of the client resolve that ambiguity differently. When two data.tar.gz entries exist, gem honours the second one when verifying the signature but the first one when installing files. The proof of concept exploits exactly this: it prepends an additional data.tar.gz entry to the genuine multi_json-1.12.2.gem.

Listing the forged archive shows the duplicate clearly:

Text
$ tar tvf multi_json-1.12.2.gem
-r--r--r-- wheel/wheel     163 2017-10-05 16:05 data.tar.gz
-r--r--r-- wheel/wheel    1840 2017-09-04 21:51 metadata.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 metadata.gz.sig
-r--r--r-- wheel/wheel   16908 2017-09-04 21:51 data.tar.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 data.tar.gz.sig
-r--r--r-- wheel/wheel     270 2017-09-04 21:51 checksums.yaml.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 checksums.yaml.gz.sig

A similar bug affects checksums.yaml.gz: checksums are read from the first such entry, while the signature is verified on the last. The inconsistencies are summarised as follows:

file extract_files uses verify uses
data.tar.gz first last
checksums.yaml.gz first last
metadata.gz last last

Exploitation

Step 1: Trust the original developer's key

The forged gem reuses the genuine signature, so the verifier must trust the key that produced it. The researcher downloads the developer's certificate and adds it to the local trust store:

Bash
$ gem --version
2.5.2
$ wget https://raw.githubusercontent.com/intridea/multi_json/master/certs/rwz.pem
$ gem cert --add rwz.pem
Added '/CN=pavel/DC=pravosud/DC=com'

Step 2: Install the forged gem under HighSecurity

The forged archive is installed into a separate directory with the strictest policy:

Bash
$ gem install --install-dir install -P HighSecurity multi_json-1.12.2.gem
Successfully installed multi_json-1.12.2
1 gem installed

The install succeeds. Under HighSecurity, the client should have rejected a package whose payload does not match its signature, but the verification path read the last data.tar.gz entry while the extraction path wrote the first one.

Step 3: Observe the installed contents

Bash
$ ls install/gems/multi_json-1.12.2/
HACKED

Instead of the multi_json library, the installed gem contains only the file HACKED.

Step 4: Forge another gem with the script

The attached forge-gem.sh automates the process against any existing signed gem:

Bash
$ gem fetch multi_json
$ mkdir orig
$ mv multi_json-1.12.2.gem orig/
$ echo hacked > HACKED
$ tar czf data.tar.gz HACKED
$ ./forge-gem.sh orig/multi_json-1.12.2.gem data.tar.gz forged.gem

One practical caveat: if the original multi_json-1.12.2.gem and the new forged.gem are in the same directory, gem install ./forged.gem will, for some reason, install multi_json-1.12.2.gem instead. The original file has to be moved to another directory first.

Root cause

The problem is that the code paths that verify a gem and the code paths that extract it resolve duplicate tar entries differently.

extract_files takes the first data.tar.gz entry and returns immediately, ignoring any further entries:

Ruby
  def extract_files destination_dir, pattern = "*"
    verify unless @spec

    FileUtils.mkdir_p destination_dir

    @gem.with_read_io do |io|
      reader = Gem::Package::TarReader.new io

      reader.each do |entry|
        next unless entry.full_name == 'data.tar.gz'

        extract_tar_gz entry, destination_dir, pattern

        return # ignore further entries
      end
    end
  end

read_checksums seeks to the first checksums.yaml.gz entry:

Ruby
  def read_checksums gem
    Gem.load_yaml

    @checksums = gem.seek 'checksums.yaml.gz' do |entry|
      Zlib::GzipReader.wrap entry do |gz_io|
        YAML.load gz_io.read
      end
    end
  end

On the verification side, verify_files and verify_entry iterate over all entries, filling in @signatures and @digests. For duplicate names, later values overwrite earlier ones, so the last result wins. verify_entry also handles metadata.gz, calling load_spec afresh each time:

Ruby
  def verify_entry entry
    file_name = entry.full_name
    @files << file_name

    case file_name
    when /\.sig$/ then
      @signatures[$`] = entry.read if @security_policy
      return
    else
      digest entry
    end

    case file_name
    when /^metadata(.gz)?$/ then
      load_spec entry
    when 'data.tar.gz' then
      verify_gz entry
    end
  rescue => e
    message = "package is corrupt, exception while verifying: " +
              "#{e.message} (#{e.class})"
    raise Gem::Package::FormatError.new message, @gem
  end

verify_checksums and verify_signatures then operate only on the precomputed @checksums, @signatures and @digests, so they validate the last entry while installation uses the first.

Incidentally, get_metadata, used by the unpack command, has its own extractor for metadata.gz, but it happens to grab the last entry, just like verify_files.

Impact

An attacker who can supply a gem file can reuse the signature of a genuine signed gem and pair it with arbitrary contents. The forged gem installs even with -P HighSecurity, so the signature check gives the user no assurance about what is actually installed.

The flaw affects only users who use the MediumSecurity or HighSecurity profiles. The report notes that not many people sign their gems or verify signatures, so for most users the possibility of signature forgery does not put them at additional risk beyond the already risky status quo.

Even when this bug is fixed, a weaker form of signature forgery remains possible. Nothing in a gem file binds data.tar.gz and metadata.gz together; they are signed independently, so files from different signed gems can be mixed and matched. If a signed gem example-1.0 has a security vulnerability and the authors release a signed update example-1.1, someone (perhaps a malicious rubygems.org admin) could forge a gem containing data.tar.gz from example-1.0 and metadata.gz from example-1.1. Users would think they are running the updated code while still running the old vulnerable code. Fixing this weaker form of forgery would likely require a redesign of the signature format, ideally signing the entire gem and verifying it before any unpacking.

Fix

The attached 0001-Add-tests-that-Gem-Package-verify-checks-duplicate-f.patch adds two new tests, both currently failing, that check signature verification when bogus files come before or after the genuine files.

The essential mitigation is to remove the ambiguity when processing a tar file with multiple entries for the same file name: data.tar.gz must refer to one and only one entry. One option is to set a policy in the code, for example that the last entry always wins, which would be consistent with the tar command, but that would be hard to enforce, especially in new code. Another option is not to permit duplicate entries at all: verify_entry could check whenever it is about to overwrite something in @signatures, @digests or @spec, and return an error. That needs care, because metadata and metadata.gz are both processed equivalently.

Symlinks can create entries that effectively point to the same file even though the paths differ:

Text
data.tar.gz
dir/ -> ..
dir/data.tar.gz

This should not be a problem for gem as long as it continues to use strict string equality with unadorned paths like "data.tar.gz".

Variants to test

  • Duplicate checksums.yaml.gz entries: place a forged checksum manifest first and the genuine one last. A positive result is an install that succeeds while the checksums actually used come from the forged entry.
  • Duplicate metadata.gz entries: the table shows both extraction and verification use the last entry, so a mismatch there is less likely, but a positive result would be a spec that differs between what is verified and what is installed.
  • Symlink-based aliases such as dir/ -> .. followed by dir/data.tar.gz: a positive result is a client that treats the aliased path as the same file as data.tar.gz.
  • Mixing data.tar.gz from an older signed gem with metadata.gz from a newer signed gem: a positive result is an install that presents the newer version while running the older code.

Hunting notes

This class of bug hides in archive and package handling code where one component verifies a container and another extracts it, especially when both walk the same tar or zip and resolve duplicate names independently. Signals during recon include clients that support signed packages, security policies such as HighSecurity, and code that stores verification results in maps keyed by file name, where later entries overwrite earlier ones.

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

What happened, in plain words

RubyGems is the system that Ruby programmers use to download and install reusable pieces of software called gems. The gem command is the tool that does the downloading and installing. A gem file is really a bundle, a bit like a zip file, that contains the actual program code, a description of the package, a list of checksums (short fingerprints used to detect changes), and digital signatures that prove who made it.

A digital signature works like a wax seal on an envelope: it lets you check that a document came from a particular person and was not altered. When you install a gem with a strict security setting such as -P HighSecurity, the gem command is supposed to check those seals before it unpacks anything.

The report shows a way to take the seal from a genuine, properly signed gem and stick it onto a completely different set of files. The result is a forged gem that still installs successfully even under the strictest setting. The problem is not that the seal is fake. The seal is real, but the gem command checks one part of the bundle and then installs a different part.

Context

RubyGems is the package manager for the Ruby ecosystem. A package manager is a program that fetches software libraries from a central place and puts them on your computer, so you do not have to collect and copy files by hand. The gem command is the client, the program on your machine that talks to the package server.

A .gem file is a tar archive. A tar archive is a way of packing many files into one file, like putting several documents into a single folder and sealing the folder. Inside a gem archive you find:

  • data.tar.gz, the package payload, meaning the actual program files.
  • metadata.gz, the gemspec, which is the description of the package (name, version, author and so on).
  • checksums.yaml.gz, a manifest of checksums, meaning a list of fingerprints for the files so changes can be detected.
  • .sig entries, detached signatures for each of those parts. A detached signature is a separate little file that acts as the seal for another file.

When a user installs with a security policy such as -P HighSecurity, the client is supposed to verify those signatures against trusted certificates before any files are unpacked. A certificate here is a public key file that identifies who is allowed to sign.

The report describes a way to take a signature from an existing signed gem and apply it to arbitrary contents, producing a forged gem that installs successfully even under HighSecurity. The affected code is the RubyGems client in https://github.com/rubygems/rubygems.

Setup

The proof of concept uses RubyGems 2.5.2 and requires the original developer's public key to be trusted first. Trusting a key means telling your gem command that signatures made with the matching private key should be accepted. The forged file is multi_json-1.12.2.gem, a modified copy of the genuine multi_json-1.12.2.gem whose payload has been replaced with a single text file called HACKED.

The researcher also provides three attachments:

  • multi_json-1.12.2.gem, the gem with the forged signature.
  • 0001-Add-tests-that-Gem-Package-verify-checks-duplicate-f.patch, which adds tests for gem files containing multiple entries with the same name.
  • forge-gem.sh, which takes an existing signed gem and produces a forged gem containing an arbitrary data.tar.gz.

Finding it

The issue is an inconsistency in how gem interprets entries of the tar container. A tar file is allowed to contain multiple entries with the same name, just as a folder could in principle hold two documents with the same label. Different parts of the client resolve that ambiguity differently. When two data.tar.gz entries exist, gem honours the second one when verifying the signature but the first one when installing files. The proof of concept exploits exactly this: it prepends an additional data.tar.gz entry to the genuine multi_json-1.12.2.gem.

Listing the forged archive shows the duplicate clearly:

Text
$ tar tvf multi_json-1.12.2.gem
-r--r--r-- wheel/wheel     163 2017-10-05 16:05 data.tar.gz
-r--r--r-- wheel/wheel    1840 2017-09-04 21:51 metadata.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 metadata.gz.sig
-r--r--r-- wheel/wheel   16908 2017-09-04 21:51 data.tar.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 data.tar.gz.sig
-r--r--r-- wheel/wheel     270 2017-09-04 21:51 checksums.yaml.gz
-r--r--r-- wheel/wheel     256 2017-09-04 21:51 checksums.yaml.gz.sig

Line by line: tar tvf asks the tar program to list (t) the contents of the archive in verbose form (v) from the file (f) named multi_json-1.12.2.gem. Each following line describes one entry: its permissions, its owner and group, its size in bytes, its date and time, and its name. The first line is a data.tar.gz of only 163 bytes. The fourth line is another data.tar.gz of 16908 bytes. The other lines are the description, the checksum manifest and their signatures.

A similar bug affects checksums.yaml.gz: checksums are read from the first such entry, while the signature is verified on the last. The inconsistencies are summarised as follows:

file extract_files uses verify uses
data.tar.gz first last
checksums.yaml.gz first last
metadata.gz last last

Read the table as two different workers reading the same bundle. extract_files is the worker that unpacks files onto disk. verify is the worker that checks the seals. For data.tar.gz and checksums.yaml.gz they pick opposite copies, which is the gap the attack uses. For metadata.gz they agree, so that part is not the weak point.

Exploitation

Step 1: Trust the original developer's key

The forged gem reuses the genuine signature, so the verifier must trust the key that produced it. The researcher downloads the developer's certificate and adds it to the local trust store:

Bash
$ gem --version
2.5.2
$ wget https://raw.githubusercontent.com/intridea/multi_json/master/certs/rwz.pem
$ gem cert --add rwz.pem
Added '/CN=pavel/DC=pravosud/DC=com'

Line by line: gem --version asks the gem command to print its own version, which confirms the client is 2.5.2. wget is a small program that downloads a file from a web address; here it fetches rwz.pem, a certificate file in PEM format (a common text format for keys and certificates). gem cert --add rwz.pem registers that public key in the local trust store, so that signatures made with the matching private key are considered valid. The output Added '/CN=pavel/DC=pravosud/DC=com' is the identity written inside the certificate, shown in the standard naming format for certificates.

This step is needed because the attack does not break the seal. It reuses a real seal, so the machine has to be willing to accept that seal in the first place.

Step 2: Install the forged gem under HighSecurity

The forged archive is installed into a separate directory with the strictest policy:

Bash
$ gem install --install-dir install -P HighSecurity multi_json-1.12.2.gem
Successfully installed multi_json-1.12.2
1 gem installed

Line by line: gem install is the command that installs a gem. --install-dir install says to put the result in a folder called install instead of the usual system location, which keeps the experiment tidy. -P HighSecurity sets the security policy to the strictest level, the one that is supposed to refuse anything whose signature does not match. multi_json-1.12.2.gem is the file being installed. The two output lines say the install succeeded and one gem was installed.

The install succeeds. Under HighSecurity, the client should have rejected a package whose payload does not match its signature, but the verification path read the last data.tar.gz entry while the extraction path wrote the first one.

Step 3: Observe the installed contents

Bash
$ ls install/gems/multi_json-1.12.2/
HACKED

Line by line: ls lists the contents of a folder. The path install/gems/multi_json-1.12.2/ is where the installed gem was placed. The single output line HACKED is the only file inside.

Instead of the multi_json library, the installed gem contains only the file HACKED.

Step 4: Forge another gem with the script

The attached forge-gem.sh automates the process against any existing signed gem:

Bash
$ gem fetch multi_json
$ mkdir orig
$ mv multi_json-1.12.2.gem orig/
$ echo hacked > HACKED
$ tar czf data.tar.gz HACKED
$ ./forge-gem.sh orig/multi_json-1.12.2.gem data.tar.gz forged.gem

Line by line: gem fetch multi_json downloads the genuine signed gem from the package server without installing it. mkdir orig creates a folder called orig. mv multi_json-1.12.2.gem orig/ moves the downloaded gem into that folder. echo hacked > HACKED writes the word hacked into a new text file called HACKED; the > symbol means send the output into that file. tar czf data.tar.gz HACKED packs that file into an archive: c means create, z means compress with gzip, f means write to the named file, so the result is data.tar.gz. Finally ./forge-gem.sh runs the attached script, giving it the genuine gem, the new payload archive and the name of the output file, forged.gem.

One practical caveat: if the original multi_json-1.12.2.gem and the new forged.gem are in the same directory, gem install ./forged.gem will, for some reason, install multi_json-1.12.2.gem instead. The original file has to be moved to another directory first.

Root cause

The problem is that the code paths that verify a gem and the code paths that extract it resolve duplicate tar entries differently. Think of two people opening the same parcel: one checks the label on the top item, the other takes the item underneath.

extract_files takes the first data.tar.gz entry and returns immediately, ignoring any further entries:

Ruby
  def extract_files destination_dir, pattern = "*"
    verify unless @spec

    FileUtils.mkdir_p destination_dir

    @gem.with_read_io do |io|
      reader = Gem::Package::TarReader.new io

      reader.each do |entry|
        next unless entry.full_name == 'data.tar.gz'

        extract_tar_gz entry, destination_dir, pattern

        return # ignore further entries
      end
    end
  end

Line by line: def extract_files destination_dir, pattern = "*" defines a method (a named block of code) that unpacks files into a destination folder, with a pattern defaulting to everything. verify unless @spec runs the verification step first, unless the package description has already been loaded. FileUtils.mkdir_p destination_dir creates the destination folder, including any missing parent folders. @gem.with_read_io do |io| opens the gem file for reading and hands the open stream to the block of code that follows. reader = Gem::Package::TarReader.new io wraps that stream in a tar reader, a helper that walks through the entries of the archive one by one. reader.each do |entry| loops over every entry. next unless entry.full_name == 'data.tar.gz' skips any entry whose name is not exactly data.tar.gz. extract_tar_gz entry, destination_dir, pattern unpacks the matching entry into the destination. return # ignore further entries stops the whole method at once, so any later entry with the same name is never looked at. That return is the heart of the bug on this side: the first match wins.

read_checksums seeks to the first checksums.yaml.gz entry:

Ruby
  def read_checksums gem
    Gem.load_yaml

    @checksums = gem.seek 'checksums.yaml.gz' do |entry|
      Zlib::GzipReader.wrap entry do |gz_io|
        YAML.load gz_io.read
      end
    end
  end

Line by line: def read_checksums gem defines a method that reads the checksum manifest out of a gem. Gem.load_yaml loads the YAML library, which is a text format for structured data. @checksums = gem.seek 'checksums.yaml.gz' do |entry| asks the gem object to find the entry with that name and hand it to the block; seek finds the first match. Zlib::GzipReader.wrap entry do |gz_io| decompresses that entry, since it is gzip-compressed. YAML.load gz_io.read reads the decompressed text and turns it into data the program can use. The result is stored in @checksums. Again, the first matching entry is the one used.

On the verification side, verify_files and verify_entry iterate over all entries, filling in @signatures and @digests. For duplicate names, later values overwrite earlier ones, so the last result wins. verify_entry also handles metadata.gz, calling load_spec afresh each time:

Ruby
  def verify_entry entry
    file_name = entry.full_name
    @files << file_name

    case file_name
    when /\.sig$/ then
      @signatures[$`] = entry.read if @security_policy
      return
    else
      digest entry
    end

    case file_name
    when /^metadata(.gz)?$/ then
      load_spec entry
    when 'data.tar.gz' then
      verify_gz entry
    end
  rescue => e
    message = "package is corrupt, exception while verifying: " +
              "#{e.message} (#{e.class})"
    raise Gem::Package::FormatError.new message, @gem
  end

Line by line: def verify_entry entry defines a method that checks one entry of the archive. file_name = entry.full_name stores the entry's name. @files << file_name appends that name to a list of files seen so far. The first case looks at the name: when /\.sig$/ then matches any name ending in .sig, meaning a signature file. @signatures[$] = entry.read if @security_policystores the signature's contents in a table, keyed by the name of the file it signs;$`` is the part of the name before the match, so data.tar.gz.sig is filed under data.tar.gz. The if @security_policy means this only happens when a security policy is active. return then stops processing this entry. else digest entry handles every other file by computing its digest, a fingerprint of its contents. The second case then looks at the name again: when /^metadata(.gz)?$/ then matches metadata or metadata.gz and calls load_spec entry to load the package description. when 'data.tar.gz' then matches the payload and calls verify_gz entry to check it. The rescue => e block catches any error, builds a message saying the package is corrupt with the error text and class, and raises a format error. The key detail is that the table @signatures is keyed by file name, so when a duplicate name appears, the later entry overwrites the earlier one. The last result wins.

verify_checksums and verify_signatures then operate only on the precomputed @checksums, @signatures and @digests, so they validate the last entry while installation uses the first.

Incidentally, get_metadata, used by the unpack command, has its own extractor for metadata.gz, but it happens to grab the last entry, just like verify_files.

Impact

An attacker who can supply a gem file can reuse the signature of a genuine signed gem and pair it with arbitrary contents. The forged gem installs even with -P HighSecurity, so the signature check gives the user no assurance about what is actually installed.

The flaw affects only users who use the MediumSecurity or HighSecurity profiles. The report notes that not many people sign their gems or verify signatures, so for most users the possibility of signature forgery does not put them at additional risk beyond the already risky status quo.

Even when this bug is fixed, a weaker form of signature forgery remains possible. Nothing in a gem file binds data.tar.gz and metadata.gz together; they are signed independently, so files from different signed gems can be mixed and matched. If a signed gem example-1.0 has a security vulnerability and the authors release a signed update example-1.1, someone (perhaps a malicious rubygems.org admin) could forge a gem containing data.tar.gz from example-1.0 and metadata.gz from example-1.1. Users would think they are running the updated code while still running the old vulnerable code. Fixing this weaker form of signature forgery would likely require a redesign of the signature format, ideally signing the entire gem and verifying it before any unpacking.

Fix

The attached 0001-Add-tests-that-Gem-Package-verify-checks-duplicate-f.patch adds two new tests, both currently failing, that check signature verification when bogus files come before or after the genuine files. A failing test is a test that describes the correct behaviour and shows the current code does not meet it yet.

The essential mitigation is to remove the ambiguity when processing a tar file with multiple entries for the same file name: data.tar.gz must refer to one and only one entry. One option is to set a policy in the code, for example that the last entry always wins, which would be consistent with the tar command, but that would be hard to enforce, especially in new code. Another option is not to permit duplicate entries at all: verify_entry could check whenever it is about to overwrite something in @signatures, @digests or @spec, and return an error. That needs care, because metadata and metadata.gz are both processed equivalently.

Symlinks can create entries that effectively point to the same file even though the paths differ. A symlink is a shortcut file that points at another location, like a signpost rather than a copy:

Text
data.tar.gz
dir/ -> ..
dir/data.tar.gz

Line by line: the first line is a normal entry called data.tar.gz. The second line is a symlink named dir that points to .., meaning the parent folder. The third line is an entry whose path goes through that symlink, so it reaches the same place as the first line even though the text of the name is different.

This should not be a problem for gem as long as it continues to use strict string equality with unadorned paths like "data.tar.gz". Strict string equality means comparing the text exactly, character for character, so dir/data.tar.gz would not be treated as the same name as data.tar.gz.

Variants to test

  • Duplicate checksums.yaml.gz entries: place a forged checksum manifest first and the genuine one last. A positive result is an install that succeeds while the checksums actually used come from the forged entry.
  • Duplicate metadata.gz entries: the table shows both extraction and verification use the last entry, so a mismatch there is less likely, but a positive result would be a spec that differs between what is verified and what is installed.
  • Symlink-based aliases such as dir/ -> .. followed by dir/data.tar.gz: a positive result is a client that treats the aliased path as the same file as data.tar.gz.
  • Mixing data.tar.gz from an older signed gem with metadata.gz from a newer signed gem: a positive result is an install that presents the newer version while running the older code.

Hunting notes

This class of bug hides in archive and package handling code where one component verifies a container and another extracts it, especially when both walk the same tar or zip and resolve duplicate names independently. Signals during recon include clients that support signed packages, security policies such as HighSecurity, and code that stores verification results in maps keyed by file name, where later entries overwrite earlier ones.

Glossary

  • RubyGems: the package manager for the Ruby programming language, which fetches, verifies and installs gems.
  • Gem: a packaged piece of Ruby software, distributed as a .gem file.
  • gem command: the client program on your computer that downloads, checks and installs gems.
  • Package manager: software that fetches libraries from a central source and installs them for you.
  • Tar archive: a single file that packs many files together, like a folder sealed into one file.
  • Gzip: a compression method that shrinks files; a .gz file is compressed this way.
  • Payload: the actual program files inside a package, as opposed to its description or signatures.
  • Gemspec / metadata: the description of a package, such as its name, version and author.
  • Checksum: a short fingerprint computed from a file's contents, used to detect changes.
  • Manifest: a list that records information about other files, here the checksums.
  • Digital signature: a cryptographic seal that proves who produced a file and that it has not been altered.
  • Detached signature: a signature kept in a separate file rather than embedded in the signed file.
  • Public key / private key: a pair of cryptographic keys; the private key makes signatures and the public key checks them.
  • Certificate: a file that binds a public key to an identity, often stored in PEM format.
  • PEM: a common text format for certificates and keys.
  • Trust store: the local list of certificates your software is willing to accept.
  • Security policy: a setting that controls how strictly signatures are checked, such as MediumSecurity or HighSecurity.
  • HighSecurity: the strictest gem policy, meant to reject packages whose signatures do not match.
  • Verification: the act of checking a signature or checksum against the expected value.
  • Extraction: the act of unpacking files from an archive onto disk.
  • Tar entry: one item inside a tar archive, with a name, size and contents.
  • Duplicate entry: two or more entries in the same archive that share the same name.
  • Symlink: a shortcut file that points to another file or folder instead of holding a copy.
  • String equality: comparing two pieces of text exactly, character for character.
  • Digest: another word for a fingerprint of a file's contents, computed by a hash function.
  • YAML: a text format for structured data, readable by humans and programs.
  • Method: a named block of code that performs a task.
  • Map / table: a data structure that stores values under keys, here file names.
  • Patch: a file describing changes to source code, often adding tests or a fix.
  • Test: a small program that checks whether code behaves as expected.
  • Recon: the early information-gathering stage of a security review.
  • Proof of concept: a working demonstration that a vulnerability is real.

More by b9629eebd06fb8f0680ecbdef829e

View all

2 more disclosed reports, best first.

More from RubyGems

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cryptographic weaknesses

The lesson behind this report.

Encryption, signatures, randomness or certificate checks that do not protect what they claim to.