Centos

如何在鏈啟動時添加防火牆規則,在 CentOS 中使用 libvirt 和 iptables?

  • October 20, 2017

有了這個 /etc/sysconfig/iptables:

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j ACCEPT -s 192.168.3.0/24 -d 10.0.0.0/24
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

我的 FORWARD 鏈如下所示:

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  192.168.3.0/24       10.0.0.0/24

現在當我啟動 libvirtd FORWARD 鏈看起來像這樣:

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             10.0.0.0/24          ctstate RELATED,ESTABLISHED
ACCEPT     all  --  10.0.0.0/24          anywhere            
ACCEPT     all  --  anywhere             anywhere            
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
ACCEPT     all  --  192.168.3.0/24       10.0.0.0/24         

如您所見,我對 192.168.3.0/24 的規則是在 REJECT 之後發生的。

如何將 192.168.3.0/24 的規則放在 REJECT 前面?

我終於用了一個 libvirt 網路腳本鉤子來解決我的問題: libvirt 腳本鉤子

# cat /etc/libvirt/hooks/network 

#!/bin/bash

NAME=$1
TASK=$2
IPTABLES=/usr/sbin/iptables

if [ $NAME = "default" ] ;then
 case "$TASK" in 
 # hook is called with <network_name> started begin -
 started)
     $IPTABLES -I FORWARD -s 192.168.3.0/24 -d 10.0.0.0/24 -j ACCEPT
 ;;
 # hook is called with <network_name> stopped end -
 stopped)
     $IPTABLES -D FORWARD -s 192.168.3.0/24 -d 10.0.0.0/24 -j ACCEPT
 ;;
 *)
     echo "qemu hook called with unexpected options $*" >&2
 ;;
 esac
fi

現在我的規則首先出現。我最喜歡的方式是通過這個: libvirt nwfilter但我無法讓它工作。

-A用於追加,-I用於在規則列表的開頭插入

引用自:https://serverfault.com/questions/878926