2013-08-29 :-(
_ 午後
1300 自習
_ [SSH][ruby][GeoIP][gem][攻撃][セキュリティ]SSH ブルートフォースアタック 攻撃元の国トップ10
環境
- ruby 1.9.3p429
 - cjheath/geoip
 
準備
hosts.deny
DenyHosts を導入済みであり hosts.deny にある程度 記録されていることとする。
hosts.deny はこんな感じになっている。
ALL : ALL sshd: 218.61.11.78 sshd: 118.145.25.90 sshd: 211.154.151.150 sshd: 218.108.85.240 sshd: 218.248.30.116 sshd: 114.255.40.1
gem geoip
cjheath/geoip をインストールしておく。
% gem install geoip
GeoIP データベースが必要なので REQUIREMENTS にあるとおりにダウンロードしておく。
% wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz % tar xzf GeoIP.dat.gz
コード
# -*- coding: utf-8 -*-
# cjheath/geoip https://github.com/cjheath/geoip
require 'geoip'
def build_hosts(hosts_file)
  hosts ||= []
  lines = File.open(hosts_file).readlines()
  lines.each{|line|
    if line =~ /^sshd/
      hosts << line.gsub('sshd: ', '').chomp
    end
  }
  return hosts
end
def build_geoip(geoip_dat)
  return geoip = GeoIP.new(geoip_dat)
end
def main(argv)
  hosts_file = argv[0]
  geoip_dat = argv[1]
  
  hosts = build_hosts(hosts_file)
  geoip = build_geoip(geoip_dat)
  
  countries ||= {}
  countries.default = 0
  
  hosts.each{|host|
    c3 = geoip.country(host).country_code3
    countries[c3] += 1
  }
  
  countries.sort {|a, b| (b[1] <=> a[1]) }.each{|c|
    puts "#{c[0]} #{c[1]}"
  }
end
main(ARGV)
実行
トップ 10
% ruby denyhosts.rb hosts.deny GeoIP.dat | head CHN 649 USA 142 KOR 111 IND 47 RUS 40 DEU 33 TWN 27 GBR 27 BRA 26 TUR 25
_ ,
Filtering attacks from China and Korea using FreeBSD and pf - BSD Security
これはさすがにやり過ぎかと思うけど CHN はたしかに弾いていいかもしれんなあ。
[ツッコミを入れる]




