BigW Consortium Gitlab

url_blocker.rb 1.45 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
require 'resolv'

module Gitlab
  class UrlBlocker
    class << self
      # Used to specify what hosts and port numbers should be prohibited for project
      # imports.
      VALID_PORTS = [22, 80, 443].freeze

      def blocked_url?(url)
11 12
        return false if url.nil?

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
        blocked_ips = ["127.0.0.1", "::1", "0.0.0.0"]
        blocked_ips.concat(Socket.ip_address_list.map(&:ip_address))

        begin
          uri = Addressable::URI.parse(url)
          # Allow imports from the GitLab instance itself but only from the configured ports
          return false if internal?(uri)

          return true if blocked_port?(uri.port)

          server_ips = Resolv.getaddresses(uri.hostname)
          return true if (blocked_ips & server_ips).any?
        rescue Addressable::URI::InvalidURIError
          return true
        end

        false
      end

      private

      def blocked_port?(port)
        return false if port.blank?

        port < 1024 && !VALID_PORTS.include?(port)
      end

      def internal?(uri)
        internal_web?(uri) || internal_shell?(uri)
      end

      def internal_web?(uri)
        uri.hostname == config.gitlab.host &&
          (uri.port.blank? || uri.port == config.gitlab.port)
      end

      def internal_shell?(uri)
        uri.hostname == config.gitlab_shell.ssh_host &&
          (uri.port.blank? || uri.port == config.gitlab_shell.ssh_port)
      end

      def config
        Gitlab.config
      end
    end
  end
end