url_blocker.rb 2.48 KB
Newer Older
1 2 3 4
require 'resolv'

module Gitlab
  class UrlBlocker
5
    BlockedUrlError = Class.new(StandardError)
6

7 8 9
    class << self
      def validate!(url, allow_localhost: false, allow_private_networks: true, valid_ports: [])
        return true if url.nil?
10 11 12 13

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

16 17 18
          raise BlockedUrlError, "Port is blocked" if blocked_port?(uri.port, valid_ports)
          raise BlockedUrlError, "User is blocked" if blocked_user_or_hostname?(uri.user)
          raise BlockedUrlError, "Hostname is blocked" if blocked_user_or_hostname?(uri.hostname)
19

20 21
          addrs_info = Addrinfo.getaddrinfo(uri.hostname, 80, nil, :STREAM)

22 23 24 25 26 27 28
          if !allow_localhost && localhost?(addrs_info)
            raise BlockedUrlError, "Requests to localhost are blocked"
          end

          if !allow_private_networks && private_network?(addrs_info)
            raise BlockedUrlError, "Requests to the private local network are blocked"
          end
29
        rescue Addressable::URI::InvalidURIError
30
          raise BlockedUrlError, "URI is invalid"
31
        rescue SocketError
32
          return
33 34
        end

35 36 37 38 39 40
        true
      end

      def blocked_url?(*args)
        validate!(*args)

41
        false
42 43
      rescue BlockedUrlError
        true
44 45 46 47
      end

      private

48 49
      def blocked_port?(port, valid_ports)
        return false if port.blank? || valid_ports.blank?
50

51
        port < 1024 && !valid_ports.include?(port)
52 53
      end

54 55 56 57 58 59
      def blocked_user_or_hostname?(value)
        return false if value.blank?

        value !~ /\A\p{Alnum}/
      end

60 61 62 63 64 65 66 67 68 69 70 71 72 73
      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

74 75 76 77 78 79 80
      def localhost?(addrs_info)
        blocked_ips = ["127.0.0.1", "::1", "0.0.0.0"]
        blocked_ips.concat(Socket.ip_address_list.map(&:ip_address))

        (blocked_ips & addrs_info.map(&:ip_address)).any?
      end

81 82 83 84
      def private_network?(addrs_info)
        addrs_info.any? { |addr| addr.ipv4_private? || addr.ipv6_sitelocal? }
      end

85 86 87 88 89 90
      def config
        Gitlab.config
      end
    end
  end
end