Table of Contents
玩了5年的linux,没有给服务器加上防火墙,今天google了一下,整了个东西出来
首先看当前的配置,执行下面命令:
1 2 3 |
iptables –L |
输出信息类似于:
1 2 3 4 5 6 7 8 9 10 |
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 |
这表明任何人可以从任何地方访问。
保存iptables规则到文件
建立一个测试iptables文件
1 2 3 |
vi /etc/iptables.rules |
在这个文件写入一下简单的规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
*filter # Remove all rules -F # Allows all loopback (lo0) traffic -A INPUT -i lo -j ACCEPT # Accepts all established inbound connections -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT # Allows all outbound traffic # You could modify this to only allow certain traffic -A OUTPUT -j ACCEPT # Allows HTTP and HTTPS connections from anywhere -A INPUT -p tcp --dport 80 -j ACCEPT -A INPUT -p tcp --dport 443 -j ACCEPT # Allows SSH connections for script kiddies -A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT # Allows MYSQL (Allow Remote Access To Particular IP): -A INPUT -p tcp --dport 3306 -j ACCEPT # Allows FTP Active mode -A INPUT -p tcp --dport 20:21 -j ACCEPT # Passive FTP Ports Maybe: (Again, specifying ports 50000 through 50050 in one rule) -A INPUT -p tcp --dport 50000:50050 -j ACCEPT # Allow ping -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT # log iptables denied calls (access via 'dmesg' command) -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7 # Reject all other inbound - default deny unless explicitly allowed policy: -A INPUT -j REJECT -A FORWARD -j REJECT COMMIT |
这个看起来有点复杂,但是每次看一节,你会发现除了我们允许的端口,其他所有端口都被关闭了。
启用这些新的规则
1 2 3 |
iptables-restore < /etc/iptables.rules |
在看看不同
1 2 3 |
iptables -L |
你也可以保存这些规则到文件
确保在重启后这些iptables规则生效,建立新文件
1 2 3 |
vi /etc/network/if-pre-up.d/iptables |
增加如下内容
1 2 3 4 |
#!/bin/sh /sbin/iptables-restore < /etc/iptables.rules |
这个文件需要可执行
1 2 3 |
chmod +x /etc/network/if-pre-up.d/iptables |