2018-10-11 16:12:21 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
module Gitlab
|
|
|
|
module Auth
|
|
|
|
class IpRateLimiter
|
2019-06-27 18:44:46 -04:00
|
|
|
include ::Gitlab::Utils::StrongMemoize
|
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
attr_reader :ip
|
|
|
|
|
|
|
|
def initialize(ip)
|
|
|
|
@ip = ip
|
|
|
|
end
|
2017-08-15 13:44:37 -04:00
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
def reset!
|
2019-12-03 16:06:23 -05:00
|
|
|
return if skip_rate_limit?
|
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
Rack::Attack::Allow2Ban.reset(ip, config)
|
|
|
|
end
|
2017-08-15 13:44:37 -04:00
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
def register_fail!
|
2019-12-03 16:06:23 -05:00
|
|
|
return false if skip_rate_limit?
|
2019-11-07 22:06:48 -05:00
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
# Allow2Ban.filter will return false if this IP has not failed too often yet
|
2019-12-03 16:06:23 -05:00
|
|
|
Rack::Attack::Allow2Ban.filter(ip, config) do
|
2019-11-07 22:06:48 -05:00
|
|
|
# We return true to increment the count for this IP
|
|
|
|
true
|
2016-06-03 11:07:40 -04:00
|
|
|
end
|
|
|
|
end
|
2017-08-15 13:44:37 -04:00
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
def banned?
|
2019-12-03 16:06:23 -05:00
|
|
|
return false if skip_rate_limit?
|
2017-08-15 13:44:37 -04:00
|
|
|
|
2019-12-03 16:06:23 -05:00
|
|
|
Rack::Attack::Allow2Ban.banned?(ip)
|
2019-11-07 22:06:48 -05:00
|
|
|
end
|
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
private
|
2017-08-15 13:44:37 -04:00
|
|
|
|
2019-12-03 16:06:23 -05:00
|
|
|
def skip_rate_limit?
|
|
|
|
!enabled? || trusted_ip?
|
|
|
|
end
|
|
|
|
|
|
|
|
def enabled?
|
|
|
|
config.enabled
|
|
|
|
end
|
|
|
|
|
2016-06-03 11:07:40 -04:00
|
|
|
def config
|
|
|
|
Gitlab.config.rack_attack.git_basic_auth
|
|
|
|
end
|
2017-08-15 13:44:37 -04:00
|
|
|
|
2019-12-03 16:06:23 -05:00
|
|
|
def trusted_ip?
|
|
|
|
trusted_ips.any? { |netmask| netmask.include?(ip) }
|
|
|
|
end
|
|
|
|
|
2019-06-27 18:44:46 -04:00
|
|
|
def trusted_ips
|
|
|
|
strong_memoize(:trusted_ips) do
|
|
|
|
config.ip_whitelist.map do |proxy|
|
|
|
|
IPAddr.new(proxy)
|
|
|
|
rescue IPAddr::InvalidAddressError
|
|
|
|
end.compact
|
|
|
|
end
|
2016-06-03 11:07:40 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|