CVE-2023-40165 (published 2023-08-17T18:15Z)

rubygems.org is the Ruby community's primary gem (library) hosting service. Insufficient input validation allowed malicious actors to replace any uploaded gem version that had a platform, version number, or gem name matching `/-\\d/`, permanently replacing the legitimate upload in the canonical gem storage bucket, and triggering an immediate CDN purge so that the malicious gem would be served immediately. The maintainers have checked all gems matching the `/-\\d/` pattern and can confirm that no unexpected `.gem`s were found. As a result, we believe this vulnerability was _not_ exploited. The easiest way to ensure that a user's applications were not exploited by this vulnerability is to check that all of your downloaded .gems have a checksum that matches the checksum recorded in the RubyGems.org database. RubyGems contributor Maciej Mensfeld wrote a tool to automatically check that all downloaded .gem files match the checksums recorded in the RubyGems.org database. You can use it by running: `bundle add bundler-integrity` followed by `bundle exec bundler-integrity`. Neither this tool nor anything else can prove you were not exploited, but the can assist your investigation by quickly comparing RubyGems API-provided checksums with the checksums of files on your disk. The issue has been patched with improved input validation and the changes are live. No action is required on the part of the user. Users are advised to validate their local gems.

CVSS v3 base score: 7.5, HIGH (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N)

Weakness information:
cwe_id: NVD-CWE-noinfo
cwe_name: Insufficient Information
description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
extended_description: Insufficient Information

Fix information:
repo_url: https://github.com/rubygems/rubygems.org
commit_details: repo_url: https://github.com/rubygems/rubygems.org
author: Samuel Giddins
author_date: 2023-08-16 18:37:38-07:00
msg: Merge pull request from GHSA-rxcq-2m4f-94wm

* Add improved input validation of pushed gemspecs

See https://github.com/rubygems/rubygems.org/security/advisories/GHSA-rxcq-2m4f-94wm

* Remove debugging code
repository: repo_url: https://github.com/rubygems/rubygems.org
repo_name: rubygems/rubygems.org
description: The Ruby community's gem hosting service.
repo_language: Ruby
owner: rubygems
file_changes: filename: Gemfile
change_type: ModificationType.MODIFY
diff: @@ -103,4 +103,5 @@ group :test do
   gem "webmock", "~> 3.18"
   gem "simplecov", "~> 0.22", require: false
   gem "simplecov-cobertura", "~> 2.1", require: false
+  gem "aggregate_assertions", "~> 0.2.0"
 end

programming_language: Ruby
filename: Gemfile.lock
change_type: ModificationType.MODIFY
diff: @@ -71,6 +71,8 @@ GEM
       tzinfo (~> 2.0)
     addressable (2.8.4)
       public_suffix (>= 2.0.2, < 6.0)
+    aggregate_assertions (0.2.0)
+      minitest (~> 5.0)
     amazing_print (1.5.0)
     android_key_attestation (0.3.0)
     argon2 (2.1.1)
@@ -621,6 +623,7 @@ PLATFORMS
   ruby
 
 DEPENDENCIES
+  aggregate_assertions (~> 0.2.0)
   amazing_print (~> 1.4)
   autoprefixer-rails (~> 10.4)
   avo (~> 2.28, < 2.36)

programming_language: Python
filename: pusher.rb
change_type: ModificationType.MODIFY
diff: @@ -36,10 +36,17 @@ class Pusher
   end
 
   def validate
-    signature_missing = "There was a problem saving your gem: \nYou have added cert_chain in gemspec but signature was empty"
+    unless validate_signature_exists?
+      return notify("There was a problem saving your gem: \nYou have added cert_chain in gemspec but signature was empty", 403)
+    end
+
+    return notify("There was a problem saving your gem: #{rubygem.all_errors(version)}", 403) unless rubygem.valid? && version.valid?
+
+    unless version.full_name == spec.original_name && Patterns::NAME_PATTERN.match?(spec.platform.to_s)
+      return notify("There was a problem saving your gem: the uploaded spec has malformed platform attributes", 409)
+    end
 
-    return notify(signature_missing, 403) unless validate_signature_exists?
-    (rubygem.valid? && version.valid?) || notify("There was a problem saving your gem: #{rubygem.all_errors(version)}", 403)
+    true
   end
 
   def save
@@ -67,6 +74,7 @@ class Pusher
     package = Gem::Package.new(body, gem_security_policy)
     @spec = package.spec
     @files = package.files
+    validate_spec
   rescue StandardError => e
     notify <<~MSG, 422
       RubyGems.org cannot process this gem.
@@ -212,7 +220,8 @@ class Pusher
   end
 
   def write_gem(body, spec)
-    original_name = spec.original_name
+    # we validate that the version full_name == spec.original_name
+    original_name = @version.full_name
 
     gem_path = "gems/#{original_name}.gem"
     gem_contents = body.string
@@ -248,4 +257,24 @@ class Pusher
       { message: "Pushing gem", version:, rubygem: @version.rubygem.name, pusher: user.as_json }
     end
   end
+
+  def validate_spec
+    @spec.send(:invalidate_memoized_attributes)
+
+    spec = @spec.dup
+
+    cert_chain = spec.cert_chain
+
+    spec.abbreviate
+    spec.sanitize
+
+    # make sure we validate the cert chain, which gets snipped in abbreviate
+    spec.cert_chain = cert_chain
+
+    # Silence warnings from the verification
+    stream = StringIO.new
+    policy = SpecificationPolicy.new(spec)
+    policy.ui = Gem::StreamUI.new(stream, stream, stream, false)
+    policy.validate(false)
+  end
 end

programming_language: Ruby
filename: specification_policy.rb
change_type: ModificationType.ADD
diff: @@ -0,0 +1,11 @@
+class SpecificationPolicy < Gem::SpecificationPolicy
+  def error(statement)
+    return if statement.start_with?("#{Gem::SpecificationPolicy::LAZY} is not a")
+
+    super
+  end
+
+  def warning(statement)
+    # do nothing
+  end
+end

programming_language: Ruby
filename: version.rb
change_type: ModificationType.MODIFY
diff: @@ -24,7 +24,7 @@ class Version < ApplicationRecord
   validates :platform, length: { maximum: Gemcutter::MAX_FIELD_LENGTH }, format: { with: Rubygem::NAME_PATTERN }
   validates :full_name, presence: true, uniqueness: { case_sensitive: false }
   validates :rubygem, presence: true
-  validates :required_rubygems_version, :licenses, length: { maximum: Gemcutter::MAX_FIELD_LENGTH }, allow_blank: true
+  validates :required_rubygems_version, :licenses, :required_ruby_version, length: { maximum: Gemcutter::MAX_FIELD_LENGTH }, allow_blank: true
   validates :description, :summary, :authors, :requirements, :cert_chain,
     length: { minimum: 0, maximum: Gemcutter::MAX_TEXT_FIELD_LENGTH },
     allow_blank: true

programming_language: Ruby
filename: patterns.rb
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,6 @@ module Patterns
   ALLOWED_CHARACTERS    = "[A-Za-z0-9#{Regexp.escape(SPECIAL_CHARACTERS)}]+".freeze
   ROUTE_PATTERN         = /#{ALLOWED_CHARACTERS}/
   LAZY_ROUTE_PATTERN    = /#{ALLOWED_CHARACTERS}?/
-  NAME_PATTERN          = /\A#{ALLOWED_CHARACTERS}\Z/
+  NAME_PATTERN          = /\A#{ALLOWED_CHARACTERS}\z/
   URL_VALIDATION_REGEXP = %r{\Ahttps?://([^\s:@]+:[^\s:@]*@)?[A-Za-z\d-]+(\.[A-Za-z\d-]+)+\.?(:\d{1,5})?([/?]\S*)?\z}
 end

programming_language: Ruby
filename: gem_helpers.rb
change_type: ModificationType.MODIFY
diff: @@ -17,6 +17,27 @@ module GemHelpers
     build_gemspec(new_gemspec(name, version, summary, platform, &))
   end
 
+  def build_gem_raw(file_name:, spec:, contents_writer: nil)
+    package = Gem::Package.new file_name
+
+    File.open(file_name, "wb") do |file|
+      Gem::Package::TarWriter.new(file) do |gem|
+        gem.add_file "metadata.gz", 0o444 do |io|
+          package.gzip_to(io) do |gz_io|
+            gz_io.write spec
+          end
+        end
+        gem.add_file "data.tar.gz", 0o444 do |io|
+          package.gzip_to io do |gz_io|
+            Gem::Package::TarWriter.new gz_io do |data_tar|
+              contents_writer[data_tar] if contents_writer
+            end
+          end
+        end
+      end
+    end
+  end
+
   def new_gemspec(name, version, summary, platform, extra_args = {})
     ruby_version = extra_args[:ruby_version]
     rubygems_version = extra_args[:rubygems_version]

programming_language: Ruby
filename: push_test.rb
change_type: ModificationType.MODIFY
diff: @@ -68,6 +68,8 @@ class PushTest < ActionDispatch::IntegrationTest
 
     push_gem "sandworm-1.0.0.gem"
 
+    assert_response :success
+
     get rubygem_path("sandworm")
 
     assert_response :success
@@ -82,6 +84,8 @@ class PushTest < ActionDispatch::IntegrationTest
 
     push_gem "sandworm-1.0.0.gem"
 
+    assert_response :success
+
     get rubygem_path("sandworm")
 
     assert_response :success
@@ -92,6 +96,8 @@ class PushTest < ActionDispatch::IntegrationTest
   test "pushing a signed gem" do
     push_gem gem_file("valid_signature-0.0.0.gem")
 
+    assert_response :success
+
     get rubygem_path("valid_signature")
 
     assert_response :success
@@ -117,11 +123,13 @@ class PushTest < ActionDispatch::IntegrationTest
   end
 
   test "push errors don't save files" do
-    build_gem "sandworm", "1.0.0" do |spec|
-      spec.instance_variable_set :@authors, "string"
-    end
+    build_gem "sandworm", "1.0.0"
 
     assert_nil Rubygem.find_by(name: "sandworm")
+
+    # Error on empty authors now happens in a different place,
+    # but test what would happen if marshal dumping failed
+    Gem::Specification.any_instance.stubs(:_dump).raises(NoMethodError)
     push_gem "sandworm-1.0.0.gem"
 
     assert_response :internal_server_error
@@ -272,6 +280,130 @@ class PushTest < ActionDispatch::IntegrationTest
     assert_equal "2023-03-01T09:51:31+00:00".to_datetime, hook.last_failure
   end
 
+  context "with specially crafted gemspecs" do
+    should "not allow overwriting gem with -\\d in name" do
+      create(:version, number: "2.0", rubygem: create(:rubygem, name: "book-2"))
+
+      build_gem_raw(file_name: "malicious.gem", spec: <<~YAML)
+        --- !ruby/hash-with-ivars:Gem::Specification
+        ivars:
+          '@name': book
+          '@version': '2-2.0'
+          '@platform': 'not_ruby'
+          '@original_platform': 'not-ruby'
+          '@new_platform': ruby
+          '@summary': 'malicious'
+          '@authors': [test@example.com]
+      YAML
+
+      push_gem "malicious.gem"
+
+      aggregate_assertions "should fail to push" do
+        assert_response :conflict
+
+        assert_nil Rubygem.find_by(name: "book")
+        assert_nil RubygemFs.instance.get("gems/book-2-2.0.gem")
+        assert_nil RubygemFs.instance.get("quick/Marshal.4.8/book-2-2.0.gemspec.rz")
+      end
+    end
+
+    should "not allow overwriting platform gem" do
+      create(:version, number: "2.0", platform: "universal-darwin-19", rubygem: create(:rubygem, name: "book"))
+
+      build_gem_raw(file_name: "malicious.gem", spec: <<~YAML)
+        --- !ruby/hash-with-ivars:Gem::Specification
+        ivars:
+          '@name': book-2.0-universal-darwin
+          '@version': '19'
+          '@platform': 'not_ruby'
+          '@original_platform': 'not-ruby'
+          '@new_platform': ruby
+          '@summary': 'malicious'
+          '@authors': [test@example.com]
+      YAML
+
+      push_gem "malicious.gem"
+
+      aggregate_assertions "should fail to push" do
+        assert_response :conflict
+
+        assert_nil Rubygem.find_by(name: "book-2.0-universal-darwin")
+        assert_nil RubygemFs.instance.get("gems/book-2.0-universal-darwin-19.gem")
+        assert_nil RubygemFs.instance.get("quick/Marshal.4.8/book-2.0-universal-darwin-19.gemspec.rz")
+      end
+    end
+
+    context "does not allow pushing a gem where the file name does not match the version full_name" do
+      should "fail when original platform is a ruby Gem::Platform" do
+        build_gem_raw(file_name: "malicious.gem", spec: <<~YAML)
+          --- !ruby/object:Gem::Specification
+          specification_version: 100
+          name: book
+          version: '1'
+          platform: !ruby/object:Gem::Platform
+            os: ruby
+          summary: 'malicious'
+          authors: [test@example.com]
+        YAML
+        push_gem "malicious.gem"
+
+        aggregate_assertions "should fail to push" do
+          assert_response :conflict
+
+          assert_nil Rubygem.find_by(name: "book")
+          assert_nil RubygemFs.instance.get("gems/book-1-ruby.gem")
+          assert_nil RubygemFs.instance.get("quick/Marshal.4.8/book-1-ruby.gemspec.rz")
+        end
+      end
+
+      should "fail when original platform is an array that resolves to a platform of ruby" do
+        build_gem_raw(file_name: "malicious.gem", spec: <<~YAML)
+          --- !ruby/object:Gem::Specification
+          specification_version: 100
+          name: book
+          version: '1'
+          platform: [ruby]
+          summary: 'malicious'
+          authors: [test@example.com]
+        YAML
+        push_gem "malicious.gem"
+
+        assert_response :forbidden
+      end
+    end
+
+    should "fail fast when spec.name is not a string" do
+      build_gem_raw(file_name: "malicious.gem", spec: <<~YAML)
+        --- !ruby/object:Gem::Specification
+        name: !ruby/object:Gem::Version
+          version: []
+        version: '1'
+        summary: 'malicious'
+        authors: [test@example.com]
+      YAML
+      push_gem "malicious.gem"
+
+      assert_response :unprocessable_entity
+    end
+
+    should "fail when spec.platform is invalid" do
+      build_gem_raw(file_name: "malicious.gem", spec: <<~YAML)
+        --- !ruby/hash-with-ivars:Gem::Specification
+        ivars:
+          '@name': book
+          '@version': '1'
+          '@new_platform': !ruby/object:Gem::Platform
+            os: "../../../../../etc/passwd"
+          '@original_platform': ruby
+          '@summary': 'malicious'
+          '@authors': [test@example.com]
+      YAML
+      push_gem "malicious.gem"
+
+      assert_response :conflict
+    end
+  end
+
   def push_gem(path)
     post api_v1_rubygems_path,
       env: { "RAW_POST_DATA" => File.read(path) },
@@ -283,4 +415,6 @@ class PushTest < ActionDispatch::IntegrationTest
     RubygemFs.mock!
     Dir.chdir(Rails.root)
   end
+
+  make_my_diffs_pretty!
 end

programming_language: Ruby
filename: pusher_test.rb
change_type: ModificationType.MODIFY
diff: @@ -137,6 +137,8 @@ class PusherTest < ActiveSupport::TestCase
     should "not be able to save a gem if it is not valid" do
       legit_gem = create(:rubygem, name: "legit-gem")
       create(:version, rubygem: legit_gem, number: "0.0.1")
+      # this isn't the kind of invalid that we're testing with this gem
+      Gem::Specification.any_instance.stubs(:authors).returns(["user@example.com"])
       @gem = gem_file("legit-gem-0.0.1.gem.fake")
       @cutter = Pusher.new(@user, @gem)
       @cutter.stubs(:save).never

programming_language: Ruby