【原创】Linux基础之iptables

iptables 1.4.21 html

 

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

 

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包过滤规则;ssh

 

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

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

Chain FORWARD (policy ACCEPT)
target prot opt source destination 工具

Chain OUTPUT (policy ACCEPT)
target prot opt source destinationurl

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

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

#容许内网和本机访问

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

相关文章
相关标签/搜索