Jump to content

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


Recommended Posts

Добрый день.

Хочу предложить всем скрипт, который я доработал. Изначально ссылкой поделился 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 3
  • Upvote 1
Link to comment
Share on other sites

  • 3 weeks later...

Добрый день!

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

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

Link to comment
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
Link to comment
Share on other sites

37 минут назад, ChaoticSerg сказал:

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

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

Link to comment
Share on other sites

5 часов назад, ChaoticSerg сказал:

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

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

  • Thanks 2
Link to comment
Share on other sites

  • 2 weeks later...

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

 

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

Edited by gamych
Дождался
Link to comment
Share on other sites

  • 3 weeks later...

Новая версия. из основного - если у кого не 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!"
fi

 

Edited by ChaoticSerg
Теперь скрит доустановит необходимые пакеты сам.
Link to comment
Share on other sites

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

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

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

Link to comment
Share on other sites

  • 3 months later...
В 28.03.2018 в 12:50, gamych сказал:

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

Для ускорения генерации ключей рекомендую перед запуском скрипта ставить пакет haveged - генератор энтропии.
opkg install haveged
/opt/etc/init.d/S02haveged start

Edited by HuduGuru
и запустить
Link to comment
Share on other sites

  • 7 months later...
  • 2 months later...

Добрый день. При соединении, в логах клиента отображается ошибка "compress must have at least two arguments" и дальше соединение не идет.

В логах на роутере:

Quote

Authenticate/Decrypt packet error: bad packet ID (may be a replay): [ #8 / time = (1577960140) Thu Jan  2 13:15:40 2020 ] -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings
Thu Jan  2 13:15:41 2020 predoc/46.133.141.171:34317 TLS Error: incoming packet authentication failed from 

В чем может быть дело?

Link to comment
Share on other sites

  • 2 weeks later...
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

Подскажите, как вы вот этот скрипт заставили работать? Ведь netfilter не обрабатывает таблицу nat.

Если добавить что нибудь типа такого скрипта 

#!/bin/sh

logger "$type($table): Test rule"

exit 0

То в логе никогда не выведется

iptables(nat): Test rule

только


iptables(filter): Test rule
iptables(mangle): Test rule

Об этой особенности на форме тут уже писали.

Edited by BonDyaRa
Link to comment
Share on other sites

8 hours ago, BonDyaRa said:

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

Подскажите, как вы вот этот скрипт заставили работать? Ведь netfilter не обрабатывает таблицу nat.

Если добавить что нибудь типа такого скрипта 


#!/bin/sh

logger "$type($table): Test rule"

exit 0

То в логе никогда не выведется

iptables(nat): Test rule

только


iptables(filter): Test rule
iptables(mangle): Test rule

Об этой особенности на форме тут уже писали.

Не обрабатывается, только для IPv6. Читайте внимательней.

Link to comment
Share on other sites

  • 3 months later...

Всем добрый день.

Доработал снова скрипт:

Добавил отдачу маршрутов, если у вас их несколько (настроены VLAN) и переписал некоторые переменные.

Убрал компрессию, перестала работать под андройд, как описал somers.

Пока не проверял (точнее проверял на другой системе и внес правки и в этот). Если что пишите в личку.

openvpn.bash

Edited by ChaoticSerg
Link to comment
Share on other sites

  • 2 weeks later...
В 17.01.2020 в 07:54, avn сказал:

Не обрабатывается, только для IPv6. Читайте внимательней.

К сожалению, это не написано в официальной документации, а именно тут: https://github.com/ndmsystems/packages/wiki/Opkg-Component#ndmnetfilterd (ПРОСЬБА ЭТО УКАЗАТЬ)

Просто перечисление доступных таблиц.

 

Опять же по скрипту, там явно не IPv6 обрабатывается, а значит выполняться эта часть сценария не будет 

Link to comment
Share on other sites

22 минуты назад, kekych сказал:

...

Опять же по скрипту, там явно не IPv6 обрабатывается, а значит выполняться эта часть сценария не будет 

И вообще, как я понял, маскарадинг уже прописан в цепочке _NDM_MASQ

Link to comment
Share on other sites

On 5/3/2020 at 6:10 PM, kekych said:

К сожалению, это не написано в официальной документации, а именно тут: https://github.com/ndmsystems/packages/wiki/Opkg-Component#ndmnetfilterd (ПРОСЬБА ЭТО УКАЗАТЬ)

Просто перечисление доступных таблиц.

 

Опять же по скрипту, там явно не IPv6 обрабатывается, а значит выполняться эта часть сценария не будет 

Создайте стартовый скрипт:

#!/bin/sh

[ "$1" != "start" ] && exit 0

type=iptables table=nat /opt/etc/ndm/netfilter.d/100-redirect.sh
type=ip6tables table=nat /opt/etc/ndm/netfilter.d/100-redirect6.sh

И проблема решена.

Edited by avn
Link to comment
Share on other sites

  • 3 years later...

День добрый, дамы и господа. Скрипт хорош. Испытал и все отлично. Допилил под себя немного. Скидываю сюда, если кому понадобится. Протестировано и стабильно работает. Использовал генерацию ключа на 4096 бит. Готовьтесь к примерно 4..6-часовому ожиданию в таком случае. В тесте просто замените под себя значения переменных страны, области, города, организации, почты и "отдела". Всем удачи!

#!/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
#This script is being finalized ChaoticSerg and is located on the forum https://forum.keenetic.net/.

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=$(route |grep -o -E '192.168.[0-9]{1,3}.0')

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 --batch build-client-full $CLIENT
        # 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.110.10.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"
        echo "   4) Quad9"
        read -p "DNS [1-4]: " -e -i 1 DNS
        echo ""
    fi
    echo "RSA key size 4096 or 3072 ?"
    echo "1) 4096"
    echo "2) 3072"
    read -p "RSA key size (1 or 2): " -e -i 1 RSA_KEY_SIZE
    echo ""
    if [ "$RSA_KEY_SIZE" = 2 ]; then
    RSA_KEY_SIZE=3072
    else
        RSA_KEY_SIZE=4096
    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/
#   openssl rand -writerand /opt/etc/openvpn/easy-rsa/pki/.rnd
    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" = 4096 ]; then
    cp vars.example vars
    echo "set_var EASYRSA_REQ_COUNTRY "Country"" >> vars
    echo "set_var EASYRSA_REQ_PROVINCE "Province"" >> vars
    echo "set_var EASYRSA_REQ_CITY "City"" >> vars
    echo "set_var EASYRSA_REQ_ORG "WTF_ORG"" >> vars
    echo "set_var EASYRSA_REQ_EMAIL "dick@pochta.net"" >> vars
    echo "set_var EASYRSA_REQ_OU "Valhalla"" >> vars
    echo "set_var EASYRSA_KEY_SIZE 4096" >> vars
    echo "set_var EASYRSA_ALGO rsa" >> vars
    echo "set_var EASYRSA_CURVE secp384r1" >> vars
    echo "set_var EASYRSA_CA_EXPIRE 3650" >> vars
    echo "set_var EASYRSA_CERT_EXPIRE 3650" >> vars
    echo "set_var EASYRSA_DIGEST "sha384"" >> vars
    else
        cp vars.example vars
    	echo "set_var EASYRSA_REQ_COUNTRY "Country"" >> vars
    	echo "set_var EASYRSA_REQ_PROVINCE "Province"" >> vars
    	echo "set_var EASYRSA_REQ_CITY "City"" >> vars
    	echo "set_var EASYRSA_REQ_ORG "WTF_ORG"" >> vars
    	echo "set_var EASYRSA_REQ_EMAIL "dick@pochta.net"" >> vars
    	echo "set_var EASYRSA_REQ_OU "Valhalla"" >> vars
    	echo "set_var EASYRSA_KEY_SIZE 3072" >> vars
    	echo "set_var EASYRSA_ALGO rsa" >> vars
    	echo "set_var EASYRSA_CURVE secp256r1" >> vars
    	echo "set_var EASYRSA_CA_EXPIRE 3650" >> vars
    	echo "set_var EASYRSA_CERT_EXPIRE 3650" >> vars
    	echo "set_var EASYRSA_DIGEST "sha256"" >> vars
    fi
    # Create the PKI, set up the CA, the DH params and the server + client certificates
    ./easyrsa init-pki
    openssl rand -writerand /opt/etc/openvpn/easy-rsa/pki/.rnd
    ./easyrsa --batch build-ca nopass
    ./easyrsa gen-dh
    ./easyrsa build-server-full server nopass
#    ./easyrsa build-client-full $CLIENT nopass
#    echo "You will be asked for the client password below"
    ./easyrsa --batch build-client-full "$CLIENT"    
    ./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
    echo "keepalive 10 120" >> /opt/etc/openvpn/openvpn.conf

if [ "$VPN_GW" = y ]; then
    echo "push \"redirect-gateway def1 bypass-dhcp\"" >> /opt/etc/openvpn/openvpn.conf
fi
    # Route
        route | grep -o -E '192.168.[0-9]{1,3}\.0' | while read line; do
        echo "push \"route $line\"" >> /opt/etc/openvpn/openvpn.conf
        done

    # 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
        ;;
	4)
	echo 'push "dhcp-option DNS 9.9.9.9"' >> /opt/etc/openvpn/openvpn.conf
        echo 'push "dhcp-option DNS 149.112.112.112"' >> /opt/etc/openvpn/openvpn.conf
esac


    echo "cipher AES-256-GCM" >> /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 "auth-nocache" >> /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-GCM" >> /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!"
fi

 

Link to comment
Share on other sites

  • 4 months later...
В 07.10.2023 в 14:56, Pure Gen сказал:

День добрый, дамы и господа. Скрипт хорош. Испытал и все отлично. Допилил под себя немного. Скидываю сюда, если кому понадобится. Протестировано и стабильно работает. Использовал генерацию ключа на 4096 бит. Готовьтесь к примерно 4..6-часовому ожиданию в таком случае. В тесте просто замените под себя значения переменных страны, области, города, организации, почты и "отдела". Всем удачи!

#!/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
#This script is being finalized ChaoticSerg and is located on the forum https://forum.keenetic.net/.

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=$(route |grep -o -E '192.168.[0-9]{1,3}.0')

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 --batch build-client-full $CLIENT
        # 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.110.10.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"
        echo "   4) Quad9"
        read -p "DNS [1-4]: " -e -i 1 DNS
        echo ""
    fi
    echo "RSA key size 4096 or 3072 ?"
    echo "1) 4096"
    echo "2) 3072"
    read -p "RSA key size (1 or 2): " -e -i 1 RSA_KEY_SIZE
    echo ""
    if [ "$RSA_KEY_SIZE" = 2 ]; then
    RSA_KEY_SIZE=3072
    else
        RSA_KEY_SIZE=4096
    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/
#   openssl rand -writerand /opt/etc/openvpn/easy-rsa/pki/.rnd
    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" = 4096 ]; then
    cp vars.example vars
    echo "set_var EASYRSA_REQ_COUNTRY "Country"" >> vars
    echo "set_var EASYRSA_REQ_PROVINCE "Province"" >> vars
    echo "set_var EASYRSA_REQ_CITY "City"" >> vars
    echo "set_var EASYRSA_REQ_ORG "WTF_ORG"" >> vars
    echo "set_var EASYRSA_REQ_EMAIL "dick@pochta.net"" >> vars
    echo "set_var EASYRSA_REQ_OU "Valhalla"" >> vars
    echo "set_var EASYRSA_KEY_SIZE 4096" >> vars
    echo "set_var EASYRSA_ALGO rsa" >> vars
    echo "set_var EASYRSA_CURVE secp384r1" >> vars
    echo "set_var EASYRSA_CA_EXPIRE 3650" >> vars
    echo "set_var EASYRSA_CERT_EXPIRE 3650" >> vars
    echo "set_var EASYRSA_DIGEST "sha384"" >> vars
    else
        cp vars.example vars
    	echo "set_var EASYRSA_REQ_COUNTRY "Country"" >> vars
    	echo "set_var EASYRSA_REQ_PROVINCE "Province"" >> vars
    	echo "set_var EASYRSA_REQ_CITY "City"" >> vars
    	echo "set_var EASYRSA_REQ_ORG "WTF_ORG"" >> vars
    	echo "set_var EASYRSA_REQ_EMAIL "dick@pochta.net"" >> vars
    	echo "set_var EASYRSA_REQ_OU "Valhalla"" >> vars
    	echo "set_var EASYRSA_KEY_SIZE 3072" >> vars
    	echo "set_var EASYRSA_ALGO rsa" >> vars
    	echo "set_var EASYRSA_CURVE secp256r1" >> vars
    	echo "set_var EASYRSA_CA_EXPIRE 3650" >> vars
    	echo "set_var EASYRSA_CERT_EXPIRE 3650" >> vars
    	echo "set_var EASYRSA_DIGEST "sha256"" >> vars
    fi
    # Create the PKI, set up the CA, the DH params and the server + client certificates
    ./easyrsa init-pki
    openssl rand -writerand /opt/etc/openvpn/easy-rsa/pki/.rnd
    ./easyrsa --batch build-ca nopass
    ./easyrsa gen-dh
    ./easyrsa build-server-full server nopass
#    ./easyrsa build-client-full $CLIENT nopass
#    echo "You will be asked for the client password below"
    ./easyrsa --batch build-client-full "$CLIENT"    
    ./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
    echo "keepalive 10 120" >> /opt/etc/openvpn/openvpn.conf

if [ "$VPN_GW" = y ]; then
    echo "push \"redirect-gateway def1 bypass-dhcp\"" >> /opt/etc/openvpn/openvpn.conf
fi
    # Route
        route | grep -o -E '192.168.[0-9]{1,3}\.0' | while read line; do
        echo "push \"route $line\"" >> /opt/etc/openvpn/openvpn.conf
        done

    # 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
        ;;
	4)
	echo 'push "dhcp-option DNS 9.9.9.9"' >> /opt/etc/openvpn/openvpn.conf
        echo 'push "dhcp-option DNS 149.112.112.112"' >> /opt/etc/openvpn/openvpn.conf
esac


    echo "cipher AES-256-GCM" >> /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 "auth-nocache" >> /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-GCM" >> /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!"
fi

 

При установке на Entware kn-1010 получается такое. Как я понимаю wget не может скачать с https

 

 

Okay, that was all I needed. We are ready to setup your OpenVPN server now
Press any key to continue...
wget: unrecognized option '--no-check-certificate'
Usage: wget [OPTION]... [URL]...

Try `wget --help' for more options.
tar: can't open '/opt/root/EasyRSA-3.0.4.tgz': No such file or directory
mv: can't rename '/opt/root/EasyRSA-3.0.4': No such file or directory
chown: /opt/etc/openvpn/easy-rsa/: No such file or directory
1ovpn.sh: line 199: cd: /opt/etc/openvpn/easy-rsa/: No such file or directory
cp: can't stat 'vars.example': No such file or directory
1ovpn.sh: line 230: ./easyrsa: No such file or directory
Cannot write random bytes:
30507277:error:12000079:random number generator:RAND_write_file:Cannot open file                                                                                        :crypto/rand/randfile.c:240:Filename=/opt/etc/openvpn/easy-rsa/pki/.rnd
1ovpn.sh: line 232: ./easyrsa: No such file or directory
1ovpn.sh: line 233: ./easyrsa: No such file or directory
1ovpn.sh: line 234: ./easyrsa: No such file or directory
1ovpn.sh: line 237: ./easyrsa: No such file or directory
1ovpn.sh: line 238: ./easyrsa: No such file or directory
2024-02-08 14:05:56 DEPRECATED OPTION: The option --secret is deprecated.
2024-02-08 14:05:56 WARNING: Using --genkey --secret filename is DEPRECATED.  Us                                                                                        e --genkey secret filename instead.
cat: can't open 'pki/ca.crt': No such file or directory
cat: can't open 'pki/issued/server.crt': No such file or directory
cat: can't open 'pki/private/server.key': No such file or directory
cat: can't open 'pki/dh.pem': No such file or directory
cat: can't open '/opt/etc/openvpn/easy-rsa/pki/ca.crt': No such file or director                                                                                        y
cat: can't open '/opt/etc/openvpn/easy-rsa/pki/issued/client.crt': No such file                                                                                         or directory
cat: can't open '/opt/etc/openvpn/easy-rsa/pki/private/client.key': No such file                                                                                         or directory

Finished!
 

Edited by Demos
Link to comment
Share on other sites

В 08.02.2024 в 21:20, Demos сказал:

При установке на Entware kn-1010 получается такое. Как я понимаю wget не может скачать с https

 

 

Okay, that was all I needed. We are ready to setup your OpenVPN server now
Press any key to continue...
wget: unrecognized option '--no-check-certificate'
Usage: wget [OPTION]... [URL]...

Try `wget --help' for more options.
tar: can't open '/opt/root/EasyRSA-3.0.4.tgz': No such file or directory
mv: can't rename '/opt/root/EasyRSA-3.0.4': No such file or directory
chown: /opt/etc/openvpn/easy-rsa/: No such file or directory
1ovpn.sh: line 199: cd: /opt/etc/openvpn/easy-rsa/: No such file or directory
cp: can't stat 'vars.example': No such file or directory
1ovpn.sh: line 230: ./easyrsa: No such file or directory
Cannot write random bytes:
30507277:error:12000079:random number generator:RAND_write_file:Cannot open file                                                                                        :crypto/rand/randfile.c:240:Filename=/opt/etc/openvpn/easy-rsa/pki/.rnd
1ovpn.sh: line 232: ./easyrsa: No such file or directory
1ovpn.sh: line 233: ./easyrsa: No such file or directory
1ovpn.sh: line 234: ./easyrsa: No such file or directory
1ovpn.sh: line 237: ./easyrsa: No such file or directory
1ovpn.sh: line 238: ./easyrsa: No such file or directory
2024-02-08 14:05:56 DEPRECATED OPTION: The option --secret is deprecated.
2024-02-08 14:05:56 WARNING: Using --genkey --secret filename is DEPRECATED.  Us                                                                                        e --genkey secret filename instead.
cat: can't open 'pki/ca.crt': No such file or directory
cat: can't open 'pki/issued/server.crt': No such file or directory
cat: can't open 'pki/private/server.key': No such file or directory
cat: can't open 'pki/dh.pem': No such file or directory
cat: can't open '/opt/etc/openvpn/easy-rsa/pki/ca.crt': No such file or director                                                                                        y
cat: can't open '/opt/etc/openvpn/easy-rsa/pki/issued/client.crt': No such file                                                                                         or directory
cat: can't open '/opt/etc/openvpn/easy-rsa/pki/private/client.key': No such file                                                                                         or directory

Finished!
 

Сделай "opkg list-installed" и выложи сюда. Возможно у тебя отсутствует кое-какой пакет, а именно "wget-ssl". Этот пакет позволяет скачивать файлы по ссылкам с протоколом "https". А ссылка там как раз такая

Edited by Pure Gen
Link to comment
Share on other sites

День добрый, дамы и господа. И вновь легкий допил скрипта. Учтена проблема в комментарии выше от "Demos". Скрипт допилен при учете мощностей роутера. Ранее проводил эксперименты с довольно большими для него цифрами и сделал оптимальную конфигурацию. В скрипте добавил блоки для пользователей с названием "UNCOMMENT WHAT YOU NEED". В этих блоках присутствует краткое описание, что к чему. Ваша задача только в них раскомментировать то, что вам нужно и замените под себя значения переменных страны, области, города, организации, почты, подразделения и имени.

#!/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
#This script is being finalized ChaoticSerg and is located on the forum https://forum.keenetic.net/.

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-nossl)

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

IW2=$(opkg list-installed |grep wget-ssl)

if [ -n "$IW2" ]
then
  echo "wget-ssl installed";
else
  opkg install wget-ssl
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=$(route |grep -o -E '192.168.[0-9]{1,3}.0')

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 --batch build-client-full $CLIENT
        # 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 211.11.112.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"
        echo "   4) Quad9"
        echo "   5) Quad9 (Secured w/ECS)"
        echo "   6) Cloudflare"
        read -p "DNS [1-6]: " -e -i 1 DNS
        echo ""
    fi
        echo "RSA key size 6144 or 4096 ?"
    echo "1) 6144"
    echo "2) 4096"
    read -p "RSA key size (1 or 2): " -e -i 1 RSA_KEY_SIZE
    echo ""
    if [ "$RSA_KEY_SIZE" = 2 ]; then
    RSA_KEY_SIZE=4096
    else
        RSA_KEY_SIZE=6144
    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" = 6144 ]; then
    cp vars.example vars
    echo "set_var EASYRSA_REQ_COUNTRY "FR"" >> vars
    echo "set_var EASYRSA_REQ_PROVINCE "My_Province"" >> vars
    echo "set_var EASYRSA_REQ_CITY "My_City"" >> vars
    echo "set_var EASYRSA_REQ_ORG "My_Corporation"" >> vars
    echo "set_var EASYRSA_REQ_EMAIL "my@email.com"" >> vars
    echo "set_var EASYRSA_REQ_OU "My_Organization_Unit"" >> vars
    echo "set_var EASYRSA_REQ_CN "My_Name"" >> vars
    echo "set_var EASYRSA_KEY_SIZE 6144" >> vars
    echo "set_var EASYRSA_ALGO rsa" >> vars
    echo "set_var EASYRSA_CA_EXPIRE 3650" >> vars
    echo "set_var EASYRSA_CERT_EXPIRE 3650" >> vars
    echo "set_var EASYRSA_DIGEST "sha512"" >> vars
    else
        cp vars.example vars
        echo "set_var EASYRSA_REQ_COUNTRY "FR"" >> vars
        echo "set_var EASYRSA_REQ_PROVINCE "My_Province"" >> vars
        echo "set_var EASYRSA_REQ_CITY "My_City"" >> vars
        echo "set_var EASYRSA_REQ_ORG "My_Corporation"" >> vars
        echo "set_var EASYRSA_REQ_EMAIL "my@email.com"" >> vars
        echo "set_var EASYRSA_REQ_OU "My_Organization_Unit"" >> vars
        echo "set_var EASYRSA_REQ_CN "My_Name"" >> vars
        echo "set_var EASYRSA_KEY_SIZE 4096" >> vars
        echo "set_var EASYRSA_ALGO rsa" >> vars
        echo "set_var EASYRSA_CA_EXPIRE 3650" >> vars
        echo "set_var EASYRSA_CERT_EXPIRE 3650" >> vars
        echo "set_var EASYRSA_DIGEST "sha384"" >> vars
    fi
    # Create the PKI, set up the CA, the DH params and the server + client certificates
    ./easyrsa init-pki
    openssl rand -writerand .rnd && cp .rnd .rand && mv .rnd pki/ && mv .rand pki/
    ./easyrsa --batch build-ca nopass


### UNCOMMENT WHAT YOU NEED
#----------------------------------------------------
# Uncomment what you need to generate DH-parameter...
    ./easyrsa gen-dh

# ...or this
#   openssl dhparam -out dh.pem 4096
#----------------------------------------------------
### UNCOMMENT WHAT YOU NEED


    mv dh.pem pki/
    ./easyrsa build-server-full server nopass
#   echo "You will be asked for the client password below"


### UNCOMMENT WHAT YOU NEED
#----------------------------------------------------
# Generate client without password
#   ./easyrsa build-client-full $CLIENT nopass

# Generate client with password
    ./easyrsa --batch build-client-full "$CLIENT"
#----------------------------------------------------
### UNCOMMENT WHAT YOU NEED


    ./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
    echo "keepalive 10 120" >> /opt/etc/openvpn/openvpn.conf

if [ "$VPN_GW" = y ]; then
    echo "push \"redirect-gateway def1 bypass-dhcp\"" >> /opt/etc/openvpn/openvpn.conf
fi
    # Route
        route | grep -o -E '192.168.[0-9]{1,3}\.0' | while read line; do
        echo "push \"route $line\"" >> /opt/etc/openvpn/openvpn.conf
        done

    # 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
        ;;
        4)
        echo 'push "dhcp-option DNS 9.9.9.9"' >> /opt/etc/openvpn/openvpn.conf
        echo 'push "dhcp-option DNS 149.112.112.112"' >> /opt/etc/openvpn/openvpn.conf
        ;;
        5)
        echo 'push "dhcp-option DNS 9.9.9.11"' >> /opt/etc/openvpn/openvpn.conf
        echo 'push "dhcp-option DNS 149.112.112.11"' >> /opt/etc/openvpn/openvpn.conf
        ;;
        6)
        echo 'push "dhcp-option DNS 1.1.1.1"' >> /opt/etc/openvpn/openvpn.conf
        echo 'push "dhcp-option DNS 1.0.0.1"' >> /opt/etc/openvpn/openvpn.conf
        ;;
esac


    echo "cipher AES-256-GCM" >> /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 "auth-nocache" >> /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-GCM" >> /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!"
fi

 

Edited by Pure Gen
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...