Jump to content
ChaoticSerg

OpenVPN (доработанный скрипт)

12 posts in this topic

Добрый день.

Хочу предложить всем скрипт, который я доработал. Изначально ссылкой поделился zyxmonа на том форуме еще кто-то, а он взял еще у кого-то.

По этому сразу прошу прощения, за то, что не уловил всю длинную цепочку авторов, но, если надо, то меня поправят в этом вопросе.

Не ругайте сильно, если где-то опечатался, все желательно проверить, мне пока негде. Готов к замечаниям, я старался, надеюсь кому поможет.

Скрипту требуется bash и wget . (opkg install bash wget openssl-util openvpn-openssl)

Что было сделано:

Добавлена генерация ta.key.

Содержимое этого файла включено в конфигурацию сервера и клиента.

Все файлы с ключами, используемые сервером, включены внутрь конфига сервера. (ранее было отдельными файлами со ссылками в конфиге).

Выключена компрессия lzo

перенесены логи в другой каталог status /opt/var/log/openvpn-status.log и log-append  /opt/var/log/openvpn.log

сам файл:

#!/opt/bin/bash
#OpenVPN road warrior installer for Entware-NG running on NDMS v.2. Please see http://keenopt.ru and http://forums.zyxmon.org
#This script will let you setup your own VPN server in a few minutes, even if you haven't used OpenVPN before

if [[ ! -e /dev/net/tun ]]; then
    echo "TUN/TAP is not available"
    exit 1
fi

newclient () {
    # Generates the custom client.ovpn
    cp /opt/etc/openvpn/client-common.txt ~/$1.ovpn
    echo "<ca>" >> ~/$1.ovpn
    cat /opt/etc/openvpn/easy-rsa/pki/ca.crt >> ~/$1.ovpn
    echo "</ca>" >> ~/$1.ovpn
    echo "<cert>" >> ~/$1.ovpn
    cat /opt/etc/openvpn/easy-rsa/pki/issued/$1.crt >> ~/$1.ovpn
    echo "</cert>" >> ~/$1.ovpn
    echo "<key>" >> ~/$1.ovpn
    cat /opt/etc/openvpn/easy-rsa/pki/private/$1.key >> ~/$1.ovpn
    echo "</key>" >> ~/$1.ovpn
    echo "key-direction 1" >> ~/$1.ovpn
    echo "<tls-auth>" >> ~/$1.ovpn
    cat ta.key >> ~/$1.ovpn
    echo "</tls-auth>" >> ~/$1.ovpn
}

echo "Getting your ip address....please wait."
IP=$(wget -qO- ipv4.icanhazip.com)


if [[ -e /opt/etc/openvpn/openvpn.conf ]]; then
    while :
    do
    clear
	echo "Looks like OpenVPN is already installed"
	echo ""
	echo "What do you want to do?"
	echo "   1) Add a cert for a new user"
	echo "   2) Revoke existing user cert"
	echo "   3) Exit"
	read -p "Select an option [1-3]: " option
	case $option in
	    1) 
	    echo ""
	    echo "Tell me a name for the client cert"
	    echo "Please, use one word only, no special characters"
	    read -p "Client name: " -e -i client CLIENT
	    cd /opt/etc/openvpn/easy-rsa/
	    ./easyrsa build-client-full $CLIENT nopass
	    # Generates the custom client.ovpn
	    newclient "$CLIENT"
	    echo ""
	    echo "Client $CLIENT added, certs available at ~/$CLIENT.ovpn"
	    exit
	    ;;
	    2)
	    # This option could be documented a bit better and maybe even be simplimplified
	    # ...but what can I say, I want some sleep too
	    NUMBEROFCLIENTS=$(tail -n +2 /opt/etc/openvpn/easy-rsa/pki/index.txt | grep -c "^V")
	    if [[ "$NUMBEROFCLIENTS" = '0' ]]; then
		echo ""
		echo "You have no existing clients!"
		exit 5
	    fi
	    echo ""
	    echo "Select the existing client certificate you want to revoke"
	    tail -n +2 /opt/etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 
	    if [[ "$NUMBEROFCLIENTS" = '1' ]]; then
		read -p "Select one client [1]: " CLIENTNUMBER
	    else
		read -p "Select one client [1-$NUMBEROFCLIENTS]: " CLIENTNUMBER
	    fi
	    CLIENT=$(tail -n +2 /opt/etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 | sed -n "$CLIENTNUMBER"p)
	    cd /opt/etc/openvpn/easy-rsa/
	    ./easyrsa --batch revoke $CLIENT
	    ./easyrsa gen-crl
	    rm -rf pki/reqs/$CLIENT.req
	    rm -rf pki/private/$CLIENT.key
	    rm -rf pki/issued/$CLIENT.crt
	    # And restart
	    /opt/etc/init.d/S20openvpn restart
	    
	    echo ""
	    echo "Certificate for client $CLIENT revoked"
	    exit
	    ;;
	    3) exit;;
	esac
    done
else
    clear
    echo 'Welcome to this quick OpenVPN "road warrior" installer'
    echo ""
    # OpenVPN setup and first user creation
    echo "I need to ask you a few questions before starting the setup"
    echo "You can leave the default options and just press enter if you are ok with them"
    echo ""
    echo "First I need to know the IPv4 address of the network interface you want OpenVPN"
    echo "listening to."
    read -p "IP address: " -e -i $IP IP
    echo ""
    echo "What protocol do you want for OpenVPN?"
    echo "1) UDP"
    echo "2) TCP"
    read -p "Protocol (1 or 2): " -e -i 1 PROTOCOL
	echo "What VPN NET do you want?"
    read -p "VPN network: " -e -i 10.8.0.0 VPN_NET
	echo "Add VPN IP to getaway?"
	echo "y or n"
    read -p "VPN GW? " -e -i no VPN_GW
    echo ""
    if [ "$PROTOCOL" = 2 ]; then
        PROTOCOL=tcp
	PORT=443
    else
        PROTOCOL=udp
	PORT=1194
    fi
	echo "What port do you want for OpenVPN?"
    read -p "Port: " -e -i $PORT PORT
    echo ""
    if ["$VPN_GW" = "y" ]; then
		echo "What DNS do you want to use with the VPN?"
		echo "   1) Current system resolvers"
		echo "   2) Yandex DNS"
		echo "   3) Google"
		read -p "DNS [1-3]: " -e -i 1 DNS
		echo ""
	fi
    echo "RSA key size 2048 or 1024 ?"
    echo "1) 2048"
    echo "2) 1024"
    read -p "RSA key size (1 or 2): " -e -i 1 RSA_KEY_SIZE
    echo ""
    if [ "$RSA_KEY_SIZE" = 2 ]; then
 	RSA_KEY_SIZE=1024
    else
        RSA_KEY_SIZE=2048
    fi
    echo ""
    echo "Finally, tell me your name for the client cert"
    echo "Please, use one word only, no special characters"
    read -p "Client name: " -e -i client CLIENT
    echo ""
    echo "Okay, that was all I needed. We are ready to setup your OpenVPN server now"
    read -n1 -r -p "Press any key to continue..."

    # An old version of easy-rsa was available by default in some openvpn packages
    if [[ -d /opt/etc/openvpn/easy-rsa/ ]]; then
	mv /opt/etc/openvpn/easy-rsa/ /opt/etc/openvpn/easy-rsa-old/
    fi
    # Get easy-rsa
    wget --no-check-certificate -O ~/EasyRSA-3.0.4.tgz https://github.com/OpenVPN/easy-rsa/releases/download/v3.0.4/EasyRSA-3.0.4.tgz
    tar xzf ~/EasyRSA-3.0.4.tgz -C ~/
    mv ~/EasyRSA-3.0.4 /opt/etc/openvpn/easy-rsa/
    chown -R root:root /opt/etc/openvpn/easy-rsa/
    rm -rf ~/EasyRSA-3.0.4.tgz
    cd /opt/etc/openvpn/easy-rsa/
    if [ "$RSA_KEY_SIZE" = 1024 ]; then
	cp vars.example vars
	echo "set_var EASYRSA_KEY_SIZE 1024" >> vars
    fi
    # Create the PKI, set up the CA, the DH params and the server + client certificates
    ./easyrsa init-pki
    ./easyrsa --batch build-ca nopass
    ./easyrsa gen-dh
    ./easyrsa build-server-full server nopass
    ./easyrsa build-client-full $CLIENT nopass
    ./easyrsa gen-crl
    openvpn --genkey --secret ta.key
	echo "local $IP" > /opt/etc/openvpn/openvpn.conf
    echo "port $PORT
proto $PROTOCOL
dev tun
sndbuf 0
rcvbuf 0
topology subnet
server $VPN_NET 255.255.255.0
ifconfig-pool-persist ipp.txt" >> /opt/etc/openvpn/openvpn.conf

if ["$VPN_GW" = "y" ]; then
	echo 'push "redirect-gateway def1 bypass-dhcp"' >> /opt/etc/openvpn/openvpn.conf
    # DNS
    case $DNS in
	1) 
	# Obtain the resolvers from resolv.conf and use them for OpenVPN
	grep -v '#' /etc/resolv.conf | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do
	    echo "push \"dhcp-option DNS $line\"" >> /opt/etc/openvpn/openvpn.conf
	done
	;;
	2)
	echo 'push "dhcp-option DNS 77.88.8.8"' >> /opt/etc/openvpn/openvpn.conf
	echo 'push "dhcp-option DNS 77.88.8.1"' >> /opt/etc/openvpn/openvpn.conf
	;;
	3) 
	echo 'push "dhcp-option DNS 8.8.8.8"' >> /opt/etc/openvpn/openvpn.conf
	echo 'push "dhcp-option DNS 8.8.4.4"' >> /opt/etc/openvpn/openvpn.conf
	;;
    esac
fi
    echo "keepalive 10 120
push \"route 192.168.1.0 255.255.255.0\"
cipher AES-256-CBC
compress
status /opt/var/log/openvpn-status.log
log-append  /opt/var/log/openvpn.log
client-to-client
persist-key
persist-tun
verb 3
explicit-exit-notify 1
crl-verify /opt/etc/openvpn/easy-rsa/pki/crl.pem" >> /opt/etc/openvpn/openvpn.conf
    echo '<ca>' >> /opt/etc/openvpn/openvpn.conf
    cat pki/ca.crt  >> /opt/etc/openvpn/openvpn.conf
    echo '</ca>'  >> /opt/etc/openvpn/openvpn.conf
    echo '<cert>'  >> /opt/etc/openvpn/openvpn.conf
    cat pki/issued/server.crt  >> /opt/etc/openvpn/openvpn.conf
    echo '</cert>'  >> /opt/etc/openvpn/openvpn.conf
    echo '<key>'  >> /opt/etc/openvpn/openvpn.conf
    cat pki/private/server.key  >> /opt/etc/openvpn/openvpn.conf
    echo '</key>'  >> /opt/etc/openvpn/openvpn.conf
    echo '<dh>'  >> /opt/etc/openvpn/openvpn.conf
    cat pki/dh.pem  >> /opt/etc/openvpn/openvpn.conf
    echo '</dh>'  >> /opt/etc/openvpn/openvpn.conf
    echo 'key-direction 0'  >> /opt/etc/openvpn/openvpn.conf
    echo '<tls-auth>' >> /opt/etc/openvpn/openvpn.conf
    cat ta.key  >> /opt/etc/openvpn/openvpn.conf
    echo '</tls-auth>'  >> /opt/etc/openvpn/openvpn.conf

    echo "#!/bin/sh

[ \"\$table\" != "filter" ] && exit 0   # check the table name
iptables -I INPUT -i tun0 -j ACCEPT
iptables -I FORWARD -s $VPN_NET/24 -j ACCEPT
iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT" >> /opt/etc/ndm/netfilter.d/052-openvpn-filter.sh

chmod +x /opt/etc/ndm/netfilter.d/052-openvpn-filter.sh

echo "#!/bin/sh

[ \"\$table\" != "nat" ] && exit 0   # check the table name
iptables -t nat -A POSTROUTING -s $VPN_NET/24 -j SNAT --to $IP" >> /opt/etc/ndm/netfilter.d/053-openvpn-nat.sh



chmod +x /opt/etc/ndm/netfilter.d/053-openvpn-nat.sh

    echo "client
dev tun
proto $PROTOCOL
sndbuf 0
rcvbuf 0
remote $IP $PORT
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
cipher AES-256-CBC
compress
verb 3" > /opt/etc/openvpn/client-common.txt
    # Generates the custom client.ovpn
    newclient "$CLIENT"
    echo ""
    echo "Finished!"
    echo ""
    echo "Your client config is available at ~/$CLIENT.ovpn"
    echo "If you want to add more clients, you simply need to run this script another time!"
fi

 

Edited by ChaoticSerg
Изменены DNS, добавлен выбор IP для VPN сети, сделан выбор "нужен ли getaway"
  • Thanks 2
  • Upvote 1

Share this post


Link to post
Share on other sites

Добрый день!

Только что настроил с этим скриптом OpenVPN на прошивке 2.11.C.0.0-2, все отлично работает, спасибо! Неплохо было добавить в скрипт проверку установленных пакетов openvpn, openvpn-utils и iptables.

P.S. Скрипт /opt/etc/init.d/S20openvpn не стартует после ребута, приходится ручками поднимать (./S20openvpn start). В чем может быть проблема?

Share this post


Link to post
Share on other sites

В Приложения > OPKG

Сценарий initrc: есть такая запись: "/opt/etc/init.d/rc.unslung"

Share this post


Link to post
Share on other sites
2 минуты назад, dexter сказал:

В Приложения > OPKG

Сценарий initrc: есть такая запись: "/opt/etc/init.d/rc.unslung"

Включено:

image.png.b6338a972eea08f3b010252e5ec5c563.png

Share this post


Link to post
Share on other sites

Тогда вставляйте в скрипт запуска logger и смотрите после какой строки все отвалится.

 

Share this post


Link to post
Share on other sites
1 час назад, denmmx сказал:

Добрый день!

Только что настроил с этим скриптом OpenVPN на прошивке 2.11.C.0.0-2, все отлично работает, спасибо! Неплохо было добавить в скрипт проверку установленных пакетов openvpn, openvpn-utils и iptables.

P.S. Скрипт /opt/etc/init.d/S20openvpn не стартует после ребута, приходится ручками поднимать (./S20openvpn start). В чем может быть проблема?

Есть такая особенность у некоторых моих клиентов. Думаю дело в том, что у них pptp не успевает подняться до старта OpenVPN. Пока некогда было разбираться, но может пауза на несколько секунд в начале стартового скрипта поможет.

  • Thanks 1

Share this post


Link to post
Share on other sites
37 минут назад, ChaoticSerg сказал:

Есть такая особенность у некоторых моих клиентов. Думаю дело в том, что у них pptp не успевает подняться до старта OpenVPN. Пока некогда было разбираться, но может пауза на несколько секунд в начале стартового скрипта поможет.

Да, действительно, используется l2tp. Поставил паузу sleep 10 в начале скрипта, теперь работает.

Share this post


Link to post
Share on other sites
5 часов назад, ChaoticSerg сказал:

Есть такая особенность у некоторых моих клиентов. Думаю дело в том, что у них pptp не успевает подняться до старта OpenVPN. Пока некогда было разбираться, но может пауза на несколько секунд в начале стартового скрипта поможет.

Немного дикарский метод, когда есть
https://github.com/ndmsystems/packages/wiki/Opkg-Component#ndmifstatechangedd

  • Thanks 1

Share this post


Link to post
Share on other sites

Как долго должна длиться работа скрипта? Уже четвёртый час пошёл, как точки с плюсами по экрану бегут. Может что-то пошло не так?

 

Прошло около получаса с момента написания этого сообщения - скрипт успешно завершил работу. В общем понятно, что я просто проявил нетерпение :) Знал бы, как удалить сообщение - удалил бы, бесполезное оно для темы.

Edited by gamych
Дождался

Share this post


Link to post
Share on other sites

Новая версия. из основного - если у кого не 192.168.1.X, то должен сам скрипт определить и добавить в маршруты.

#!/opt/bin/bash
#OpenVPN road warrior installer for Entware-NG running on NDMS v.2. Please see http://keenopt.ru and http://forums.zyxmon.org
#This script will let you setup your own VPN server in a few minutes, even if you haven't used OpenVPN before

if [[ ! -e /dev/net/tun ]]; then
    echo "TUN/TAP is not available"
    exit 1
fi

newclient () {
    # Generates the custom client.ovpn
    cp /opt/etc/openvpn/client-common.txt ~/$1.ovpn
    echo "<ca>" >> ~/$1.ovpn
    cat /opt/etc/openvpn/easy-rsa/pki/ca.crt >> ~/$1.ovpn
    echo "</ca>" >> ~/$1.ovpn
    echo "<cert>" >> ~/$1.ovpn
    cat /opt/etc/openvpn/easy-rsa/pki/issued/$1.crt >> ~/$1.ovpn
    echo "</cert>" >> ~/$1.ovpn
    echo "<key>" >> ~/$1.ovpn
    cat /opt/etc/openvpn/easy-rsa/pki/private/$1.key >> ~/$1.ovpn
    echo "</key>" >> ~/$1.ovpn
    echo "key-direction 1" >> ~/$1.ovpn
    echo "<tls-auth>" >> ~/$1.ovpn
    cat ta.key >> ~/$1.ovpn
    echo "</tls-auth>" >> ~/$1.ovpn
}

echo "Test installed components"
IO=$(opkg list-installed |grep openvpn)

if [ -n "$IO" ]
then
  echo "OpenVPN installed";
else
  opkg install openvpn-openssl
fi

IO2=$(opkg list-installed |grep openssl-util)

if [ -n "$IO2" ]
then
  echo "openssl-util installed";
else
  opkg install openssl-util
fi

IW=$(opkg list-installed |grep wget)

if [ -n "$IW" ]
then
  echo "wget installed";
else
  opkg install wget
fi

II=$(opkg list-installed |grep iptables)

if [ -n "$II" ]
then
  echo "Iptables installed";
else
  opkg install iptables
fi

echo "Getting your ip address....please wait."
IP=$(wget -qO- ipv4.icanhazip.com)
LOCALNET=$(ip a | grep -o -E '(192.168.[0-9]{1,3}\.)1')

if [[ -e /opt/etc/openvpn/openvpn.conf ]]; then
    while :
    do
    clear
    echo "Looks like OpenVPN is already installed"
    echo ""
    echo "What do you want to do?"
    echo "   1) Add a cert for a new user"
    echo "   2) Revoke existing user cert"
    echo "   3) Exit"
    read -p "Select an option [1-3]: " option
    case $option in
        1)
        echo ""
        echo "Tell me a name for the client cert"
        echo "Please, use one word only, no special characters"
        read -p "Client name: " -e -i client CLIENT
        cd /opt/etc/openvpn/easy-rsa/
        ./easyrsa build-client-full $CLIENT nopass
        # Generates the custom client.ovpn
        newclient "$CLIENT"
        echo ""
        echo "Client $CLIENT added, certs available at ~/$CLIENT.ovpn"
        exit
        ;;
        2)
        # This option could be documented a bit better and maybe even be simplimplified
        # ...but what can I say, I want some sleep too
        NUMBEROFCLIENTS=$(tail -n +2 /opt/etc/openvpn/easy-rsa/pki/index.txt | grep -c "^V")
        if [[ "$NUMBEROFCLIENTS" = "0" ]]; then
        echo ""
        echo "You have no existing clients!"
        exit 5
        fi
        echo ""
        echo "Select the existing client certificate you want to revoke"
        tail -n +2 /opt/etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2
        if [[ "$NUMBEROFCLIENTS" = "1" ]]; then
        read -p "Select one client [1]: " CLIENTNUMBER
        else
        read -p "Select one client [1-$NUMBEROFCLIENTS]: " CLIENTNUMBER
        fi
        CLIENT=$(tail -n +2 /opt/etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 | sed -n "$CLIENTNUMBER"p)
        cd /opt/etc/openvpn/easy-rsa/
        ./easyrsa --batch revoke $CLIENT
        ./easyrsa gen-crl
        rm -rf pki/reqs/$CLIENT.req
        rm -rf pki/private/$CLIENT.key
        rm -rf pki/issued/$CLIENT.crt
        # And restart
        /opt/etc/init.d/S20openvpn restart

        echo ""
        echo "Certificate for client $CLIENT revoked"
        exit
        ;;
        3) exit;;
    esac
    done
else
    clear
    echo "Welcome to this quick OpenVPN \"road warrior\" installer"
    echo ""
    # OpenVPN setup and first user creation
    echo "I need to ask you a few questions before starting the setup"
    echo "You can leave the default options and just press enter if you are ok with them"
    echo ""
    echo "First I need to know the IPv4 address of the network interface you want OpenVPN"
    echo "listening to."
    read -p "IP address: " -e -i $IP IP
    echo ""
    echo "What protocol do you want for OpenVPN?"
    echo "1) UDP"
    echo "2) TCP"
    read -p "Protocol (1 or 2): " -e -i 1 PROTOCOL
    echo "What VPN NET do you want?"
    read -p "VPN network: " -e -i 10.8.0.0 VPN_NET
    echo "Add VPN IP to getaway?"
    echo "y or n"
    read -p "VPN GW? " -e -i no VPN_GW
    echo ""
    if [ "$PROTOCOL" = 2 ]; then
        PROTOCOL=tcp
    PORT=443
    else
        PROTOCOL=udp
    PORT=1194
    fi
    echo "What port do you want for OpenVPN?"
    read -p "Port: " -e -i $PORT PORT
    echo ""
    if ["$VPN_GW" = "y" ]; then
        echo "What DNS do you want to use with the VPN?"
        echo "   1) Current system resolvers"
        echo "   2) Yandex DNS"
        echo "   3) Google"
        read -p "DNS [1-3]: " -e -i 1 DNS
        echo ""
    fi
    echo "RSA key size 2048 or 1024 ?"
    echo "1) 2048"
    echo "2) 1024"
    read -p "RSA key size (1 or 2): " -e -i 1 RSA_KEY_SIZE
    echo ""
    if [ "$RSA_KEY_SIZE" = 2 ]; then
    RSA_KEY_SIZE=1024
    else
        RSA_KEY_SIZE=2048
    fi
    echo ""
    echo "Finally, tell me your name for the client cert"
    echo "Please, use one word only, no special characters"
    read -p "Client name: " -e -i client CLIENT
    echo ""
    echo "Okay, that was all I needed. We are ready to setup your OpenVPN server now"
    read -n1 -r -p "Press any key to continue..."

    # An old version of easy-rsa was available by default in some openvpn packages
    if [[ -d /opt/etc/openvpn/easy-rsa/ ]]; then
    mv /opt/etc/openvpn/easy-rsa/ /opt/etc/openvpn/easy-rsa-old/
    fi
    # Get easy-rsa
    wget --no-check-certificate -O ~/EasyRSA-3.0.4.tgz https://github.com/OpenVPN/easy-rsa/releases/download/v3.0.4/EasyRSA-3.0.4.tgz
    tar xzf ~/EasyRSA-3.0.4.tgz -C ~/
    mv ~/EasyRSA-3.0.4 /opt/etc/openvpn/easy-rsa/
    chown -R root:root /opt/etc/openvpn/easy-rsa/
    rm -rf ~/EasyRSA-3.0.4.tgz
    cd /opt/etc/openvpn/easy-rsa/
    if [ "$RSA_KEY_SIZE" = 1024 ]; then
    cp vars.example vars
    echo "set_var EASYRSA_KEY_SIZE 1024" >> vars
    fi
    # Create the PKI, set up the CA, the DH params and the server + client certificates
    ./easyrsa init-pki
    ./easyrsa --batch build-ca nopass
    ./easyrsa gen-dh
    ./easyrsa build-server-full server nopass
    ./easyrsa build-client-full $CLIENT nopass
    ./easyrsa gen-crl
    openvpn --genkey --secret ta.key
    echo "local $IP" > /opt/etc/openvpn/openvpn.conf
    echo "port $PORT" >> /opt/etc/openvpn/openvpn.conf
    echo "proto $PROTOCOL" >> /opt/etc/openvpn/openvpn.conf
    echo "dev tun" >> /opt/etc/openvpn/openvpn.conf
    echo "sndbuf 0" >> /opt/etc/openvpn/openvpn.conf
    echo "rcvbuf 0" >> /opt/etc/openvpn/openvpn.conf
    echo "topology subnet" >> /opt/etc/openvpn/openvpn.conf
    echo "server $VPN_NET 255.255.255.0" >> /opt/etc/openvpn/openvpn.conf
    echo "ifconfig-pool-persist ipp.txt" >> /opt/etc/openvpn/openvpn.conf



if [ "$VPN_GW" = y ]; then
    echo "push \"redirect-gateway def1 bypass-dhcp\"" >> /opt/etc/openvpn/openvpn.conf
    # DNS
    case $DNS in
    1)
    # Obtain the resolvers from resolv.conf and use them for OpenVPN
    grep -v '#' /etc/resolv.conf | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do
        echo "push \"dhcp-option DNS $line\"" >> /opt/etc/openvpn/openvpn.conf
    done
    ;;
    2)
    echo "push \"dhcp-option DNS 77.88.8.8\"" >> /opt/etc/openvpn/openvpn.conf
    echo "push \"dhcp-option DNS 77.88.8.1\"" >> /opt/etc/openvpn/openvpn.conf
    ;;
    3)
    echo "push \"dhcp-option DNS 8.8.8.8\"" >> /opt/etc/openvpn/openvpn.conf
    echo "push \"dhcp-option DNS 8.8.4.4\"" >> /opt/etc/openvpn/openvpn.conf
    ;;
    esac
fi
    echo "keepalive 10 120" >> /opt/etc/openvpn/openvpn.conf
    echo "push \"route $LOCALNET 255.255.255.0\"" >> /opt/etc/openvpn/openvpn.conf
    echo "cipher AES-256-CBC" >> /opt/etc/openvpn/openvpn.conf
    echo "compress" >> /opt/etc/openvpn/openvpn.conf
    echo "status /opt/var/log/openvpn-status.log" >> /opt/etc/openvpn/openvpn.conf
    echo "log-append  /opt/var/log/openvpn.log" >> /opt/etc/openvpn/openvpn.conf
    echo "client-to-client" >> /opt/etc/openvpn/openvpn.conf
    echo "persist-key" >> /opt/etc/openvpn/openvpn.conf
    echo "persist-tun" >> /opt/etc/openvpn/openvpn.conf
    echo "verb 3" >> /opt/etc/openvpn/openvpn.conf
    echo "explicit-exit-notify 1" >> /opt/etc/openvpn/openvpn.conf
    echo "crl-verify /opt/etc/openvpn/easy-rsa/pki/crl.pem" >> /opt/etc/openvpn/openvpn.conf

    echo "<ca>" >> /opt/etc/openvpn/openvpn.conf
    cat pki/ca.crt  >> /opt/etc/openvpn/openvpn.conf
    echo "</ca>"  >> /opt/etc/openvpn/openvpn.conf
    echo "<cert>"  >> /opt/etc/openvpn/openvpn.conf
    cat pki/issued/server.crt  >> /opt/etc/openvpn/openvpn.conf
    echo "</cert>"  >> /opt/etc/openvpn/openvpn.conf
    echo "<key>"  >> /opt/etc/openvpn/openvpn.conf
    cat pki/private/server.key  >> /opt/etc/openvpn/openvpn.conf
    echo "</key>"  >> /opt/etc/openvpn/openvpn.conf
    echo "<dh>"  >> /opt/etc/openvpn/openvpn.conf
    cat pki/dh.pem  >> /opt/etc/openvpn/openvpn.conf
    echo "</dh>"  >> /opt/etc/openvpn/openvpn.conf
    echo "key-direction 0"  >> /opt/etc/openvpn/openvpn.conf
    echo "<tls-auth>" >> /opt/etc/openvpn/openvpn.conf
    cat ta.key  >> /opt/etc/openvpn/openvpn.conf
    echo "</tls-auth>"  >> /opt/etc/openvpn/openvpn.conf

    echo "#!/bin/sh

[ \"\$table\" != \"filter\" ] && exit 0   # check the table name
iptables -I INPUT -i tun0 -j ACCEPT
iptables -I FORWARD -s $VPN_NET/24 -j ACCEPT
iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT" >> /opt/etc/ndm/netfilter.d/052-openvpn-filter.sh

chmod +x /opt/etc/ndm/netfilter.d/052-openvpn-filter.sh

echo "#!/bin/sh

[ \"\$table\" != \"nat\" ] && exit 0   # check the table name
iptables -t nat -A POSTROUTING -s $VPN_NET/24 -j SNAT --to $IP" >> /opt/etc/ndm/netfilter.d/053-openvpn-nat.sh



chmod +x /opt/etc/ndm/netfilter.d/053-openvpn-nat.sh

    echo "client" > /opt/etc/openvpn/client-common.txt
    echo "dev tun" >> /opt/etc/openvpn/client-common.txt
    echo "proto $PROTOCOL" >> /opt/etc/openvpn/client-common.txt
    echo "sndbuf 0" >> /opt/etc/openvpn/client-common.txt
    echo "rcvbuf 0" >> /opt/etc/openvpn/client-common.txt
    echo "remote $IP $PORT" >> /opt/etc/openvpn/client-common.txt
    echo "resolv-retry infinite" >> /opt/etc/openvpn/client-common.txt
    echo "nobind" >> /opt/etc/openvpn/client-common.txt
    echo "persist-key" >> /opt/etc/openvpn/client-common.txt
    echo "persist-tun" >> /opt/etc/openvpn/client-common.txt
    echo "remote-cert-tls server" >> /opt/etc/openvpn/client-common.txt
    echo "cipher AES-256-CBC" >> /opt/etc/openvpn/client-common.txt
    echo "compress" >> /opt/etc/openvpn/client-common.txt
    echo "verb 3" >> /opt/etc/openvpn/client-common.txt


    # Generates the custom client.ovpn
    newclient "$CLIENT"
    echo ""
    echo "Finished!"
    echo ""
    echo "Your client config is available at ~/$CLIENT.ovpn"
    echo "If you want to add more clients, you simply need to run this script another time!"

 

Edited by ChaoticSerg
Теперь скрит доустановит необходимые пакеты сам.

Share this post


Link to post
Share on other sites

Just for information. Оригинал этого скрипта тут - https://github.com/Nyr/openvpn-install

Скрипт постоянно дорабатывается, последнее изменение менее недели назад.

Скрипт (оригинал) предназначен для развертывания на VPS и Debian-based дистрибутиве.

Share this post


Link to post
Share on other sites

Спасибо, но я на основе этого скрипта уже свой давно делаю для RHEL.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×