iptables实例1
准备工作
准备两台安装ceonos7的机器:
web1: 192.168.200.3
web2: 192.168.200.4
proxy: 192.168.200.2
web1和web2关闭防火墙:
systemctl stop firewalld
systemctl disable firewalld
安装iptables:
yum -y install iptables-services
systemctl start iptables
systemctl enable iptables
在web1上安装httpd, samba, tftp, vsftpd,telnet-server:
yum install -y httpd samba tftp vsftpd,telnet-server
查看web1的默认iptables的filter表中链规则,默认规则是允许的:
iptables -t filter -nL
开始测试:
添加web1的INPUT和OUT规则
只允许通过eth0(ip地址:192.168.200.3)访问web1的tcp 22号端口:
iptables -A INPUT -d 192.168.200.3 -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -s 192.168.200.3 -p tcp --sport 22 -j ACCEPT
iptables -t filter -A INPUT -i eth0 -j REJECT
iptables -t filter -A OUTPUT -o eth0 -j REJECT
在proxy上ping不通web1这台主机,在web1上也ping不通proxy:
在proxy上可以ssh连接web1这台主机:
web1在filter表中OUTPUT链上放行icmp请求包,在INPUT链上放行icmp响应包
在web1上可以ping通proxy:
在proxy上ping不通web1:
一次放行多个tcp端口
用-m指定使用multiport模块,用–dports指定多个目标端口,用–sports指定多个端口:
在web1上启动httpd服务器,并且写一个index.html首页文件:
在proxy上用curl访问web1上的web服务器,放行tcp 80端口后,能够成功访问首页文件:
设置指定范围内的IP地址可以telnet连接web1
设置IP地址范围192.168.200.2-192.168.200.3的主机可以用telnet连接web1
在web1上启动telnet服务器:systemctl start telnet.socket
在proxy(192.168.200.2)和web2(192.168.200.4)上测试,在proxy可以telent登录到web1上,而在web2上无法telnet登录web1:
时间同步
在web1上使用ntpdate与proxy进行时间同步:
时间同步时服务器使用udp端口123,323,web1上需要开放这两个端口,在开放之前,web1不能与proxy进行时间同步,iptables的filter表中输入和输出链各添加一条放行规则,就能够实现web1时间同步proxy。
在指定时间内允许指定IP地址范围内主机Telnet连接web1
用-m指定使用的扩展模块:
iprange模块,–src-range用于指定IP地址范围
time模块:–timestart指定开始时间,–timestop指定结束时,示例中显示的是早上10点到下午4点;–weekdays指定星期几,示例中显示的周一到周五;–kerneltz指定使用内核配置的时区
不在指定时间范围内:proxy用telnet连接不上web1
更改允许时间后,proxy又可以用telnet连接web1
拒绝包含指定字符串的报文
-m string指定字符串模块
在web1上编写一个指定的html文件:
在web2上用curl访问这个test.html和先前的index.html文件:
这两个文件都可以被访问到。
在web1的iptables的filter表中的OUTPUT链中添加一条拒绝报文中包含world的规则:
iptables -t filter -I OUTPUT 2 -m string --algo bm --string “world” -j REJECT
添加后的iptables的filter表:
在web2上进行相同测试,index.html可以被访问,而由于test.html中含有world关键字,而不能被访问。(注意:string模块只适合明文编码的协议有效)
限制对某个服务的连接数目
限制对web1上telnet服务的数目为2
iptables -R INPUT 4 -d 192.168.200.3 -p tcp --dport 23 -m iprange --src-range 192.168.200.2-192.168.200.4 -m connlimit --connlimit-upto 2 -j ACCEPT
iptables -R OUTPUT 5 -s 192.168.200.3 -p tcp --sport 23 -m iprange --dst-range 192.168.200.2-192.168.200.4 -m connlimit --connlimit-upto 2 -j ACCEPT
更改后filter表的INPUT和OUTPUT:
测试结果:
proxy上连接一次web1:
web2上连接两次web1:
第一次可以连接,第二次就连接不上了。
限制响应ping报文的速率
在web1上的filter表中添加如下规则,限制web1每分钟只能响应20个ping报文:
iptables -I INPUT 6 -d 192.168.200.3 -p icmp --icmp-type 8 -m limit --limit-burst 5 --limit 20/minute -j ACCEPT
iptables -I OUTPUT 7 -s 192.168.200.3 -p icmp --icmp-type 0 -j ACCEPT
在proxy上测试ping web1:
第7个数据包后,大约3秒种响应一次ping请求