Debian安装配置Iptables防火墙

服务器一般会安装防火墙,Debian上有很防火墙,Iptables为比较经常使用的免费防火墙,Iptables可以提供数据包过滤,网络地址转换(NAT)等功能.在Debian上手工配置Iptables的资料比较少,本文作一个详细的介绍.

第一步,首先肯定你的系统已经安装Iptables.打开SSH终端,输入
whereis iptables
若是能看到以下相似信息,说明你已经安装了iptables
iptables: /sbin/iptables /usr/share/iptables /usr/share/man/man8/iptables.8.gz
若是不是这个提示,或者没有任何提示,那你的Debian上可能没有安装iptables
请使用以下命令安装:
sudo apt-get install iptables
注意:本文全部命令在普通账号下完成,本普通账号使用sudo具备root权限,本人不建议直接使用root用户

第二步:查看Iptables目前的配置信息
可使用以下命令查看
sudo iptables -L
若是你是第一次安装配置iptables,你可能会看到以下结果:
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,咱们先把一个基本的Iptables的规则文章保存起来,这个规则文章作为测试用
sudo vim /etc/iptables.test.rules
而后在这个文章中输入以下规则内容,这个内容是debian官方给出的基本配置
01 *filter
02   
03 # Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
04 -A INPUT -i lo -j ACCEPT
05 -A INPUT -i ! lo -d 127.0.0.0/8 -j REJECT
06   
07 # Accepts all established inbound connections
08 -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
09   
10 # Allows all outbound traffic
11 # You could modify this to only allow certain traffic
12 -A OUTPUT -j ACCEPT
13   
14 # Allows HTTP and HTTPS connections from anywhere (the normal ports for websites)
15 -A INPUT -p tcp --dport 80 -j ACCEPT
16 -A INPUT -p tcp --dport 443 -j ACCEPT
17   
18 # Allows SSH connections for script kiddies
19 # THE -dport NUMBER IS THE SAME ONE YOU SET UP IN THE SSHD_CONFIG FILE
20 -A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT
21   
22 # Now you should read up on iptables rules and consider whether ssh access
23 # for everyone is really desired. Most likely you will only allow access from certain IPs.
24   
25 # Allow ping
26 -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
27   
28 # log iptables denied calls (access via 'dmesg' command)
29 -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
30   
31 # Reject all other inbound - default deny unless explicitly allowed policy:
32 -A INPUT -j REJECT
33 -A FORWARD -j REJECT
34   
35 COMMIT

保存本文件,而后把本规则加载,使之生效,注意,iptables不须要重启,加载一次规则就成了
sudo iptables-restore < /etc/iptables.test.rules
而后再查看最新的配置,应该全部的设置都生效了.
sudo iptables -L

第四步:保存生效的配置,让系统重启的时候自动加载有效配置
iptables提供了保存当前运行的规则功能
iptables-save > /etc/iptables.up.rules

注意,若是当前用户不是root,即便使用了sudo,也会提示你没有权限,没法保存,因此执行本命令,你必须使用root用户.
可使用sudo -i快速转到root,使用完成,请及时使用su username切换到普通账户.

为了重启服务器后,规则自动加载,咱们建立以下文件:
sudo vim /etc/network/if-pre-up.d/iptables
本文章的内容以下:
#!/bin/bash
/sbin/iptables-restore < /etc/iptables.up.rules
最后,设置本文章具体可执行仅限
chmod +x /etc/network/if-pre-up.d/iptables

第五:其它
若是你想设置某ip段能够访问全部服务,你须要在iptables.test.rules文件中加入-A INPUT -m iprange --src-range 192.168.1.1-192.168.1.199 -j ACCEPT,而后从第三步再设置一次.注意iptables.test.rules不是必须的,它只是让你的修改时,能更好的测试.
相关文章
相关标签/搜索