url_blocker.rb 7.56 KB
Newer Older
1 2
# frozen_string_literal: true

3
require 'resolv'
4
require 'ipaddress'
5 6 7

module Gitlab
  class UrlBlocker
8
    BlockedUrlError = Class.new(StandardError)
9

10
    class << self
11 12 13 14 15 16 17 18 19 20
      # Validates the given url according to the constraints specified by arguments.
      #
      # ports - Raises error if the given URL port does is not between given ports.
      # allow_localhost - Raises error if URL resolves to a localhost IP address and argument is true.
      # allow_local_network - Raises error if URL resolves to a link-local address and argument is true.
      # ascii_only - Raises error if URL has unicode characters and argument is true.
      # enforce_user - Raises error if URL user doesn't start with alphanumeric characters and argument is true.
      # enforce_sanitization - Raises error if URL includes any HTML/CSS/JS tags and argument is true.
      #
      # Returns an array with [<uri>, <original-hostname>].
21 22 23 24 25 26 27 28 29 30 31 32 33
      # rubocop:disable Metrics/ParameterLists
      def validate!(
        url,
        ports: [],
        schemes: [],
        allow_localhost: false,
        allow_local_network: true,
        ascii_only: false,
        enforce_user: false,
        enforce_sanitization: false,
        dns_rebind_protection: true)
        # rubocop:enable Metrics/ParameterLists

34
        return [nil, nil] if url.nil?
35

36 37
        # Param url can be a string, URI or Addressable::URI
        uri = parse_url(url)
38

39 40 41 42 43 44 45 46
        validate_uri(
          uri: uri,
          schemes: schemes,
          ports: ports,
          enforce_sanitization: enforce_sanitization,
          enforce_user: enforce_user,
          ascii_only: ascii_only
        )
47

48
        hostname = uri.hostname
49
        port = get_port(uri)
50

51 52
        address_info = get_address_info(hostname, port)
        return [uri, nil] unless address_info
53

54
        protected_uri_with_hostname = enforce_uri_hostname(address_info, uri, hostname, dns_rebind_protection)
55

56
        # Allow url from the GitLab instance itself but only for the configured hostname and ports
57
        return protected_uri_with_hostname if internal?(uri)
58

59 60 61 62 63
        validate_local_request(
          address_info: address_info,
          allow_localhost: allow_localhost,
          allow_local_network: allow_local_network
        )
64

65
        protected_uri_with_hostname
66 67 68 69 70
      end

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

71
        false
72 73
      rescue BlockedUrlError
        true
74 75 76 77
      end

      private

78 79 80 81 82 83 84 85
      # Returns the given URI with IP address as hostname and the original hostname respectively
      # in an Array.
      #
      # It checks whether the resolved IP address matches with the hostname. If not, it changes
      # the hostname to the resolved IP address.
      #
      # The original hostname is used to validate the SSL, given in that scenario
      # we'll be making the request to the IP address, instead of using the hostname.
86
      def enforce_uri_hostname(addrs_info, uri, hostname, dns_rebind_protection)
87 88 89
        address = addrs_info.first
        ip_address = address&.ip_address

90
        return [uri, nil] unless dns_rebind_protection && ip_address && ip_address != hostname
91

92 93 94
        uri = uri.dup
        uri.hostname = ip_address
        [uri, hostname]
95 96
      end

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
      def validate_uri(uri:, schemes:, ports:, enforce_sanitization:, enforce_user:, ascii_only:)
        validate_html_tags(uri) if enforce_sanitization

        return if internal?(uri)

        validate_scheme(uri.scheme, schemes)
        validate_port(get_port(uri), ports) if ports.any?
        validate_user(uri.user) if enforce_user
        validate_hostname(uri.hostname)
        validate_unicode_restriction(uri) if ascii_only
      end

      def get_address_info(hostname, port)
        Addrinfo.getaddrinfo(hostname, port, nil, :STREAM).map do |addr|
          addr.ipv6_v4mapped? ? addr.ipv6_to_ipv4 : addr
        end
      rescue SocketError
      end

      def validate_local_request(address_info:, allow_localhost:, allow_local_network:)
        return if allow_local_network && allow_localhost

        unless allow_localhost
          validate_localhost(address_info)
          validate_loopback(address_info)
        end

        unless allow_local_network
          validate_local_network(address_info)
          validate_link_local(address_info)
        end
      end

130 131 132 133
      def get_port(uri)
        uri.port || uri.default_port
      end

134
      def validate_html_tags(uri)
135 136 137 138 139 140 141
        uri_str = uri.to_s
        sanitized_uri = ActionController::Base.helpers.sanitize(uri_str, tags: [])
        if sanitized_uri != uri_str
          raise BlockedUrlError, 'HTML/CSS/JS tags are not allowed'
        end
      end

142 143 144 145 146 147 148 149 150 151 152 153
      def parse_url(url)
        raise Addressable::URI::InvalidURIError if multiline?(url)

        Addressable::URI.parse(url)
      rescue Addressable::URI::InvalidURIError, URI::InvalidURIError
        raise BlockedUrlError, 'URI is invalid'
      end

      def multiline?(url)
        CGI.unescape(url.to_s) =~ /\n|\r/
      end

154
      def validate_port(port, ports)
155 156 157
        return if port.blank?
        # Only ports under 1024 are restricted
        return if port >= 1024
158
        return if ports.include?(port)
159

160 161 162
        raise BlockedUrlError, "Only allowed ports are #{ports.join(', ')}, and any over 1024"
      end

163
      def validate_scheme(scheme, schemes)
164 165
        if scheme.blank? || (schemes.any? && !schemes.include?(scheme))
          raise BlockedUrlError, "Only allowed schemes are #{schemes.join(', ')}"
166
        end
167 168
      end

169
      def validate_user(value)
170 171
        return if value.blank?
        return if value =~ /\A\p{Alnum}/
172

173
        raise BlockedUrlError, "Username needs to start with an alphanumeric character"
174 175
      end

176
      def validate_hostname(value)
177
        return if value.blank?
178
        return if IPAddress.valid?(value)
179
        return if value =~ /\A\p{Alnum}/
180

181
        raise BlockedUrlError, "Hostname or IP address invalid"
182 183
      end

184
      def validate_unicode_restriction(uri)
185 186 187 188 189
        return if uri.to_s.ascii_only?

        raise BlockedUrlError, "URI must be ascii only #{uri.to_s.dump}"
      end

190
      def validate_localhost(addrs_info)
191
        local_ips = ["::", "0.0.0.0"]
192 193 194 195 196 197 198
        local_ips.concat(Socket.ip_address_list.map(&:ip_address))

        return if (local_ips & addrs_info.map(&:ip_address)).empty?

        raise BlockedUrlError, "Requests to localhost are not allowed"
      end

199
      def validate_loopback(addrs_info)
200 201 202 203 204
        return unless addrs_info.any? { |addr| addr.ipv4_loopback? || addr.ipv6_loopback? }

        raise BlockedUrlError, "Requests to loopback addresses are not allowed"
      end

205
      def validate_local_network(addrs_info)
206
        return unless addrs_info.any? { |addr| addr.ipv4_private? || addr.ipv6_sitelocal? || addr.ipv6_unique_local? }
207 208

        raise BlockedUrlError, "Requests to the local network are not allowed"
209 210
      end

211
      def validate_link_local(addrs_info)
212 213 214 215 216 217
        netmask = IPAddr.new('169.254.0.0/16')
        return unless addrs_info.any? { |addr| addr.ipv6_linklocal? || netmask.include?(addr.ip_address) }

        raise BlockedUrlError, "Requests to the link local network are not allowed"
      end

218 219 220 221 222
      def internal?(uri)
        internal_web?(uri) || internal_shell?(uri)
      end

      def internal_web?(uri)
223 224
        uri.scheme == config.gitlab.protocol &&
          uri.hostname == config.gitlab.host &&
225 226 227 228
          (uri.port.blank? || uri.port == config.gitlab.port)
      end

      def internal_shell?(uri)
229 230
        uri.scheme == 'ssh' &&
          uri.hostname == config.gitlab_shell.ssh_host &&
231 232 233 234 235 236 237 238 239
          (uri.port.blank? || uri.port == config.gitlab_shell.ssh_port)
      end

      def config
        Gitlab.config
      end
    end
  end
end