aboutsummaryrefslogtreecommitdiffstats
path: root/lib/bundler/rubygems_gem_installer.rb
blob: 977e13d9482974517720582dd76ccff1909cc8e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# frozen_string_literal: true
require "rubygems/installer"

module Bundler
  class RubyGemsGemInstaller < Gem::Installer
    unless respond_to?(:at)
      def self.at(*args)
        new(*args)
      end
    end

    def check_executable_overwrite(filename)
      # Bundler needs to install gems regardless of binstub overwriting
    end

    def pre_install_checks
      super && validate_bundler_checksum(options[:bundler_expected_checksum])
    end

  private

    def validate_bundler_checksum(checksum)
      return true if Bundler.settings[:disable_checksum_validation]
      return true unless checksum
      return true unless source = @package.instance_variable_get(:@gem)
      return true unless source.respond_to?(:with_read_io)
      digest = source.with_read_io do |io|
        digest = Digest::SHA256.new
        digest << io.read(16_384) until io.eof?
        io.rewind
        send(checksum_type(checksum), digest)
      end
      unless digest == checksum
        raise SecurityError, <<-MESSAGE
          Bundler cannot continue installing #{spec.name} (#{spec.version}).
          The checksum for the downloaded `#{spec.full_name}.gem` does not match \
          the checksum given by the server. This means the contents of the downloaded \
          gem is different from what was uploaded to the server, and could be a potential security issue.

          To resolve this issue:
          1. delete the downloaded gem located at: `#{spec.gem_dir}/#{spec.full_name}.gem`
          2. run `bundle install`

          If you wish to continue installing the downloaded gem, and are certain it does not pose a \
          security issue despite the mismatching checksum, do the following:
          1. run `bundle config disable_checksum_validation true` to turn off checksum verification
          2. run `bundle install`

          (More info: The expected SHA256 checksum was #{checksum.inspect}, but the \
          checksum for the downloaded gem was #{digest.inspect}.)
          MESSAGE
      end
      true
    end

    def checksum_type(checksum)
      case checksum.length
      when 64 then :hexdigest!
      when 44 then :base64digest!
      else raise InstallError, "The given checksum for #{spec.full_name} (#{checksum.inspect}) is not a valid SHA256 hexdigest nor base64digest"
      end
    end

    def hexdigest!(digest)
      digest.hexdigest!
    end

    def base64digest!(digest)
      if digest.respond_to?(:base64digest!)
        digest.base64digest!
      else
        [digest.digest!].pack("m0")
      end
    end
  end
end