【原创】Linux基础之iptables

iptables 1.4.21

【原创】Linux基础之iptables

官方:https://www.netfilter.org/projects/iptables/index.html

iptables is the userspace command line program used to configure the Linux 2.4.x and later packet filtering ruleset. It is targeted towards system administrators.

iptables是一个命令行工具,与netfilter一起组成linux服务器的防火墙,通过iptables可以设置管理各种ip包过滤规则;

查看当前配置,以下为初始配置:

# iptables -nL
Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

policy有两种,一种是ACCEPT(默认放开,需要加黑名单,初始配置为全部放开),一种是DROP(默认拒绝,需要加白名单),常用的是后一种

服务器常见的策略是放开内网访问,限制外网访问:

#允许内网和本机访问

iptables -A INPUT -p tcp -s 192.168.0.0/24 -j ACCEPT
iptables -A INPUT -p tcp -s 127.0.0.1 -j ACCEPT

#允许ssh登录

iptables -A INPUT -p tcp --dport 22 -j ACCEPT

#允许访问dns、curl外网等

iptables -A INPUT -p udp --sport 53 -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

#允许访问80端口

iptables -A INPUT -p tcp --dport 80 -j ACCEPT

#允许ping

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

#允许keepalived

iptables -I INPUT -d 224.0.0.0/8 -j ACCEPT
iptables -A INPUT -p vrrp -j ACCEPT

iptables -P INPUT DROP

注意在执行最后一句之前,一定要先执行各种ACCEPT,否则执行之后服务器直接远程直接登录不了;

策略生效之后是这样的:

# iptables -nL
Chain INPUT (policy DROP)
target prot opt source destination
ACCEPT tcp -- 192.168.0.0/24 0.0.0.0/0
ACCEPT tcp -- 127.0.0.1 0.0.0.0/0
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22

ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp spt:53
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

如果想删除某条规则,增加--line-number

# iptables -nL --line-number
Chain INPUT (policy DROP)
num target prot opt source destination
1 ACCEPT tcp -- 192.168.0.0/24 0.0.0.0/0
2 ACCEPT tcp -- 127.0.0.1 0.0.0.0/0
3 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
4 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
5 ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp spt:53
6 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED

Chain FORWARD (policy ACCEPT)
num target prot opt source destination

Chain OUTPUT (policy ACCEPT)
num target prot opt source destination

然后指定行号删除

# iptables -D INPUT $line

上一篇:对某菠菜网站的一次渗透测试 heatlevel


下一篇:基于VRML的虚拟校园漫游系统