Различия

Показаны различия между двумя версиями страницы.


wiki:articles:openvpn [17/03/2020 12:41] (текущий) – создано - внешнее изменение 127.0.0.1
Строка 1: Строка 1:
 +^   ** OpenVPN **   ^
 +\\
 +Так как в SlackWare 14.1 //OpenVPN//  уже установлен (если нет, просто качаем и ставим :), то сразу переходим к его настройке:
 +
 +   * eth0(22.22.22.22) - //внешний интерфейс и IP-адрес сервера//\\
 +   * eth1(192.168.10.250) - //внутренний интерфейс и IP-адрес сервера//\\
 +   * tap0(192.168.111.1) - //VPN интерфейс и IP-адрес сервера//\\
 +   * 192.168.10.244 - //внутренний DNS сервер//
 +
 +=====Генерация сертификатов и ключей=====
 +
 +Если у Вас нет необходимости создавать свой центр сертификации, и вы будете генерировать ключи только для //OpenVPN//, можно воспользоваться набором скриптов //Easy RSA//, который поставлялся в комплекте с //OpenVPN// до версий 2.2.*. И они находились в директории с документацией: ///usr/share/doc/openvpn-версия/easy-rsa.// Теперь этот набор поставляется отдельно и на день написания статьи, дя OpenVPN-2.3.2 я скачал этот набор с https://github.com/OpenVPN/easy-rsa/archive/release/2.x.zip. После распаковки весь каталог //easy-rsa// я положил в привычное место, а именно в ///usr/share/doc/openvpn-2.3.2//.
 +
 +Для генерации ключей перейдите в каталог ///usr/share/doc/openvpn-2.3.2/easy-rsa/2.0///
 +<code>
 + # cd /usr/share/doc/openvpn-2.3.2/easy-rsa/2.0
 +</code>
 +
 +Теперь отредактируйте файл //vars//
 +<code>
 + export EASY_RSA="`pwd`"
 + export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`
 + export KEY_DIR=/etc/openvpn/keys
 + echo NOTE: when you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
 + export KEY_SIZE=1024
 + export KEY_COUNTRY=RU
 + export KEY_PROVINCE=RU
 + export KEY_CITY=MOSCOW
 + export KEY_ORG="MYORG"
 + export KEY_EMAIL="it@myorg.ru"
 +</code> 
 +
 +Этот файл предназначен для установок переменных среды окружения, перед генерацией ключей. Запускаем  его при помощи точки: 
 +<code>
 + # . ./vars
 + NOTE: when you run ./clean-all, I will be doing a rm -rf on /etc/openvpn/keys
 + #
 +</code> 
 +
 +Теперь запускаем программу очистки (на всякий пожарный, т.е. очистит весь каталог с ключами). 
 +<code>
 + # ./clean-all
 + #
 +</code> 
 +
 +Осталось запустить процесс генерации ключей и сертификата СА. 
 +<code>
 + # ./build-ca
 + Generating a 1024 bit RSA private key
 + ..................++++++
 + ......................................................++++++
 + writing new private key to 'ca.key'
 + -----
 + You are about to be asked to enter information that will be incorporated
 + into your certificate request.
 + What you are about to enter is what is called a Distinguished Name or a DN.
 + There are quite a few fields but you can leave some blank
 + For some fields there will be a default value,
 + If you enter '.', the field will be left blank.
 + -----
 + Country Name (2 letter code) [RU]:
 + State or Province Name (full name) [RU]:
 + Locality Name (eg, city) [MOSCOW]:
 + Organization Name (eg, company) [MYORG]:
 + Organizational Unit Name (eg, section) []:myorg
 + Common Name (eg, your name or your server's hostname) []:vpnsrv.myorg
 + Email Address [it@myorg.ru]:
 + #
 +</code> 
 +
 +Некоторые поля заполняются автоматически, ведь не зря мы изменяли содержимое файла //vars//. Хотя ответы по умолчанию можно было поместить в конфигурационный файл программы //openssl-1.0.0.cnf//.
 + 
 +В директории ///etc/openvpn// появилась директория //keys//, в которой находятся файлы сертификата и ключ. 
 +Теперь следует создать ключ и сертификат для сервера. 
 +<code>
 + # ./build-key-server vpnsrv.myorg
 + Generating a 1024 bit RSA private key
 + ...++++++
 + ..++++++
 + writing new private key to 'vpnsrv.myorg.key'
 + -----
 + You are about to be asked to enter information that will be incorporated
 + into your certificate request.
 + What you are about to enter is what is called a Distinguished Name or a DN.
 + There are quite a few fields but you can leave some blank
 + For some fields there will be a default value,
 + If you enter '.', the field will be left blank.
 + -----
 + Country Name (2 letter code) [RU]:
 + State or Province Name (full name) [RU]:
 + Locality Name (eg, city) [MOSCOW]:
 + Organization Name (eg, company) [MYORG]:
 + Organizational Unit Name (eg, section) []:myorg
 + Common Name (eg, your name or your server's hostname) []:vpnsrv.myorg
 + Email Address [it@myorg.ru]: 
 + 
 + Please enter the following 'extra' attributes
 + to be sent with your certificate request
 + A challenge password []:password
 + An optional company name []:
 + Using configuration from /usr/share/doc/openvpn-2.3.2/easy-rsa/2.0/openssl-1.0.0.cnf
 + Check that the request matches the signature
 + Signature ok
 + The Subject's Distinguished Name is as follows 
 + 
 + countryName           :PRINTABLE:'RU'
 + stateOrProvinceName   :PRINTABLE:'RU'
 + localityName          :PRINTABLE:'MOSCOW'
 + organizationName      :PRINTABLE:'MYORG'
 + organizationalUnitName:PRINTABLE:'myorg'
 + commonName            :PRINTABLE:'vpnsrv.myorg'
 + emailAddress          :IA5STRING:'it@myorg.ru'
 + Certificate is to be certified until Sep 25 14:31:19 2024 GMT (3650 days)
 + Sign the certificate? [y/n]:y
 + 
 + 1 out of 1 certificate requests certified, commit? [y/n]y
 + Write out database with 1 new entries
 + Data Base Updated
 + #
 +</code> 
 +
 +Сгенерируем сертификаты и ключи для клиентской машины. (для каждой новой машины лучше генерировать сертификат по ее имени)
 +<code>
 + # ./build-key mashina_01
 + Generating a 1024 bit RSA private key
 + .......++++++
 + .............................................++++++
 + writing new private key to 'mashina_01.key'
 + -----
 + You are about to be asked to enter information that will be incorporated
 + into your certificate request.
 + What you are about to enter is what is called a Distinguished Name or a DN.
 + There are quite a few fields but you can leave some blank
 + For some fields there will be a default value,
 + If you enter '.', the field will be left blank.
 + -----
 + Country Name (2 letter code) [RU]:
 + State or Province Name (full name) [RU]:
 + Locality Name (eg, city) [MOSCOW]:
 + Organization Name (eg, company) [MYORG]:
 + Organizational Unit Name (eg, section) []: myorg
 + Common Name (eg, your name or your server's hostname) []:mashina_01
 + Email Address [it@myorg.ru]:user@yandex.ru 
 + 
 + Please enter the following 'extra' attributes
 + to be sent with your certificate request
 + A challenge password []:password
 + An optional company name []:
 + Using configuration from /usr/share/doc/openvpn-2.3.2/easy-rsa/2.0/openssl-1.0.0.cnf
 + DEBUG[load_index]: unique_subject = "yes"
 + Check that the request matches the signature
 + Signature ok
 + The Subject's Distinguished Name is as follows
 + countryName           :PRINTABLE:'RU'
 + stateOrProvinceName   :PRINTABLE:'RU'
 + localityName          :PRINTABLE:'MOSCOW'
 + organizationName      :PRINTABLE:'MYORG'
 + commonName            :PRINTABLE:'mashina_01'
 + emailAddress          :IA5STRING:'user@yandex.ru'
 + Certificate is to be certified until Sep 25 14:39:59 2024 GMT (3650 days)
 + Sign the certificate? [y/n]:
 + 
 + 1 out of 1 certificate requests certified, commit? [y/n]y
 + Write out database with 1 new entries
 + Data Base Updated
 + #
 +</code>
 +
 +В заключении следует создать //Diffie Hellman// параметры. 
 +<code>
 + # ./build-dh
 + Generating DH parameters, 1024 bit long safe prime, generator 2
 + This is going to take a long time
 + ..+.......................................................................+...+
 + .....+.....+...................................................................
 + ............................+..................+.+...........+.................
 + ...+.....++*++*++*
 + #
 +</code>
 +
 +И создать секретный ключ.
 +<code>
 + # openvpn --genkey --secret /etc/openvpn/keys/ta.key
 +</code>
 +
 +Посмотрим содержимое директории ///etc/openvpn/keys//:
 +<code> 
 + # ls /etc/openvpn/keys/
 + 01.pem                ca.key               index.txt.old
 + 02.pem                dh1024.pem           serial      
 + 03.pem                mashina_01.crt       serial.old
 + vpnsrv.myorg.crt      mashina_01.csr       ta.key 
 + vpnsrv.myorg.csr      mashina_01.key       
 + vpnsrv.myorg.key      index.txt            
 + ca.crt                index.txt.attr
 +                       index.txt.attr.old
 + #
 +</code>
 +Теперь необходимо разобраться какие файлы куда помещать.
 +
 +^   ** Файл **  ^   ** Машина **     ** Назначение **    ^   ** Доступ **   ^
 +|ca.crt   |Сервер и клиенты   |Сертификат корневого СА   |Публичный    |
 +|ca.key   |Только на сервере   |Необходим для подписи других сертификатов   |Секретный   |
 +|dh1024.pem   |Только на сервере   |Diffie Hellman параметры   |Публичный   |
 +|vpnsrv.myorg.crt   |Только на сервере   |Сертификат сервера   |Публичный   |
 +|vpnsrv.myorg.key   |Только на сервере   |Ключ сервера   |Секретный   |
 +|mashina_01.crt   |Только на клиенте   |Сертификат клиента   |Публичный   |
 +|mashina_01.key   |Только на клиенте   |Ключ клиента   |Секретный   |
 +|ta.key   |Сервер и клиенты   |Ключ аутентификации   |Секретный   |
 +
 +Файлы *.csr можно удалить. 
 +
 +Скопируйте все необходимые файлы на клиенты в директорию ///etc/openvpn/keys//. Для клиента //mashina_01//, я скопировал четыре файла: //ca.crt, ta.key, mashina_01.crt// и //mashina_01.key//.
 + 
 +На всякий пожарный проверьте действительность создаваемых сертификатов. 
 +<code>
 + #openssl verify -CApath /etc/openvpn/keys -CAfile ca.crt -purpose sslclient mashina_01.crt
 +</code>
 +Для сервера следует изменить //sslclient// на //sslserver//.
 + 
 +Теперь настраиваем сервер. Для этого создаём файл ///etc/openvpn/openvpn.conf// :
 +<code>
 + cd /etc/openvpn
 + local 22.22.22.22 # внешний IP-адрес
 + proto udp # протокол
 + port 1194 # порт
 + comp-lzo  # компрессия
 + verb 3    # уровень логов 
 + log-append /var/log/openvpn.log  # где логии лежат
 + daemon
 + dev tap0   # интерфейс
 + persist-tun
 + persist-key
 + mode server
 + tls-server
 + ifconfig-pool 192.168.111.2 192.168.111.52 # устанавливаем диапазон выдаваемых адресов
 + ifconfig 192.168.111.1 255.255.255.0 192.168.10.250
 + client-to-client
 + push "route 192.168.10.0 255.255.255.0 192.168.111.1"
 + push "redirect-gateway"
 + push "dhcp-option DNS 192.168.111.1"
 + push "dhcp-option DNS 192.168.10.244"
 + cipher DES-EDE3-CBC
 + ca /etc/openvpn/keys/ca.crt
 + dh /etc/openvpn/keys/dh1024.pem
 + cert /etc/openvpn/keys/vpnserv.myorg.crt
 + key /etc/openvpn/keys/vpnserv.myorg.key
 + tls-auth /etc/openvpn/keys/ta.key 0 # 0 – означает сервер, 1 - клиент
 + user nobody  # понижаем права 
 + group nobody
 + keepalive 10 600 # опрашиваем каждые 10 сек., если в течении 10 мин отклика нет – отрубаем!
 + #duplicate-cn # расскомментарить, если один сертификат на всех пользователей.
 +</code>
 +
 +Настраиваем //iptables// :
 +<code>
 + LAN_IP="192.168.10.250"
 + LAN_IP_RANGE="192.168.10.0/24"
 + LAN_IFACE="eth0"
 + 
 + VPN_IP="192.168.111.1"
 + VPN_IP_RANGE="192.168.111.0/24"
 + VPN_IFACE="tap0"
 + 
 + iptables -A INPUT -p udp --dport 1194 -j ACCEPT
 + iptables -A INPUT -i tap+ -j ACCEPT
 + iptables -A FORWARD -s 192.168.111.0/24 -d 0.0.0.0/0 -j ACCEPT
 + iptables -t nat -A POSTROUTING -s $VPN_IP_RANGE -o $LAN_IFACE -j MASQUERADE 
 +</code>
 +
 +Создадим стартовый скрипт ///etc/rc.d/rc.openvpn//. Не забываем, что он должен быть исполняемым.\\
 +Пример стартового скрипта можно найти в документации к //OpenVPN//. Но на всякий случай, ниже показан файл, который я использую на своей машине. 
 +<code>
 + #!/bin/sh
 + #
 + # openvpn       This shell script takes care of starting and stopping
 + #               openvpn on RedHat or other chkconfig-based system.
 + #
 + # description: OpenVPN is a robust and highly flexible tunneling application that
 + #              uses all of the encryption, authentication, and certification features
 + #              of the OpenSSL library to securely tunnel IP networks over a single
 + #              UDP port.
 + #
 + # Contributed to the OpenVPN project by
 + # Douglas Keller <doug@voidstar.dyndns.org>
 + # 2002.05.15
 + #
 + # To install:
 + #   copy this file to /etc/rc.d/rc.openvpn
 + #   and add something like this to your file
 + #   /etc/rc.d/rc.M or /etc/rc.d/rc.local
 + #   #  Start the OpenVPN daemon:
 + #   if [ -x /etc/rc.d/rc.openvpn ]; then
 + #     . /etc/rc.d/rc.openvpn start
 + #   fi
 + #   make .conf or .sh files in /etc/openvpn (see below)
 + # To uninstall:
 + #   run: chmod -x /etc/rc.d/rc.openvpn
 + #
 + # Author's Notes:
 + #
 + # I have created an /etc/init.d init script and enhanced openvpn.spec to
 + # automatically register the init script.  Once the RPM is installed you
 + # can start and stop OpenVPN with "service openvpn start" and "service
 + # openvpn stop".
 + #
 + # The init script does the following:
 + #
 + # - Starts an openvpn process for each .conf file it finds in
 + #   /etc/openvpn.
 + #
 + # - If /etc/openvpn/xxx.sh exists for a xxx.conf file then it executes
 + #   it before starting openvpn (useful for doing openvpn --mktun...).
 + #
 + # - In addition to start/stop you can do:
 + #
 + #   /etc/rc.d/rc.openvpn reload - SIGHUP
 + #   /etc/rc.d/rc.openvpn reopen - SIGUSR1
 + #   /etc/rc.d/rc.openvpn status - SIGUSR2
 + #
 + # Modifications:
 + #
 + # 2003.05.02
 + #   * Changed == to = for sh compliance (Bishop Clark).
 + #   * If condrestart|reload|reopen|status, check that we were
 + #     actually started (James Yonan).
 + #   * Added lock, piddir, and work variables (James Yonan).
 + #   * If start is attempted twice, without an intervening stop, or
 + #     if start is attempted when previous start was not properly
 + #     shut down, then kill any previously started processes, before
 + #     commencing new start operation (James Yonan).
 + #   * Do a better job of flagging errors on start, and properly
 + #     returning success or failure status to caller (James Yonan).
 + #
 + # 2005.04.04
 + #   * Added openvpn-startup and openvpn-shutdown script calls
 + #     (James Yonan).
 + #
 + # 2005.12.13
 + #   * Asssssign openvpn variable directly for package for Slackware Linux
 + # 
 + 
 + # Location of openvpn binary
 + openvpn="/usr/sbin/openvpn" 
 + 
 + # Lockfile
 + lock="/var/lock/subsys/openvpn" 
 + 
 + # PID directory
 + piddir="/var/run/openvpn"
 + 
 + # Our working directory
 + work=/etc/openvpn
 + 
 + # Check that binary exists
 + if ! [ -f  $openvpn ]
 + then
 +   echo "openvpn binary not found"
 +   exit 0
 + fi
 + 
 + # See how we were called.
 + case "$1" in
 +   start)
 +         echo -n $"Starting openvpn: "
 + 
 +         /sbin/modprobe tun >/dev/null 2>&1
 + 
 +         # From a security perspective, I think it makes
 +         # sense to remove this, and have users who need
 +         # it explictly enable in their --up scripts or
 +         # firewall setups. 
 + 
 +         #echo 1 > /proc/sys/net/ipv4/ip_forward 
 + 
 +         # Run startup script, if defined
 +         if [ -f $work/openvpn-startup ]; then
 +             $work/openvpn-startup
 +         fi
 + 
 +         if [ ! -d  $piddir ]; then
 +             mkdir $piddir
 +        fi
 + 
 +         if [ -f $lock ]; then
 +             # we were not shut down correctly
 +             for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
 +               if [ -s $pidf ]; then
 +                 kill `cat $pidf` >/dev/null 2>&1
 +               fi
 +               rm -f $pidf
 +             done
 +             rm -f $lock
 +             sleep 2
 +         fi
 + 
 +         rm -f $piddir/*.pid
 +         cd $work
 + 
 +         # Start every .conf in $work and run .sh if exists
 +         errors=0
 +         successes=0
 +         for c in `/bin/ls *.conf 2>/dev/null`; do
 +             bn=${c%%.conf}
 +             if [ -f "$bn.sh" ]; then
 +                 . $bn.sh
 +             fi
 +             rm -f $piddir/$bn.pid
 +             $openvpn --daemon --writepid $piddir/$bn.pid --config $c --cd $work
 +             if [ $? = 0 ]; then
 +                 successes=1
 +             else
 +                 errors=1
 +             fi
 +         done 
 + 
 +         if [ $errors = 1 ]; then
 +             echo faliure
 +         else
 +             echo success
 +         fi
 + 
 +         if [ $successes = 1 ]; then
 +             touch $lock
 +         fi
 +         ;;
 +   stop)
 +         echo -n $"Shutting down openvpn: "
 +         for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
 +           if [ -s $pidf ]; then
 +             kill `cat $pidf` >/dev/null 2>&1
 +           fi
 +           rm -f $pidf
 +         done
 + 
 +         # Run shutdown script, if defined
 +         if [ -f $work/openvpn-shutdown ]; then
 +             $work/openvpn-shutdown
 +         fi
 + 
 +         echo success
 +         rm -f $lock
 +         ;;
 +   restart)
 +         $0 stop
 +         sleep 2
 +         $0 start
 +         ;;
 +   reload)
 +         if [ -f $lock ]; then
 +             for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
 +                 if [ -s $pidf ]; then
 +                     kill -HUP `cat $pidf` >/dev/null 2>&1
 +                 fi
 +             done
 +         else
 +             echo "openvpn: service not started"
 +             exit 1
 +         fi
 +         ;;
 +   reopen)
 +         if [ -f $lock ]; then
 +             for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
 +                 if [ -s $pidf ]; then
 +                     kill -USR1 `cat $pidf` >/dev/null 2>&1
 +                 fi
 +             done
 +         else
 +             echo "openvpn: service not started"
 +             exit 1
 +         fi
 +         ;;
 +   condrestart)
 +         if [ -f $lock ]; then
 +             $0 stop
 +             # avoid race
 +             sleep 2
 +             $0 start
 +         fi
 +         ;;
 +   status)
 +         if [ -f $lock ]; then
 +             for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
 +                 if [ -s $pidf ]; then
 +                     kill -USR2 `cat $pidf` >/dev/null 2>&1
 +                 fi
 +             done
 +             echo "Status written to /var/log/messages"
 +         else
 +             echo "openvpn: service not started"
 +             exit 1
 +         fi
 +         ;;
 +   *)
 +         echo "Usage: openvpn {start|stop|restart|condrestart|reload|reopen|status}"
 +         exit 1
 +         ;;
 + esac
 + exit 0
 +</code>
 +
 +Если необходим автоматический старт при запуске системы вручную добавьте в скрипт ///etc/rc.d/rc.M// следующие строки сразу после старта сети: 
 +<code>
 + # Open VPN
 + if [ -x /etc/rc.d/rc.openvpn ]; then
 +     /etc/rc.d/rc.openvpn start
 + fi
 +</code>
 +
 +И сразу же запустим «в ручную»:
 +<code>
 + # /etc/rc.d/rc.openvpn start
 +</code>
 +
 +
 +
 +===== Настраиваем клиента (Windows) =====
 +
 +Скачиваем [[https://openvpn.net/community-downloads/ | ТУТ]] файл для нужной платформы и устанавливаем на клиенте.\\
 +Устанавливаем в каталог, например, //C:\OpenVPN// , создаем там подкаталог //key//  и копируем туда наши клиентские ключи : //ca.crt, ta.key, mashina_01.crt// и //mashina_01.key//.
 +
 +В каталоге //C:\OpenVPN\config// создаём файл //client.ovpn// с содержимым:
 +<code>
 + client
 + dev tap
 + proto udp
 + remote 22.22.22.22 1194
 + resolv-retry infinite
 + nobind
 + persist-key
 + persist-tun
 + ca C:\\OpenVPN\\key\\ca.crt
 + cert C:\\OpenVPN\\key\\mashina_01.crt
 + key C:\\OpenVPN\\key\\mashina_01.key
 + tls-auth C:\\OpenVPN\\key\\ta.key 1
 + cipher DES-EDE3-CBC
 + comp-lzo
 + verb 3
 + mute 5
 + ping 10
 + mtu-test
 + tun-mtu 1500
 + tun-mtu-extra 32
 + mssfix 1450
 + pull
 + route-method exe
 + explicit-exit-notify 10
 + show-net-up
 +</code>
 +
 +И соединяемся…  - правый клик на иконке в системном лотке - //connect// \\
 +Всё, дальше работаем как с локалкой.
 +
 +===== Настраиваем клиента (Linux Slackware) =====
 +
 +Скачиваем [[http://slackfind.net/ru/packages/search/?name=kvpnc+&distversion= | KVpnc (клиент VPN под KDE)]] и устанавливаем.\\
 +В каталог ///etc/openvpn/keys// скидываем наши клиентские ключи и сертификаты : //ca.crt, ta.key, mashina_01.crt// и //mashina_01.key//.\\
 +И создаем файл ///etc/openvpn/openvpn.conf// со следующим содержимым:
 +<code>
 + client
 + dev tap0
 + proto udp
 + remote 22.22.22.22 1194
 + resolv-retry infinite
 + nobind
 + persist-key
 + persist-tun
 + ca /etc/openvpn/keys/ca.crt
 + cert /etc/openvpn/keys/mashina_01.crt
 + key /etc/openvpn/keys/mashina_01.key
 + tls-auth /etc/openvpn/keys/ta.key 1
 + cipher DES-EDE3-CBC
 + comp-lzo
 + verb 3
 + mute 5
 + ping 10
 + mtu-test
 + tun-mtu 1500
 + tun-mtu-extra 32
 + mssfix 1450
 + pull
 + route-method exe
 + explicit-exit-notify 10
 +</code>
 +
 +Запускаем //KVpnc// и импортируем наш файл //openvpn.conf//\\
 +{{http://slackware.su/forum/files/ovpn/Kvpnc-1.png}}
 +
 +Указываем его место расположение \\
 +{{http://slackware.su/forum/files/ovpn/Kvpnc-2.png}}
 +
 +И получив сообщение об успешном импорте, соединяемся нажав на кнопку //<<Connect>>//.\\
 +{{http://slackware.su/forum/files/ovpn/Kvpnc-3.png}}
 +
 +Если все верно, должно пройти соединение и дальше можно работать как в локальной сети.\\
 +Если же соединение не получилось, смотрим ошибки, исправляем и пробуем снова. 
 +
 +В принципе, использование GUI - это дело вкуса. На клиенте достаточно создать и запустить /etc/rc.d/rc.openvpn по аналогии сервера и все будет работать! :)
 +
 +===== Аутентификация по логину и паролю =====
 +
 +Для аутентификации будем использовать файл с хешироваными по md5 паролями.
 +
 +Сначала создадим каталог для скрипта авторизации:
 +<code>
 + # mkdir /etc/openvpn/auth
 +</code>
 +
 +Затем, в этом каталоге, создадим файл //auth-static-file.pl// со содержимым:
 +<code>
 +#!/usr/bin/perl
 +
 +#
 +# $Id$
 +#
 +# Кравчук Сергей, <alfss.obsd@gmail.com>
 +#
 +
 +use strict;
 +use warnings;
 +use Digest::MD5  qw(md5 md5_hex md5_base64);
 +use version; our $VERSION = qv(0.01);
 +
 +my $password_file = '/etc/openvpn/auth/user_password.txt';
 +my $ARG = undef;
 +if ( $ARG = shift @ARGV ) {
 +    if ( !open( UPFILE, "<$ARG" ) ) {
 +        print "Could not open username/password tmp file: $ARG\n";
 +        exit 1;
 +    }
 +}
 +else {
 +    print "No username/password file specified on command line\n";
 +    exit 1;
 +}
 +
 +my $username = <UPFILE>;
 +my $password = <UPFILE>;
 +
 +if ( !$username || !$password ) {
 +    print "Username/password not found in tmp file: $ARG\n";
 +    exit 1;
 +}
 +
 +chomp $username;
 +chomp $password;
 +
 +close(UPFILE);
 +
 +if ( !open( USER_PASSWORD, "<$password_file" ) ) {
 +    print "Could not open username/password db file: $ARG\n";
 +    exit 1;
 +}
 +foreach my $line (<USER_PASSWORD>) {
 +    chomp($line);
 +    my ( $read_user, $read_password ) = split(/:/, $line);
 +    if ( $read_user eq $username ) {
 +        my $hex_password = md5_hex $password;
 +        if ( $hex_password eq $read_password) {
 +            close(USER_PASSWORD);
 +            exit 0;
 +        }
 +        exit 1;
 +    }
 +}
 +
 +close(USER_PASSWORD);
 +
 +exit 1;
 +</code>
 +
 +Далее хешируем пароли для пользователей:\\
 +Graf - MySuperPassword\\
 +v_pupkin - Vasiliy123
 +
 +<code>
 +# echo -n 'MySuperPassword' | md5sum
 +b742afa4446f65e348ad07d05f154cc3
 +
 +# echo -n 'Vasiliy123' | md5sum
 +4799f3cc499f7257dd4091c71d9333cb
 +</code>
 +
 +и прописываем их в файл ///etc/openvpn/auth/user_password.txt//
 +<code>
 +Graf:b742afa4446f65e348ad07d05f154cc3
 +v_pupkin:4799f3cc499f7257dd4091c71d9333cb
 +
 +</code>
 +**Последний перевод строки обязателен!**
 +
 +Ну, и файл ///etc/openvpn.conf// приводим к следующему виду:
 +<code>
 +cd/etc/openvpn                                              
 +local 22.22.22.22
 +proto udp
 +port 1194                                           
 +comp-lzo                                                
 +verb 3
 +status /var/log/openvpn/openvpn-status.log                
 +log /var/log/openvpn/openvpn.log                            
 +tmp-dir /tmp
 +dev tap0
 +persist-key                                                
 +persist-tun                                                
 +mode server    
 +tls-server                                                
 +tls-timeout 120                                    
 +ifconfig-pool 192.168.111.2 192.168.111.52
 +ifconfig 192.168.111.1 255.255.255.0  192.168.10.250
 +push "route 192.168.10.0 255.255.255.0 192.168.111.1 192.168.10.250"
 +ca /etc/openvpn/keys/ca.crt                                 
 +dh /etc/openvpn/keys/dh1024.pem                 
 +cert /etc/openvpn/keys/vpnserv.myorg.crt           
 +key /etc/openvpn/keys/vpnserv.myorg.key            
 +tls-auth /etc/openvpn/keys/ta.key 0
 +client-cert-not-required
 +cipher DES-EDE3-CBC
 +keepalive 10 600
 +max-clients 100
 +user nobody
 +group nogroup
 +auth MD5
 +auth-user-pass-verify /etc/openvpn/auth/auth-static-file.pl via-file
 +</code>
 +
 +и файл конфигурации для Linux клиента:
 +<code>
 +auth-user-pass
 +dev tap0
 +proto udp
 +remote 22.22.22.22
 +port 1194
 +client
 +resolv-retry infinite
 +ca /etc/openvpn/keys/ca.crt
 +cert /etc/openvpn/keys/mashina_01.crt
 +key /etc/openvpn/keys/mashina_01.key
 +tls-auth /etc/openvpn/keys/ta.key 1
 +tls-client
 +auth MD5
 +cipher DES-EDE3-CBC
 +ns-cert-type server
 +comp-lzo
 +persist-key
 +persist-tun
 +verb 3
 +mute 5
 +ping 10
 +tun-mtu 1500
 +tun-mtu-extra 32
 +mssfix 1450
 +pull
 +route-method exe
 +explicit-exit-notify 10
 +</code>
 +
 +и файл конфигурации для Windows клиента:
 +<code>
 +auth-user-pass
 +dev tap0
 +proto udp
 +remote 22.22.22.22
 +port 1194
 +client
 +nobind
 +resolv-retry infinite
 +ca "C:\\OpenVPN\\keys\\ca.crt"
 +cert "C:\\OpenVPN\\keys\\mashina_01.crt"
 +key "C:\\OpenVPN\\keys\\mashina_01.key"
 +tls-auth "C:\\OpenVPN\\keys\\ta.key" 1
 +tls-client
 +auth MD5
 +cipher DES-EDE3-CBC
 +ns-cert-type server
 +comp-lzo
 +persist-key
 +persist-tun
 +verb 3
 +mute 5
 +ping 10
 +tun-mtu 1500
 +tun-mtu-extra 32
 +mssfix 1450
 +pull
 +route-method exe
 +explicit-exit-notify 10
 +show-net-up
 +</code>
 +
 +Вот и всё :) \\
 +После ввода логина и пароля, работаем как в обычной локалке.
 +
 +
 +
 +=== Ссылался на.... ====
 +----
 +http://wiki.kryukov.biz/wiki/Openvpn \\
 +http://www.nexttel.kz/asd-ovpn.htm \\
 +http://www.hackedpro.org/index.php?name=Pages&op=page&pid=29&pagenum=1\\
 +http://blog.alfss.net/post/2012/10/26/openvpn-plus-autientifikatsiia-po-loghinu-i-paroliu
 +\\
 +\\
 +[[http://slackware.su/forum/index.php/topic,81.0.html | Обсуждаем на форуме ]]
  
Навигация
Печать/экспорт
QR Code
QR Code wiki:articles:openvpn (generated for current page)