防火墙

阅读更多
2006-06-12

http://forum.iteye.com/viewtopic.php?t=20177&postdays=0&postorder=asc&start=15

防火墙

不是什么防火墙,其实就是用Java写了一个脚本,定期扫描netstat状态,检测80端口的连接IP数量和状态,当超过一个阀值,就调用iptables ban掉它,30分钟之后才解除封锁。其实这种脚本用perl/python/ruby去写可能更好,但是我比较熟悉Java,就用Java写了一个,主要是为了解决对网站的恶意访问的,例如使用webzip之类工具抓网站,非IP伪装类的DOS攻击,都有比较好的效果。当然有时候也会误杀一些IP(例如公司里面很多人访问javaeye,都喜欢一下点开很多页面导致超过阀值)。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

/**
 * @author Robbin Fan
 * 
 */
public class IPBanner {

	public static final String NETSTAT = "netstat -nt";

	public static final String IP_INSERT = "iptables -I INPUT -i eth0 -j DROP -p tcp --dport 80 -s ";

	public static final String IP_DEL = "iptables -D INPUT -i eth0 -j DROP -p tcp --dport 80 -s ";

	public static final String HOST_IP = "61.129.70.239:80";

	public static final long BAN_TIMEOUT = 30 * 60 * 1000L;

	public static final long BAN_INTERVAL = 30 * 1000L;

	public static final int CONCURRENT = 80;

	public static final int SYN_CONCURRENT = 8;

	public static final Map banMap = new HashMap();

	
	public static void ban() throws Exception {

		Set banList = dynamicBanIP();
		System.out.println();
		System.out.println("Time: " + new Date());
		Runtime runtime = Runtime.getRuntime();

		List expiredIPList = new ArrayList();
		
		for (Iterator iter = banMap.entrySet().iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			if ((System.currentTimeMillis() - ((Long) entry.getValue()).longValue()) > BAN_TIMEOUT) {
				expiredIPList.add(entry.getKey());
			}
		}
		
		for (int i = 0; i  CONCURRENT)
				banList.add(ipList.get(i));
			if (((Integer) synCountList.get(i)).intValue() > SYN_CONCURRENT)
				banList.add(ipList.get(i));
			if (((Integer) finCountList.get(i)).intValue() > SYN_CONCURRENT)
				banList.add(ipList.get(i));
		}
		return banList;
	}

	public static void main(String[] args) throws Exception {
		while (true) {
			ban();
			Thread.sleep(BAN_INTERVAL);
		}
	}
}



控制服务的脚本ban.sh

#!/bin/sh

cd /root/bin

case "$1" in 

  start)         
		nohup /usr/local/jdk1.5.0_05/bin/java -client IPBanner > ban.log 2>&1 &
		echo $! > ban.pid
        ;;

  stop) 
        kill `cat ban.pid`
        rm -rf ban.pid
        ;;

  restart) 
  		$0 stop
  		sleep 1 
  		$0 start 
  		;;
  
  *) 
  		echo "Usage: ban.sh {start|stop|restart}" 
  		;; 
  
esac 

exit 0 

你可能感兴趣的:(防火墙,Java,脚本,Python,Ruby)