포고플러그 보안

분류없음 2014.01.19 22:10
참초: http://cafe.naver.com/pogolinux/31


본글은 클리앙의 Ethica 님께서 클리앙 팁과강좌 게시판에 작성하신 글입니다.

http://www.clien.net/cs2/bbs/board.php?bo_table=lecture&wr_id=149147


Ethica님 허락하에 본 카페에 스크랩 된 게시물임을 알려드리며, 많은 참고 바랍니다.

fail2ban은 특정 서비스로 로그인시 몇회 이상 실패할 경우 일정기간 동안 차단하는 툴입니다. 


---------------------------------------------------------------------------------------------------------


포 고플러그를 ftp, samba, torrent등 많이 사용하시죠? 시스템 관리자라면 보안 정책을 세워서 관리를 하시겠지만 미디어서버나 토렌트 머신으로 사용하시는 분들이 많아서 신경을 덜 쓰실겁니다. 저도 /var/log/auth.log가 많이 쌓여서 보다가 중국, 미국, 호주, 국내를 비롯하여 ssh 무작위 로그인이 보이더군요. 자, 막아봅시다. ^^

 

fail2ban은 특정 서비스로 로그인시 몇회 이상 실패할 경우 일정기간 동안 차단하는 툴입니다. 

 

참고: http://www.fail2ban.org/

        https://wiki.archlinux.org/index.php/Fail2ban

 

[root@alarm ~]# pacman -S python2-pyinotify

 

[root@alarm ~]# pacman -S fail2ban

 

[root@alarm ~]# pacman -S whois

 

[root@alarm ~]# pacman -S gamin

 

[root@alarm ~]# systemctl enable fail2ban

 
[root@alarm ~]# cat /etc/systemd/system/multi-user.target.wants/fail2ban.service
[Unit]
Description=Ban IPs that make too many password failures
After=syslog.target network.target
 
[Service]
Type=forking
ExecStart=/usr/bin/fail2ban-client start
ExecReload=/usr/bin/fail2ban-client reload
ExecStop=/usr/bin/fail2ban-client stop
PIDFile=/var/run/fail2ban/fail2ban.pid
CapabilityBoundingSet=CAP_DAC_READ_SEARCH CAP_NET_ADMIN CAP_NET_RAW
 
[Install]
WantedBy=multi-user.target
 
vi나 nano로 [Service] 섹션에 CapabilityBoundingSet=CAP_DAC_READ_SEARCH CAP_NET_ADMIN CAP_NET_RAW 추가
 
[root@alarm ~]# cat /etc/fail2ban/filter.d/fail2ban.conf
# Fail2Ban configuration file
#
# Author: Tom Hendrikx
#
# $Revision$
#
 
[Definition]
 
# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>\S+)
# Values:  TEXT
#
 
# Count all bans in the logfile
failregex = fail2ban.actions: WARNING \[(.*)\] Ban <HOST>
 
# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
 
# Ignore our own bans, to keep our counts exact.
# In your config, name your jail 'fail2ban', or change this line!
ignoreregex = fail2ban.actions: WARNING \[fail2ban\] Ban <HOST>
 
긁어서 /etc/fail2ban/filter.d/fail2ban.conf로 저장합니다.
 
[root@alarm ~]# cat /etc/fail2ban/jail.conf
# Fail2Ban jail specifications file
#
# Comments: use '#' for comment lines and ';' for inline comments
#
# Changes:  in most of the cases you should not modify this
#           file, but provide customizations in jail.local file, e.g.:
#
# [DEFAULT]
# bantime = 3600
#
# [ssh-iptables]
# enabled = true
#
 
# The DEFAULT allows a global definition of the options. They can be overridden
# in each jail afterwards.
 
[DEFAULT]
 
# "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not
# ban a host which matches an address in this list. Several addresses can be
# defined using space separator.
ignoreip = 127.0.0.1/8
ignoreip = 172.30.1.2/24
 
# "bantime" is the number of seconds that a host is banned.
# bantime : 1 day
bantime  = 86400
 
# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime  = 600
 
# "maxretry" is the number of failures before a host get banned.
maxretry = 3
 
# "backend" specifies the backend used to get files modification.
# Available options are "pyinotify", "gamin", "polling" and "auto".
# This option can be overridden in each jail as well.
#
# pyinotify: requires pyinotify (a file alteration monitor) to be installed.
#              If pyinotify is not installed, Fail2ban will use auto.
# gamin:     requires Gamin (a file alteration monitor) to be installed.
#              If Gamin is not installed, Fail2ban will use auto.
# polling:   uses a polling algorithm which does not require external libraries.
# auto:      will try to use the following backends, in order:
#              pyinotify, gamin, polling.
backend = gamin
 
# "usedns" specifies if jails should trust hostnames in logs,
#   warn when reverse DNS lookups are performed, or ignore all hostnames in logs
#
# yes:   if a hostname is encountered, a reverse DNS lookup will be performed.
# warn:  if a hostname is encountered, a reverse DNS lookup will be performed,
#        but it will be logged as a warning.
# no:    if a hostname is encountered, will not be used for banning,
#        but it will be logged as info.
usedns = warn
 
 
# This jail corresponds to the standard configuration in Fail2ban 0.6.
# The mail-whois action send a notification e-mail with a whois request
# in the body.
 
[ssh-iptables]
enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
#          sendmail-whois[name=SSH, dest=root, sender=fail2ban@example.com]
logpath  = /var/log/auth.log
maxretry = 3
 
[fail2ban]
enabled  = true
filter   = fail2ban
action   = iptables-allports[name=fail2ban]
#       sendmail-whois[name=fail2ban]
logpath  = /var/log/fail2ban.log
# findtime: 1 week
findtime = 604800
# bantime: 1 week
bantime  = 604800
 
긁어서 /etc/fail2ban/jail.conf로 저장합니다.
(저 의 설정입니다. 자신에게 맞게 수정하세요. ssh만 설정했는데 vsftpd나 운영하시는 서비스에 맞춰서 설정하시면 됩니다. ignoreip에 자신의 공유기 ip대역대를 설정하시고, 외부에서 접근시 외부 ip도 적어두시면 됩니다.)
 
-----

[DEFAULT] 섹션 : 아래의 설정사항들에 대한 기본값을 설정한다. 이 섹션에서 설정한 기본값은 각각의 필터항목에서 개별적으로도 설정이 가능하다.

 

ignoreip : 무시할 IP주소 (여기에 입력한 IP는 차단 하지 않음) CIDR Mask, DNS, IP를 입력가능

              공백을 이용하여 여러개 입력 가능

bantime : 해킹시도가 감지되었을 때 해당 IP를 차단할 차단기간 (기본값 : 600, 단위 : 초)

findtime : 로그에서 검색할 시간 (기본값 : 600, 단위 : 초)

maxretry : 일정시간동안 해킹시도 횟수

backend : 로그 파일 변경을 감지할 방법 (gamin, polling, auto)

               gamin : Gamin(file alteration monitor)설치된 경우 사용가능

               polling : 주기적으로 점검

               auto : Gamin이 설치된 경우 gamin사용, 아니면 polling 사용

 

* ignoreip에 있는 주소를 제외한 다른 곳에서 findtime 동안 maxretry 횟수 만큼 인증실패가 일어 난 경우 bantime 시간 만큼 해당 IP를 차단한다.

 
-----
 
[root@alarm ~]# mkdir /var/run/fail2ban
 
[root@alarm ~]# systemctl start fail2ban
 
[root@alarm ~]# systemctl status fail2ban
fail2ban.service - Ban IPs that make too many password failures
          Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; enabled)
          Active: active (running) since 화 2013-03-05 15:43:47 KST; 1h 7min ago
         Process: 219 ExecStart=/usr/bin/fail2ban-client start (code=exited, status=0/SUCCESS)
        Main PID: 271 (fail2ban-server)
          CGroup: name=systemd:/system/fail2ban.service
                  ├─271 /usr/bin/python2 /usr/bin/fail2ban-server -b -s /var/run/fail2ban/fail2ban.sock
                  └─273 /usr/lib/gamin/gam_server
 
 3월 05 15:43:41 alarm fail2ban-client[219]: 2013-03-05 15:43:41,038 fail2ban.server : INFO   Starting Fail2ban v0.8.8
 3월 05 15:43:41 alarm fail2ban-client[219]: 2013-03-05 15:43:41,053 fail2ban.server : INFO   Starting in daemon mode
 3월 05 15:43:47 alarm systemd[1]: Started Ban IPs that make too many password failures.
 
부팅시 iptables 실행
[root@alarm ~]# systemctl enable iptables
 
[root@alarm ~]# iptables -nvL
Chain INPUT (policy ACCEPT 658 packets, 54986 bytes)
 pkts bytes target     prot opt in     out     source               destination
  352 24636 fail2ban-fail2ban  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0
  273 20844 fail2ban-SSH  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22
  361 25896 fail2ban-fail2ban  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0
  273 20844 fail2ban-SSH  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22
 
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
 
Chain OUTPUT (policy ACCEPT 646 packets, 181K bytes)
 pkts bytes target     prot opt in     out     source               destination
 
Chain fail2ban-SSH (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      *       198.7.63.79          0.0.0.0/0
    0     0 DROP       all  --  *      *       60.23.248.21         0.0.0.0/0
    0     0 DROP       all  --  *      *       81.57.244.146        0.0.0.0/0
    0     0 DROP       all  --  *      *       61.147.109.195       0.0.0.0/0
  546 41688 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
 
Chain fail2ban-fail2ban (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      *       60.23.248.21         0.0.0.0/0
  713 50532 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
 
iptables 보시면 추가된 ip들이 보입니다.
 
재부팅시에도 적용해야 겠죠?
[root@alarm ~]# iptables-save >/etc/iptables/iptables.rules
 
[root@alarm ~]# fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
입력해보시면 로그인 실패한 ip들이 보입니다. 많아서 생략했습니다.
 
[root@alarm ~]# pacman -S geoip
 
[root@alarm ~]# cat Fail2BanGeo.py
#!/usr/bin/env python2
# Fail2BanGeo.py
import os
import re
f = open('/var/log/fail2ban.log', 'r')
pattern = r".*?Ban\s*?((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$"
p = re.compile(pattern)
for i in f:
        m = p.match(i)
        if m:
                ip = m.group(1)
                file = os.popen('geoiplookup %s' % ip)
                print file.read()
 
[root@alarm ~]# ./Fail2BanGeo.py
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: US, United States
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: KR, Korea, Republic of
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: CA, Canada
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: FR, France
 
GeoIP Country Edition: CN, China
 
GeoIP Country Edition: US, United States
 
해킹 시도하는 놈들 중국, 미국, 한국, 프랑스도 있네요. 
 
이제 신경을 덜 쓰셔도 되겠습니다. ^.^;


저작자 표시
신고

설정

트랙백

댓글