Iptables

在 openvpn 連接上添加 iptables 路由

  • February 28, 2020

我的 openvpn 伺服器啟動並執行,我通過 ccd 指令將某些路由推送到我的客戶端,我想知道當客戶端連接時如何根據 ccd 文件更新 iptables。

所以可以說我的客戶 1 的 ccd 是:

ifconfig-push 10.8.0.45 255.255.255.0
push 'route 10.10.0.45'

我想把它添加到 iptables 中。

iptables -A FORWARD -s 10.8.0.45 -d 10.10.0.45 -j ACCEPT

進而

iptables -A FORWARD -s 10.8.0.0/24 -d 10.10.0.0/16 -j DROP

如果有人能指出我正確的方向將不勝感激,我對 bash 腳本相當陌生

您可以將許多腳本掛接到OpenVPN配置中,這些腳本從伺服器接收許多參數作為環境變數:cf。參考手冊

您最感興趣的是在伺服器啟動和關閉時插入規則up的腳本和每個客戶端規則的腳本。您需要修改伺服器配置以包含:down``DROP``client-connect``client-disconnect

# Allow user scripts
script-security 2
# up/down script
up /etc/openvpn/updown.sh
down /etc/openvpn/updown.sh
# Client connect/disconnect
client-connect /etc/openvpn/client.sh
client-disconnect /etc/openvpn/client.sh
  1. 您的/etc/openvpn/updown.sh腳本將創建一個OPENVPN並從FORWARD鏈中連結它:
#!/bin/bash
IPT=/usr/sbin/iptables
# 'script_type' contains the type of the script
if [ "$script_type" = "up" ]; then
 $IPT -N OPENVPN
 $IPT -A FORWARD -j OPENVPN
 $IPT -A OPENVPN -s 10.8.0.0/24 -d 10.10.0.0/16 -j DROP
else
 $IPT -F OPENVPN
 $IPT -D FORWARD -j OPENVPN
 $IPT -X OPENVPN
fi
  1. 您的客戶端腳本/etc/openvpn/client.sh會更複雜:雖然遠端客戶端的公共和私有 IP 地址包含在ifconfig_remoteandifconfig_pool_remote_ip中,但您需要解析 ccd 文件以找出您發送給客戶端的路由:
#!/bin/bash
IPT=/usr/sbin/iptables
# We need to split the line into words as bash would, by
# interpreting the double quotes, hence the 'eval'.
function parse_ccd_line() {
 eval "local line=($1)"
 # If the first word is 'push' return the second one.
 if [ "${line[0]}" = "push" ]; then
   echo "${line[1]}"
 fi
}

# Your ccd_dir so we don't need to parse the OpenVPN
# server config file too.
ccd_dir=/etc/openvpn/ccd

if [ -f "$ccd_dir/$common_name" ]; then
 # We read the "$ccd_dir/$common_name" file line by line:
 while read line; do
   # We split the argument of every 'push' directive into 'cmd' and 'arg1'
   # If you need more arguments, the array 'push_opt' contains them.
   push_opt=($(parse_ccd_line "$line"))
   cmd=${push_opt[0]}
   arg1=${push_opt[1]}
   # We use just the 'route' commands
   if [ "$cmd" = "route" ]; then
     if [ "$script_type" = "client-connect" ]; then
       $IPT -I OPENVPN -s "$ifconfig_pool_remote_ip" -d "$arg1" -j ACCEPT
     else
       $IPT -D OPENVPN -s "$ifconfig_pool_remote_ip" -d "$arg1" -j ACCEPT
     fi
   fi
 done < "$ccd_dir/$common_name"
fi

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