class WebShield::IPShield

Constants

OPTION_KEYS

Public Class Methods

new(id, shield_path, options, config) click to toggle source

Params:

path:
options:
  whitelist: options, defualt [], like 172.10.10.10 172.10.10.10/16
  blacklist: options, default [], like 172.10.10.10 172.10.10.10/16
Calls superclass method
# File lib/web_shield/ip_shield.rb, line 13
def initialize(id, shield_path, options, config)
  super

  check_options(@options)
  @options[:dictatorial] = true
  push_to_whitelist(options[:whitelist]) if options[:whitelist]
  push_to_blacklist(options[:blacklist]) if options[:blacklist]
end

Public Instance Methods

filter(request) click to toggle source
# File lib/web_shield/ip_shield.rb, line 22
def filter(request)
  req_path = request.path
  return unless path_matcher.match(req_path)

  if in_blacklist?(request.ip)
    user = config.user_parser.call(request)
    write_log(:info, "Blacklist block '#{user}' #{request.request_method} #{req_path}")
    :block
  elsif in_whitelist?(request.ip)
    write_log(:info, "Whitelist pass '#{user}' #{request.request_method} #{req_path}")
    :pass
  else
    nil
  end
end
in_blacklist?(ip) click to toggle source
# File lib/web_shield/ip_shield.rb, line 42
def in_blacklist?(ip)
  in_ip_list?(get_store_key('blacklist'), ip)
end
in_whitelist?(ip) click to toggle source
# File lib/web_shield/ip_shield.rb, line 38
def in_whitelist?(ip)
  in_ip_list?(get_store_key('whitelist'), ip)
end
push_to_blacklist(ips) click to toggle source
# File lib/web_shield/ip_shield.rb, line 50
def push_to_blacklist(ips)
  config.store.push_to_set(get_store_key('blacklist'), ips)
end
push_to_whitelist(ips) click to toggle source
# File lib/web_shield/ip_shield.rb, line 46
def push_to_whitelist(ips)
  config.store.push_to_set(get_store_key('whitelist'), ips)
end

Private Instance Methods

check_options(options) click to toggle source
# File lib/web_shield/ip_shield.rb, line 66
def check_options(options)
  options.each do |key, val|
    raise Error, "Invalid shield option '#{key}'" unless OPTION_KEYS.include?(key)
  end
end
get_store_key(list_name) click to toggle source
# File lib/web_shield/ip_shield.rb, line 62
def get_store_key(list_name)
  ['web_shield', 'ip_shield', list_name].join('/')
end
in_ip_list?(list_key, ip) click to toggle source

TODO optimize it

# File lib/web_shield/ip_shield.rb, line 58
def in_ip_list?(list_key, ip)
  config.store.read_set(list_key).any? {|ip_range| IPAddr.new(ip_range).include?(ip) }
end