IT 정보/정보보안

[정보보안/보안/보안전문가/보안학원]포트스캔 검사및 방어프로그램 : portsentry

김윤석 2007. 12. 14. 17:11
포트스캔 검사및 방어프로그램
----------------------------
portsentry는 누군가 내 새스템에 열려 있는 포트가 있는가 스캔을 검사하는 프로그램으로 해킹 방어용 툴 입니다. 누가 내 시스템을 스캔했는지 IP를 검사하고 공격시 정해진 방법으로 방어를 하며, tcpwrapper에서 IP를 원천 차단하도록 막아주는 기능, 공격자를 내 e-mail계정으로 알람 해주는 기능 등이 있습니다.

또 스캔 공격을 받았을시 외부 스크립트나 binary 프로그램을 실행하는 기능도 있습니다. 따라서 잘 이용하면 자동 역 공격도 가능 하겠습니다만, 권하고싶지는 않습니다.

rpm 버전으로 했을 경우 설치는 매우 쉽습니다. 단, .conf 파일등은 잘 살펴보아두어야 어떤 메커니즘으로 동작 하는지를 알 수 있겠습니다.

1. 설치
2. /etc/poresentry/ 의 conf 파일들
3. 테스트

( ** 레드햇 계열은(레드햇 8.0도)기본으로 sunproc 라는 rpc 용 포트가 열려 있습니다.  rpc 관련된 부분은 취약점이 많으므로 사용하지 않으면 내려 놓는게 좋습니다. portmap을 내리면 됩니다. )

1. 설치
설치는 rpm으로 했습니다. ( www.psonic.com 에서 최신 베타 2.10은 src는 어떤이유에선가 컴파일은 되는데 동작을 안하더군요. )

사용 환경 : 레드햇 리눅스 8.0 서버

1)http://www.rpmfind.net   에서 portsentry로 (search)검색을 해서 다운 로드를 받습니다.
  저는 portsentry-1.1-fr7.i386.rpm을 다운 받았습니다.

2) rpm을 풉니다.
[root@ibsis root]# rpm -Uvh portsentry-1.1-fr7.i386.rpm
경고: portsentry-1.1-fr7.i386.rpm: V3 DSA signature: NOKEY, key ID e42d547b
준비 중...                  ########################################### [100%]
   1:portsentry             ########################################### [100%]

**. 의존성 관계로 설치가 안될때는 그 의존성이 있는 rpm을 먼저 설치해 주어야 합니다.이부분이 좀 까다 롭습니다. 계속 의존성 rpm을 요구하는데 어디 속해있는지 찾기 힘들 때 ..

3) 잘 설치되었는가 확인 합니다.
[root@ibsis root]# rpm -ql portsentry
/etc/cron.d/portsentry
/etc/init.d/portsentry
/etc/portsentry
/etc/portsentry/portsentry.conf
/etc/portsentry/portsentry.ignore
/etc/portsentry/portsentry.modes
/usr/sbin/portsentry
/usr/share/doc/portsentry-1.1
/usr/share/doc/portsentry-1.1/CHANGES
/usr/share/doc/portsentry-1.1/CREDITS
/usr/share/doc/portsentry-1.1/LICENSE
/usr/share/doc/portsentry-1.1/README.COMPAT
/usr/share/doc/portsentry-1.1/README.install
/usr/share/doc/portsentry-1.1/README.methods
/usr/share/doc/portsentry-1.1/README.stealth
/var/portsentry

4) 실행을 시켜 봅니다.
[root@ibsis root]# portsentry
Psionic PortSentry - Port Scan Detector.
Copyright 1997-2000 Psionic Software, Inc. help@psionic.com>
Licensing restrictions apply. Please see documentation
Version: 1.1

usage: portsentry [-tcp -udp -stcp -atcp -sudp -audp]

*** PLEASE READ THE DOCS BEFORE USING ***

옵션을 안주고 그냥 치면 당연히(?) 아무것도 실행이 안됩니다.

4) 옵션을 주어야 실행 되는 것을 알 수 있습니다.  tcp , udp 포트만 검색하도록 해 보겠습니다. 나머지 -stcp -atcp -sudp -audp 도 각각 실행 시켜 주면 됩니다.
[root@ibsis root]# portsentry -tcp
[root@ibsis root]# portsentry -udp

# view /var/log/message  해서 실행을 확인 합니다.

2. 설정
/etc/portsentry 에 설정 파일 및 관련된 파일이 들어 갑니다.

/etc/portsentry/portsentry.conf 는 기본값으로 써도 되지만 다양한 설정이 가능 합니다. 기본값으로는 iptable을 이용해서 아래처럼 막아지게 되어 있습니다.
/sbin/iptables -I INPUT -s $TARGET$ -j DROP

.conf를 바꾸어서 이를 tcpwrapper 에 넘겨주어서 /etc/hosts.deny 에 IP를 등록하여 영구적으로 해당  IP를 차단 할수도 있습니다. 또 공격된 로그를 내 메일계정으로 e-mail을 보내게도 할수 있습니다.

/etc/portsentry/portsentry.ignore 에는 블록시키지 말아야할 기본 IP ( 내 로칼 IP, DNS,Gateway 등 ) 이 들어 갑니다.

3. 테스트
portsentry 가 설정된 서버에 다른 서버에서 nmap ( 레드햇 8.0 서버에 기본설치 됩니다.)으로 테스트를 해 봅니다.
# nmap xxx.xxx.xxx.xxx

/var/log/message 에 보면 로그가 되고 차단 메시지가 나옵니다.
/etc/portsentry.패킷.   해당 파일에 공격한  IP가 기록되는 것을 알 수 있습니다.

참고 1) 설치가 되면 portsentry는 crond 에 6시간 마다 재실행 되도록 등록 되며, 시스템서비스에도 실행하도록 등록 됩니다. # setup 이나 #natsysv 로 확인해보면 알수 있습니다.
즉 기본값에서 차단한  IP는 6시간 마다풀립니다. 따라서 영구히 막으려면 tcpwrapper 설정을 해 주어야 합니다.

참고 2) nmap 등으로 테스트하다 테스트한 서버의 IP가 막혔을 경우, 해당 블록 방법(iptables 등)을 찾아서 풀어 줘야 합니다.

/etc/portsentry/portsentry.conf 샘플 입니다.

# PortSentry Configuration
#
# $Id: portsentry.conf,v 1.23 2001/06/26 15:20:56 crowland Exp crowland $
#
# IMPORTANT NOTE: You CAN NOT put spaces between your port arguments.
#
# The default ports will catch a large number of common probes
#
# All entries must be in quotes.


#######################
# Port Configurations #
#######################
#
#
# Some example port configs for classic and basic Stealth modes
#
# I like to always keep some ports at the "low" end of the spectrum.
# This will detect a sequential port sweep really quickly and usually
# these ports are not in use (i.e. tcpmux port 1)
#
# ** X-Windows Users **: If you are running X on your box, you need to be sure
# you are not binding PortSentry to port 6000 (or port 2000 for OpenWindows users).
# Doing so will prevent the X-client from starting properly.
#
# These port bindings are *ignored* for Advanced Stealth Scan Detection Mode.
#
# 어떤 포트를 막을 것인가 선택 하는 부분입니다. 이 포트들은 막힙니다.
# Un-comment these if you are really anal: 여기로 하면 아파치 기본80 포트도 막힙니다.
#TCP_PORTS="1,7,9,11,15,70,79,80,109,110,111,119,138,139,143,512,513,514,515,540,635,1080,1524,2000,2001,4000,4001,5742,6000,6001,6667,12345,12346,20034,27665,30303,32771,32772,32773,32774,31337,40421,40425,49724,54320"
#UDP_PORTS="1,7,9,66,67,68,69,111,137,138,161,162,474,513,517,518,635,640,641,666,700,2049,31335,27444,34555,32770,32771,32772,32773,32774,31337,54321"
#
# 기본값은 여기 입니다.
# Use these if you just want to be aware:
TCP_PORTS="1,11,15,79,111,119,143,540,635,1080,1524,2000,5742,6667,12345,12346,20034,27665,31337,32771,32772,32773,32774,40421,49724,54320"
UDP_PORTS="1,7,9,69,161,162,513,635,640,641,700,37444,34555,31335,32770,32771,32772,32773,32774,31337,54321"
#
# Use these for just bare-bones
#TCP_PORTS="1,11,15,110,111,143,540,635,1080,1524,2000,12345,12346,20034,32771,32772,32773,32774,49724,54320"
#UDP_PORTS="1,7,9,69,161,162,513,640,700,32770,32771,32772,32773,32774,31337,54321"

###########################################
# Advanced Stealth Scan Detection Options #
###########################################
#
# This is the number of ports you want PortSentry to monitor in Advanced mode.
# Any port *below* this number will be monitored. Right now it watches
# everything below 1024.
#
# On many Linux systems you cannot bind above port 61000. This is because
# these ports are used as part of IP masquerading. I don't recommend you
# bind over this number of ports. Realistically: I DON'T RECOMMEND YOU MONITOR
# OVER 1024 PORTS AS YOUR FALSE ALARM RATE WILL ALMOST CERTAINLY RISE. You've been
# warned! Don't write me if you have have a problem because I'll only tell
# you to RTFM and don't run above the first 1024 ports.
#
#
ADVANCED_PORTS_TCP="1024"
ADVANCED_PORTS_UDP="1024"
#
# This field tells PortSentry what ports (besides listening daemons) to
# ignore. This is helpful for services like ident that services such
# as FTP, SMTP, and wrappers look for but you may not run (and probably
# *shouldn't* IMHO).
#
# By specifying ports here PortSentry will simply not respond to
# incoming requests, in effect PortSentry treats them as if they are
# actual bound daemons. The default ports are ones reported as
# problematic false alarms and should probably be left alone for
# all but the most isolated systems/networks.
#
# Default TCP ident and NetBIOS service
ADVANCED_EXCLUDE_TCP="21,22,25,53,80,110,113,137,138,139,443"
# Default UDP route (RIP), NetBIOS, bootp broadcasts.
ADVANCED_EXCLUDE_UDP="520,517,518,513,138,137,123,67,53"


######################
# Configuration Files#
######################
# 블록을 하지 않을 ignore 파일과 블록된 history 파일, 각 패킷별로 블록된 파일을 지정하는 부분 입니다.
# Hosts to ignore
IGNORE_FILE="/etc/portsentry/portsentry.ignore"
# Hosts that have been denied (running history)
HISTORY_FILE="/etc/portsentry/portsentry.history"
# Hosts that have been denied this session only (temporary until next restart)
BLOCKED_FILE="/etc/portsentry/portsentry.blocked"

##############################
# Misc. Configuration Options#
##############################
# 1이면 DNS lookup을 해서 공격한 호스트 네임을 가져오게 합니다.
# DNS Name resolution - Setting this to "1" will turn on DNS lookups
# for attacking hosts. Setting it to "0" (or any other value) will shut
# it off.
RESOLVE_HOST = "1"

###################
# Response Options#
###################
# Options to dispose of attacker. Each is an action that will
# be run if an attack is detected. If you don't want a particular
# option then comment it out and it will be skipped.
#
# The variable $TARGET$ will be substituted with the target attacking
# host when an attack is detected. The variable $PORT$ will be substituted
# with the port that was scanned.
#
##################
# Ignore Options #
##################
# These options allow you to enable automatic response
# options for UDP/TCP. This is useful if you just want
# warnings for connections, but don't want to react for
# a particular protocol (i.e. you want to block TCP, but
# not UDP). To prevent a possible Denial of service attack
# against UDP and stealth scan detection for TCP, you may
# want to disable blocking, but leave the warning enabled.
# I personally would wait for this to become a problem before
# doing though as most attackers really aren't doing this.
# The third option allows you to run just the external command
# in case of a scan to have a pager script or such execute
# but not drop the route. This may be useful for some admins
# who want to block TCP, but only want pager/e-mail warnings
# on UDP, etc.
#
#
# 0 = Do not block UDP/TCP scans.
# 1 = Block UDP/TCP scans.
# 2 = Run external command only (KILL_RUN_CMD)

BLOCK_UDP="1"
BLOCK_TCP="1"

###################
# Dropping Routes:#
###################
# This command is used to drop the route or add the host into
# a local filter table.
#
# The gateway (333.444.555.666) should ideally be a dead host on
# the *local* subnet. On some hosts you can also point this at
# localhost (127.0.0.1) and get the same effect. NOTE THAT
# 333.444.555.66 WILL *NOT* WORK. YOU NEED TO CHANGE IT!!
#
# ALL KILL ROUTE OPTIONS ARE COMMENTED OUT INITIALLY. Make sure you
# uncomment the correct line for your OS. If you OS is not listed
# here and you have a route drop command that works then please
# mail it to me so I can include it. ONLY ONE KILL_ROUTE OPTION
# CAN BE USED AT A TIME SO DON'T UNCOMMENT MULTIPLE LINES.
#
# NOTE: The route commands are the least optimal way of blocking
# and do not provide complete protection against UDP attacks and
# will still generate alarms for both UDP and stealth scans. I
# always recommend you use a packet filter because they are made
# for this purpose.
# 어떤 방법으로 공격  IP를 차단할 것인가를 세팅 하는 부분 입니다.

# Generic
#KILL_ROUTE="/sbin/route add $TARGET$ 333.444.555.666"

# Generic Linux
#KILL_ROUTE="/sbin/route add -host $TARGET$ gw 333.444.555.666"

# Newer versions of Linux support the reject flag now. This
# is cleaner than the above option.
#KILL_ROUTE="/sbin/route add -host $TARGET$ reject"

# Generic BSD (BSDI, OpenBSD, NetBSD, FreeBSD)
#KILL_ROUTE="/sbin/route add $TARGET$ 333.444.555.666"

# Generic Sun
#KILL_ROUTE="/usr/sbin/route add $TARGET$ 333.444.555.666 1"

# NEXTSTEP
#KILL_ROUTE="/usr/etc/route add $TARGET$ 127.0.0.1 1"

# FreeBSD
#KILL_ROUTE="route add -net $TARGET$ -netmask 255.255.255.255 127.0.0.1 -blackhole"

# Digital UNIX 4.0D (OSF/1 / Compaq Tru64 UNIX)
#KILL_ROUTE="/sbin/route add -host -blackhole $TARGET$ 127.0.0.1"

# Generic HP-UX
#KILL_ROUTE="/usr/sbin/route add net $TARGET$ netmask 255.255.255.0 127.0.0.1"

##
# Using a packet filter is the PREFERRED. The below lines
# work well on many OS's. Remember, you can only uncomment *one*
# KILL_ROUTE option.
##

# ipfwadm support for Linux
#KILL_ROUTE="/sbin/ipfwadm -I -i deny -S $TARGET$ -o"
#
# ipfwadm support for Linux (no logging of denied packets)
#KILL_ROUTE="/sbin/ipfwadm -I -i deny -S $TARGET$"
#
# ipchain support for Linux
#KILL_ROUTE="/sbin/ipchains -I input -s $TARGET$ -j DENY -l"
#
# ipchain support for Linux (no logging of denied packets)
#KILL_ROUTE="/sbin/ipchains -I input -s $TARGET$ -j DENY"
#
# iptables support for Linux
# iptables를 이용해서 차단 하도록 되어 있습니다.
KILL_ROUTE="/sbin/iptables -I INPUT -s $TARGET$ -j DROP"

# For those of you running FreeBSD (and compatible) you can
# use their built in firewalling as well.
#
#KILL_ROUTE="/sbin/ipfw add 1 deny all from $TARGET$:255.255.255.255 to any"
#
#
# For those running ipfilt (OpenBSD, etc.)
# NOTE THAT YOU NEED TO CHANGE external_interface TO A VALID INTERFACE!!
#
#KILL_ROUTE="/bin/echo 'block in log on external_interface from $TARGET$/32 to any' | /sbin/ipf -f -"


###############
# TCP Wrappers#
###############
# This text will be dropped into the hosts.deny file for wrappers
# to use. There are two formats for TCP wrappers:
#
# Format One: Old Style - The default when extended host processing
# options are not enabled.
#
#KILL_HOSTS_DENY="ALL: $TARGET$"

# Format Two: New Style - The format used when extended option
# processing is enabled. You can drop in extended processing
# options, but be sure you escape all '%' symbols with a backslash
# to prevent problems writing out (i.e. \%c \%h )
# 아래 콤멘트(#)을 지워서 hosts.deny 에 IP를 추가 해서 공격 IP는영구 추방 하도록 했습니다.
KILL_HOSTS_DENY="ALL: $TARGET$ : DENY"

###################
# External Command#
###################
# This is a command that is run when a host connects, it can be whatever
# you want it to be (pager, etc.). This command is executed before the
# route is dropped or after depending on the KILL_RUN_CMD_FIRST option below
#
#
# I NEVER RECOMMEND YOU PUT IN RETALIATORY ACTIONS AGAINST THE HOST SCANNING
# YOU!
#
# TCP/IP is an *unauthenticated protocol* and people can make scans appear out
# of thin air. The only time it is reasonably safe (and I *never* think it is
# reasonable) to run reverse probe scripts is when using the "classic" -tcp mode.
# This mode requires a full connect and is very hard to spoof.
#
# The KILL_RUN_CMD_FIRST value should be set to "1" to force the command
# to run *before* the blocking occurs and should be set to "0" to make the
# command run *after* the blocking has occurred.
# 특정 e-mail 계정으로 공격 IP를 보내도록 세텡하는 부분입니다.
KILL_RUN_CMD_FIRST = "0"
#
#
#KILL_RUN_CMD="/some/path/here/script $TARGET$ $PORT$"
# 2002.11.28 ibjeong setting email
KILL_RUN_CMD="/bin/mail -s 'Portscan from $TARGET$ on port $PORT$' 내e-mail계정@orgio.net < /dev/null"


#####################
# Scan trigger value#
#####################
# Enter in the number of port connects you will allow before an
# alarm is given. The default is 0 which will react immediately.
# A value of 1 or 2 will reduce false alarms. Anything higher is
# probably not necessary. This value must always be specified, but
# generally can be left at 0.
#
# NOTE: If you are using the advanced detection option you need to
# be careful that you don't make a hair trigger situation. Because
# Advanced mode will react for *any* host connecting to a non-used
# below your specified range, you have the opportunity to really
# break things. (i.e someone innocently tries to connect to you via
# SSL [TCP port 443] and you immediately block them). Some of you
# may even want this though. Just be careful.
#
SCAN_TRIGGER="2"

######################
# Port Banner Section#
######################
#
# Enter text in here you want displayed to a person tripping the PortSentry.
# I *don't* recommend taunting the person as this will aggravate them.
# Leave this commented out to disable the feature
#
# Stealth scan detection modes don't use this feature
#
PORT_BANNER="** UNAUTHORIZED ACCESS PROHIBITED *** YOUR CONNECTION ATTEMPT HAS BEEN LOGGED. GO AWAY."

# EOF

보안추천학원:
http://www.it-bank.or.kr/boan/boan.htm