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不是必須的,它只是讓你的修改時,能更好的測試.
相關文章
相關標籤/搜索