There are now port-proof tools, such as Psad, Portsentry, but feel the configuration is a bit cumbersome, and the server does not want to install an additional software. So I wrote a shell script to implement this function. The basic idea is: the use of iptables recent module records in 60 Seconds to scan over 10 ports of IP, and combined with the Inotify-tools tool real-time monitoring iptables log, once the Iptables log file has written new IP records, The use of iptables to block source IP, played a role in preventing port scanning.
1, iptables rule set
New Script iptables.sh, execute this script.
Copy Code code as follows:
ipt= "/sbin/iptables"
$IPT--delete-chain
$IPT--flush
#Default Policy
$IPT-P INPUT DROP
$IPT-P FORWARD DROP
$IPT-P OUTPUT DROP
#INPUT Chain
$IPT-A input-m State--state related,established-j ACCEPT
$IPT-A input-p tcp-m TCP--dport 80-j ACCEPT
$IPT-A input-p tcp-m TCP--dport 22-j ACCEPT
$IPT-A input-i lo-j ACCEPT
$IPT-A input-p icmp-m ICMP--icmp-type 8-j ACCEPT
$IPT-A input-p icmp-m ICMP--icmp-type 11-j ACCEPT
$IPT-A input-p TCP--syn-m recent--name portscan--rcheck--seconds--hitcount LOG
$IPT-A input-p TCP--syn-m recent--name Portscan--set-j DROP
#OUTPUT Chain
$IPT-A output-m State--state related,established-j ACCEPT
$IPT-A output-p udp-m UDP--dport 53-j ACCEPT
$IPT-A output-o lo-j ACCEPT
$IPT-A output-p icmp-m ICMP--icmp-type 8-j ACCEPT
$IPT-A output-p icmp-m ICMP--icmp-type 11-j ACCEPT
#iptables Save
Service Iptables Save
Service Iptables Restart
Note: 17-18 lines of two rules must be at the bottom of the input chain, other rules themselves can be supplemented.
2, iptables log location changes
Edit/etc/syslog.conf, add:
Copy Code code as follows:
Kern.warning/var/log/iptables.log
Reboot syslog
Copy Code code as follows:
/etc/init.d/syslog restart
3. Anti-port Scan shell script
First install INotify:
Copy Code code as follows:
Yum Install Inotify-tools
Save the following code as ban-portscan.sh
Copy Code code as follows:
btime=600 #封ip的时间
While True;do
While Inotifywait-q-q-e Modify/var/log/iptables.log;do
ip= ' Tail-1/var/log/iptables.log | Awk-f "[=]" ' {print $} ' | grep ' \ ([0-9]\{1,3\}\.\) \{3\}[0-9]\{1,3\} '
If Test-z "'/sbin/iptables-nl | grep $ip ' "; then
/sbin/iptables-i input-s $ip-j DROP
{
Sleep $btime &&/sbin/iptables-d input-s $ip-j DROP
} &
Fi
Done
Done
Execute command to start Port anti-scan
Copy Code code as follows: