Установка и настройка OpenVPN
Rendering Error in layout Widget/Social: Call to a member function exists() on null. Please enable debug mode for more information.
Меньше
Больше
- Сообщений: 50
- Спасибо получено: 15
11 года 3 мес. назад - 11 года 3 мес. назад #11
от PNV
PNV создал тему: Установка и настройка OpenVPN
Недавно мне понадобилось предоставить доступ интернет-клиенту в корпоративную внутреннюю сеть (интранет). Т.к. граничный маршрутизатор/firewall в конторе обычный D-Link DIR-300, то и речи быть не могло об организации на нём VPN-сервера
. Поэтому решено было организовать VPN-сервер под Linux (ОС CentOS), который находится в корпоративной сети конторы. На сервере поднимаем сервис OpenVPN.
Подключение построено по следующей схеме:
Задача: организовать VPN-туннель через интернет между сервером находящимся за NAT и клиентом, который тоже находится где-то в интернет за NAT.
(Все действия выполняются под пользователем root)
Для решения задачи необходимо настроить серверную (на сервере) и клиентские части (в данном случае на компьютерах пользователей) сервиса OpenVPN.
Серверная часть
1. Скачиваем дистрибутив OpenVPN по ссылке swupdate.openvpn.net/community/releases/openvpn-2.1.4.tar.gz:
wget swupdate.openvpn.net/community/releases/openvpn-2.1.4.tar.gz
и распаковываем архив:
tar -xf openvpn-2.1.4.tar.gz
2. Скачиваем обязательную библиотеку компрессии LZO, необходимую для сжатия потока данных по ссылке www.oberhumer.com/opensource/lzo/download/lzo-2.04.tar.gz:
wget www.oberhumer.com/opensource/lzo/download/lzo-2.04.tar.gz
и распаковываем архив:
tar -xf openvpn-2.1.4.tar.gz
3. Также необходимо установить библиотеку gcc.i386
Устанавливаем её из репозитория:
yum install gcc.i386
Возможно данная библиотека уже может быть установлена, что можно проверить командой yum list |grep gcc.i386. Должно быть что-то вроде:
gcc.i386 4.1.2-48.el5 installed
libgcc.i386 4.1.2-48.el5 installed
Если же данная библиотека не установлена и вы попытаетесь установить непосредственно OpenVPN, то при компиляции выйдет ошибка:
configure: error: no acceptable C compiler found in $PATH
4. Устанавливаем LZO из распакованного архива (см. п.2):
cd .../lzo-2.04
./configure
make
make install
5. Устанавливаем непосредственно сам OpenVPN из распакованной папки (см. п.1):
cd .../openvpn-2.1.4
./configure
make
make install
6. Создаём для удобства все необходимые папки для OpenVPN (при установке данные папки автоматически не создаются) и копируем туда необходимые файлы из распакованного архива (см. п.1):
mkdir /etc/openvpn
cp .../openvpn-2.1.4/easy-rsa/2.0/* /etc/openvpn
mkdir /etc/openvpn/keys - создаём папку для сертификатов и ключей
7. По желанию редактируем файл /etc/openvpn/vars в соответствии с необходимыми параметрами, чтобы каждый раз при генерации ключей не вводить снова одни и те же параметры:
пример файла vars:
# easy-rsa parameter settings
# NOTE: If you installed from an RPM,
# don't edit this file in place in
# /usr/share/openvpn/easy-rsa --
# instead, you should copy the whole
# easy-rsa directory to another location
# (such as /etc/openvpn) so that your
# edits will not be wiped out by a future
# OpenVPN package upgrade.
# This variable should point to
# the top level of the easy-rsa
# tree.
export EASY_RSA="`pwd`"
#
# This variable should point to
# the requested executables
#
export OPENSSL="openssl"
export PKCS11TOOL="pkcs11-tool"
export GREP="grep"
# This variable should point to
# the openssl.cnf file included
# with easy-rsa.
export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`
# Edit this variable to point to
# your soon-to-be-created key
# directory.
#
# WARNING: clean-all will do
# a rm -rf on this directory
# so make sure you define
# it correctly!
export KEY_DIR="$EASY_RSA/keys"
# Issue rm -rf warning
echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
# PKCS11 fixes
export PKCS11_MODULE_PATH="dummy"
export PKCS11_PIN="dummy"
# Increase this to 2048 if you
# are paranoid. This will slow
# down TLS negotiation performance
# as well as the one-time DH parms
# generation process.
export KEY_SIZE=1024
# In how many days should the root CA key expire?
export CA_EXPIRE=3650
# In how many days should certificates expire?
export KEY_EXPIRE=3650
# These are the default values for fields
# which will be placed in the certificate.
# Don't leave any of these fields blank.
export KEY_COUNTRY="US"
export KEY_PROVINCE="CA"
export KEY_CITY="SanFrancisco"
export KEY_ORG="Fort-Funston"
export KEY_EMAIL="Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript."
[asterisk test]# cat ./vars |more
# easy-rsa parameter settings
# NOTE: If you installed from an RPM,
# don't edit this file in place in
# /usr/share/openvpn/easy-rsa --
# instead, you should copy the whole
# easy-rsa directory to another location
# (such as /etc/openvpn) so that your
# edits will not be wiped out by a future
# OpenVPN package upgrade.
# This variable should point to
# the top level of the easy-rsa
# tree.
export EASY_RSA="`pwd`"
#
# This variable should point to
# the requested executables
#
export OPENSSL="openssl"
export PKCS11TOOL="pkcs11-tool"
export GREP="grep"
# This variable should point to
# the openssl.cnf file included
# with easy-rsa.
export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`
# Edit this variable to point to
# your soon-to-be-created key
# directory.
#
# WARNING: clean-all will do
# a rm -rf on this directory
# so make sure you define
# it correctly!
export KEY_DIR="$EASY_RSA/keys"
# Issue rm -rf warning
echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
# PKCS11 fixes
export PKCS11_MODULE_PATH="dummy"
export PKCS11_PIN="dummy"
# Increase this to 2048 if you
# are paranoid. This will slow
# down TLS negotiation performance
# as well as the one-time DH parms
# generation process.
export KEY_SIZE=1024
# In how many days should the root CA key expire?
export CA_EXPIRE=3650
# In how many days should certificates e
xpire?
export KEY_EXPIRE=3650
# These are the default values for fields
# which will be placed in the certificate.
# Don't leave any of these fields blank.
export KEY_COUNTRY="US"
export KEY_PROVINCE="CA"
export KEY_CITY="SanFrancisco"
export KEY_ORG="Fort-Funston"
export KEY_EMAIL="Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript."
8. Экпортируем переменные из файла vars и выполняем удаление всех возможно уже существующих ключей:
cd /etc/openvpn
source ./vars
./clean-all
9. Генерируем закрытый ключ и сертификат сервера сертификации (СA) или назовём по-другому - Удостоверяющего центра, на основе которого будут созданы все остальные ключи (ключ и сертификат для VPN-сервера и ключи и сертификаты для VPN-клиентов)(т.е. используется обычный механизм PKI - public key infrastructure).
./build-ca
[asterisk.gs.int openvpn]# ./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) [US]:RU
State or Province Name (full name) [CA]:SPB
Locality Name (eg, city) [SanFrancisco]:SPB
Organization Name (eg, company) [Fort-Funston]:Organization
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) [Fort-Funston CA]:Asterisk
Name []:Asterisk
Email Address [Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.]:myemail@domain.com
10. Генерируем закрытый ключ и сертификат для сервера:
./build-key-server name
11. Генерируем закрытый ключ и сертификат для клиента:
./build-key client1
[asterisk.gs.int openvpn]# ./build-key client1
Generating a 1024 bit RSA private key
..........++++++
......++++++
writing new private key to 'client1.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) [US]:RU
State or Province Name (full name) [CA]:SPB
Locality Name (eg, city) [SanFrancisco]:SPB
Organization Name (eg, company) [Fort-Funston]:Organization
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) [client1]:
Name []:client1
Email Address [Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.]:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'SPB'
localityName :PRINTABLE:'SPB'
organizationName :PRINTABLE:'Organization'
organizationalUnitName:PRINTABLE:'IT'
commonName :PRINTABLE:'client1'
name :PRINTABLE:'client1'
emailAddress :IA5STRING:'Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.'
Certificate is to be certified until Mar 7 16:40:55 2021 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
12. Генерируем 1024-битный ключ по алгоритму Диффи-Хэллмана, который используется в механизме аутентификации ключей при установлении VPN-туннеля. Данный ключ остаётся на сервере.
Алгори́тм Ди́ффи — Хе́ллмана (англ. Diffie-Hellman, DH) — алгоритм, позволяющий двум сторонам получить общий секретный ключ, используя незащищенный от прослушивания, но защищённый от подмены, канал связи.
./build-dh
[asterisk.gs.int openvpn]# ./build-dh
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
.....................+.....................+.........................+..........+.................................................................................................................................+......................................................................+......+................................................................................................................................................+..................+..........................+............+...............................................+...+...................................................+.....................................................................................+........................................................+.................................+..........+.....+....................................................+........+.+.....................+................................................................................+...............................................................................................+......................................................+.................+.......................................................................................................+................................................................................................................................................................................................................+......................................................................+.........................................++*++*++*
13. (Не обязательно) Генерируем симметричный TLS-ключ для предварительной защиты канала, еще до установленимя VPN-туннеля. Данный ключ является симметричным и должен находится как на сервере, так и на клиенте. Генерируем в папке /etc/openvpn/keys/
openvpn --genkey --secret ./ta.key
Все созданные ключи, сертификаты и запросы серверной части помещаем в папку /etc/openvpn/keys для удобства (в случае если они были сгенерированы в другом месте). Клиентские ключи и сертификаты передаются соответственно защищенным способом на клиентские машины. При этом для каждого сертификата существует свой закрытый ключ и файл запроса на сертификат:
*.key - закрытый ключ;
*.csr - запрос на сертификат;
*.crt - сертификат;
В идеале клиентские закрытые ключи не должны генерироваться на сервере и затем передаваться клиенту, а должны генерироваться на самом клиенте при помощи какого-либо установленного криптопровайдера (в качестве хранилища закрытого ключа используется например реестр, smart-карта или flash-накопитель). Затем создаётся файл запроса сертификата созданный на основе сгенерированного закрытого ключа, который уже отправляется по сети на сервер сертификации (Удостоверяющий центр), где в ответ по сети передаётся сгенерированный сертификат. (т.к. файл запроса сертификата и сам сертификат шифрования сами по себе не составляют ценности без закрытого ключа, то их можно передавать по незащищённым каналам связи).
14. Копируем пример файла конфигурации VPN-сервера server.conf из разархивированной папки (см п.1) в боевую папку /etc/openvpn
cp ...../openvpn-2.1.4/sample-config-files/server.conf /etc/openvpn/server.conf
и редактируем необходимые параметры:
vi /etc/openvpn/server.conf
15. Копируем примеры скриптов для запуска и остановки OpenVPN из разархивированной папки (см п.1) в боевую папку /etc/openvpn и правим их в соответствии со своими предпочтениями:
cp ...../openvpn-2.1.4/sample-config-files/openvpn-startup.sh /etc/openvpn
Пример скрипта openvpn-startup.sh:
cp ...../openvpn-2.1.4/sample-config-files/openvpn-stutdown.sh /etc/openvpn
Пример скрипта openvpn-shutdown.sh:
16. Запускаем OpenVPN-сервер:
/etc/openvpn/openvpn-startup.sh
и проверяем запустился ли сервис:
netstat -luntp |grep openvp
На этом этапе серверная часть закончена и готова к установлению туннеля.
Клиентская часть
Т.к. в моём случае на клиенте (компьютере пользователя) стоит ОС Windows, то рассмотрим пример настройки OpenVPN-клиента именно для Windows.
1. Скачиваем дистрибутив OpenVPN для Windows по ссылке swupdate.openvpn.net/community/releases/...pn-2.1.4-install.exe и устанавливаем с опциями "по умолчанию".
При установке дистрибутива система установит также драйвер виртуального VPN-интерфейса:
2. Копируем пример файла конфигурации клиента client.ovpn из папки c:\Program Files\OpenVPN\sample-config в c:\Program Files\OpenVPN\config и редактируем его:
##############################################
# Sample client-side OpenVPN 2.0 config file #
# for connecting to multi-client server. #
# #
# This configuration can be used by multiple #
# clients, however each client should have #
# its own cert and key files. #
# #
# On Windows, you might want to rename this #
# file so it has a .ovpn extension #
##############################################
# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client
# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel
# if you have more than one. On XP SP2,
# you may need to disable the firewall
# for the TAP adapter.
;dev-node MyTap
# Are we connecting to a TCP or
# UDP server? Use the same setting as
# on the server.
;proto tcp
proto udp
# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
# Прописываем внешний IP-адрес сервера, если он напрямую подключен в интернет (либо адрес файрвола, на
# котором предварительно через NAT/PAT прокинут порт udp 1194 на наш VPN-сервер). Можно указать несколько
# VPN-серверов
remote Х.Х.Х.Х 1194
;remote Y.Y.Y.Y 1194
;remote Z.Z.Z.Z 1195
# Choose a random host from the remote
# list for load-balancing. Otherwise
# try hosts in the order specified.
# Можно включить данную функцию, если используются несколько VPN-серверов, для балансировки нагрузки
# на серверы.
;remote-random
# Keep trying indefinitely to resolve the
# host name of the OpenVPN server. Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite
# Most clients don't need to bind to
# a specific local port number.
# Здесь можно прописать конкретный клиентский локальный порт, на котором будет строиться туннель (полезно,
# если установлен файрвол на компьютере). Если прописано nobind, то локальный порт выбирается автоматически.
nobind
# Downgrade privileges after initialization (non-Windows only)
;user nobody
;group nobody
# Try to preserve some state across restarts.
persist-key
persist-tun
# If you are connecting through an
# HTTP proxy to reach the actual OpenVPN
# server, put the proxy server/IP and
# port number here. See the man page
# if your proxy server requires
# authentication.
;http-proxy-retry # retry on connection failures
;http-proxy [proxy server] [proxy port #]
# Wireless networks often produce a lot
# of duplicate packets. Set this flag
# to silence duplicate packet warnings.
;mute-replay-warnings
# SSL/TLS parms.
# See the server config file for more
# description. It's best to use
# a separate .crt/.key file pair
# for each client. A single ca
# file can be used for all clients.
# Имя файла сертификата CA и файлов сертификата и ключа клиента
ca ca.crt
cert client.crt
key client.key
# Verify server certificate by checking
# that the certicate has the nsCertType
# field set to "server". This is an
# important precaution to protect against
# a potential attack discussed here:
# openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the nsCertType
# field set to "server". The build-key-server
# script in the easy-rsa folder will do this.
ns-cert-type server
# If a tls-auth key is used on the server
# then every client must also have the key.
# предварительного установления защищенного канала с использованием симметричного ключа. На клиенте
# прописывается цифра 1, на сервере - 0. ta.key - имя симметричного ключа.
tls-auth ta.key 1
# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
;cipher x
# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
comp-lzo
# Set log file verbosity.
verb 3
# Silence repeating messages
;mute 20
3. Копируем в папку c:\Program Files\OpenVPN\config\ клиентский ключ client1.key и сертификат client1.crt, сертификат СA.crt (сертификат сервера сертификации), и симметричный ключ ta.key.
4. Запускаем GUI интерфейс из меню "Пуск", либо из c:\Program Files\OpenVPN\bin\openvpn-gui-1.0.3.exe и нажимаем Connect из-под иконки OpenVPN в трее.
Для установления туннеля из командной строки запускаем:
c:\Program Files\OpenVPN\bin\openvpnserv.exe /start
Для автоматического установления VPN-туннеля при загрузке ОС включаем OpenVPN Service в режим автоматического запуска:
Проверяем работоспособность туннеля, маршрутизацию и т.д.
Наслаждаемся результатом!!!
Дополнения.
Для просмотра VPN-соединений на сервере в реальном времени можно зайти по telnet на сервер по порту tcp 8329, если соответствующая строка была прописана в файле server.conf
management 0.0.0.0 8329
и в режиме командной строки смотреть сессии клиентов и если нужно, удалять сессии:
telnet X.X.X.X 8329
Кроме этого можно скачать графическую оболочку для мониторинга VPN-соединений под названием OpenVPN Control по ссылке sourceforge.net/projects/openvpn-control...staller.exe/download
Скриншоты программы OpenVPN Control:

Подключение построено по следующей схеме:
Задача: организовать VPN-туннель через интернет между сервером находящимся за NAT и клиентом, который тоже находится где-то в интернет за NAT.
(Все действия выполняются под пользователем root)
Для решения задачи необходимо настроить серверную (на сервере) и клиентские части (в данном случае на компьютерах пользователей) сервиса OpenVPN.
Серверная часть
1. Скачиваем дистрибутив OpenVPN по ссылке swupdate.openvpn.net/community/releases/openvpn-2.1.4.tar.gz:
wget swupdate.openvpn.net/community/releases/openvpn-2.1.4.tar.gz
и распаковываем архив:
tar -xf openvpn-2.1.4.tar.gz
2. Скачиваем обязательную библиотеку компрессии LZO, необходимую для сжатия потока данных по ссылке www.oberhumer.com/opensource/lzo/download/lzo-2.04.tar.gz:
wget www.oberhumer.com/opensource/lzo/download/lzo-2.04.tar.gz
и распаковываем архив:
tar -xf openvpn-2.1.4.tar.gz
3. Также необходимо установить библиотеку gcc.i386
Устанавливаем её из репозитория:
yum install gcc.i386
Возможно данная библиотека уже может быть установлена, что можно проверить командой yum list |grep gcc.i386. Должно быть что-то вроде:
gcc.i386 4.1.2-48.el5 installed
libgcc.i386 4.1.2-48.el5 installed
Если же данная библиотека не установлена и вы попытаетесь установить непосредственно OpenVPN, то при компиляции выйдет ошибка:
configure: error: no acceptable C compiler found in $PATH
4. Устанавливаем LZO из распакованного архива (см. п.2):
cd .../lzo-2.04
./configure
make
make install
5. Устанавливаем непосредственно сам OpenVPN из распакованной папки (см. п.1):
cd .../openvpn-2.1.4
./configure
make
make install
6. Создаём для удобства все необходимые папки для OpenVPN (при установке данные папки автоматически не создаются) и копируем туда необходимые файлы из распакованного архива (см. п.1):
mkdir /etc/openvpn
cp .../openvpn-2.1.4/easy-rsa/2.0/* /etc/openvpn
mkdir /etc/openvpn/keys - создаём папку для сертификатов и ключей
7. По желанию редактируем файл /etc/openvpn/vars в соответствии с необходимыми параметрами, чтобы каждый раз при генерации ключей не вводить снова одни и те же параметры:
пример файла vars:
ВНИМАНИЕ: Спойлер!
# easy-rsa parameter settings
# NOTE: If you installed from an RPM,
# don't edit this file in place in
# /usr/share/openvpn/easy-rsa --
# instead, you should copy the whole
# easy-rsa directory to another location
# (such as /etc/openvpn) so that your
# edits will not be wiped out by a future
# OpenVPN package upgrade.
# This variable should point to
# the top level of the easy-rsa
# tree.
export EASY_RSA="`pwd`"
#
# This variable should point to
# the requested executables
#
export OPENSSL="openssl"
export PKCS11TOOL="pkcs11-tool"
export GREP="grep"
# This variable should point to
# the openssl.cnf file included
# with easy-rsa.
export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`
# Edit this variable to point to
# your soon-to-be-created key
# directory.
#
# WARNING: clean-all will do
# a rm -rf on this directory
# so make sure you define
# it correctly!
export KEY_DIR="$EASY_RSA/keys"
# Issue rm -rf warning
echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
# PKCS11 fixes
export PKCS11_MODULE_PATH="dummy"
export PKCS11_PIN="dummy"
# Increase this to 2048 if you
# are paranoid. This will slow
# down TLS negotiation performance
# as well as the one-time DH parms
# generation process.
export KEY_SIZE=1024
# In how many days should the root CA key expire?
export CA_EXPIRE=3650
# In how many days should certificates expire?
export KEY_EXPIRE=3650
# These are the default values for fields
# which will be placed in the certificate.
# Don't leave any of these fields blank.
export KEY_COUNTRY="US"
export KEY_PROVINCE="CA"
export KEY_CITY="SanFrancisco"
export KEY_ORG="Fort-Funston"
export KEY_EMAIL="Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript."
[asterisk test]# cat ./vars |more
# easy-rsa parameter settings
# NOTE: If you installed from an RPM,
# don't edit this file in place in
# /usr/share/openvpn/easy-rsa --
# instead, you should copy the whole
# easy-rsa directory to another location
# (such as /etc/openvpn) so that your
# edits will not be wiped out by a future
# OpenVPN package upgrade.
# This variable should point to
# the top level of the easy-rsa
# tree.
export EASY_RSA="`pwd`"
#
# This variable should point to
# the requested executables
#
export OPENSSL="openssl"
export PKCS11TOOL="pkcs11-tool"
export GREP="grep"
# This variable should point to
# the openssl.cnf file included
# with easy-rsa.
export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`
# Edit this variable to point to
# your soon-to-be-created key
# directory.
#
# WARNING: clean-all will do
# a rm -rf on this directory
# so make sure you define
# it correctly!
export KEY_DIR="$EASY_RSA/keys"
# Issue rm -rf warning
echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
# PKCS11 fixes
export PKCS11_MODULE_PATH="dummy"
export PKCS11_PIN="dummy"
# Increase this to 2048 if you
# are paranoid. This will slow
# down TLS negotiation performance
# as well as the one-time DH parms
# generation process.
export KEY_SIZE=1024
# In how many days should the root CA key expire?
export CA_EXPIRE=3650
# In how many days should certificates e
ВНИМАНИЕ: Спойлер!
ВНИМАНИЕ: Спойлер!
export KEY_EXPIRE=3650
# These are the default values for fields
# which will be placed in the certificate.
# Don't leave any of these fields blank.
export KEY_COUNTRY="US"
export KEY_PROVINCE="CA"
export KEY_CITY="SanFrancisco"
export KEY_ORG="Fort-Funston"
export KEY_EMAIL="Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript."
8. Экпортируем переменные из файла vars и выполняем удаление всех возможно уже существующих ключей:
cd /etc/openvpn
source ./vars
./clean-all
9. Генерируем закрытый ключ и сертификат сервера сертификации (СA) или назовём по-другому - Удостоверяющего центра, на основе которого будут созданы все остальные ключи (ключ и сертификат для VPN-сервера и ключи и сертификаты для VPN-клиентов)(т.е. используется обычный механизм PKI - public key infrastructure).
./build-ca
ВНИМАНИЕ: Спойлер!
[asterisk.gs.int openvpn]# ./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) [US]:RU
State or Province Name (full name) [CA]:SPB
Locality Name (eg, city) [SanFrancisco]:SPB
Organization Name (eg, company) [Fort-Funston]:Organization
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) [Fort-Funston CA]:Asterisk
Name []:Asterisk
Email Address [Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.]:myemail@domain.com
10. Генерируем закрытый ключ и сертификат для сервера:
./build-key-server name
ВНИМАНИЕ: Спойлер!
[asterisk.gs.int openvpn]# ./build-key-server asterisk
Generating a 1024 bit RSA private key
..................++++++
.++++++
writing new private key to 'asterisk.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) [US]:RU
State or Province Name (full name) [CA]:SPB
Locality Name (eg, city) [SanFrancisco]:SPB
Organization Name (eg, company) [Fort-Funston]:Organization
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) [asterisk]:
Name []:asterisk
Email Address [Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.]:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'SPB'
localityName :PRINTABLE:'SPB'
organizationName :PRINTABLE:'Organization'
organizationalUnitName:PRINTABLE:'IT'
commonName :PRINTABLE:'asterisk'
name :PRINTABLE:'asterisk'
emailAddress :IA5STRING:'Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.'
Certificate is to be certified until Mar 7 16:25:54 2021 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
Generating a 1024 bit RSA private key
..................++++++
.++++++
writing new private key to 'asterisk.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) [US]:RU
State or Province Name (full name) [CA]:SPB
Locality Name (eg, city) [SanFrancisco]:SPB
Organization Name (eg, company) [Fort-Funston]:Organization
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) [asterisk]:
Name []:asterisk
Email Address [Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.]:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'SPB'
localityName :PRINTABLE:'SPB'
organizationName :PRINTABLE:'Organization'
organizationalUnitName:PRINTABLE:'IT'
commonName :PRINTABLE:'asterisk'
name :PRINTABLE:'asterisk'
emailAddress :IA5STRING:'Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.'
Certificate is to be certified until Mar 7 16:25:54 2021 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
11. Генерируем закрытый ключ и сертификат для клиента:
./build-key client1
ВНИМАНИЕ: Спойлер!
[asterisk.gs.int openvpn]# ./build-key client1
Generating a 1024 bit RSA private key
..........++++++
......++++++
writing new private key to 'client1.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) [US]:RU
State or Province Name (full name) [CA]:SPB
Locality Name (eg, city) [SanFrancisco]:SPB
Organization Name (eg, company) [Fort-Funston]:Organization
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) [client1]:
Name []:client1
Email Address [Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.]:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'SPB'
localityName :PRINTABLE:'SPB'
organizationName :PRINTABLE:'Organization'
organizationalUnitName:PRINTABLE:'IT'
commonName :PRINTABLE:'client1'
name :PRINTABLE:'client1'
emailAddress :IA5STRING:'Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.'
Certificate is to be certified until Mar 7 16:40:55 2021 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
12. Генерируем 1024-битный ключ по алгоритму Диффи-Хэллмана, который используется в механизме аутентификации ключей при установлении VPN-туннеля. Данный ключ остаётся на сервере.
Алгори́тм Ди́ффи — Хе́ллмана (англ. Diffie-Hellman, DH) — алгоритм, позволяющий двум сторонам получить общий секретный ключ, используя незащищенный от прослушивания, но защищённый от подмены, канал связи.
./build-dh
ВНИМАНИЕ: Спойлер!
[asterisk.gs.int openvpn]# ./build-dh
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
.....................+.....................+.........................+..........+.................................................................................................................................+......................................................................+......+................................................................................................................................................+..................+..........................+............+...............................................+...+...................................................+.....................................................................................+........................................................+.................................+..........+.....+....................................................+........+.+.....................+................................................................................+...............................................................................................+......................................................+.................+.......................................................................................................+................................................................................................................................................................................................................+......................................................................+.........................................++*++*++*
13. (Не обязательно) Генерируем симметричный TLS-ключ для предварительной защиты канала, еще до установленимя VPN-туннеля. Данный ключ является симметричным и должен находится как на сервере, так и на клиенте. Генерируем в папке /etc/openvpn/keys/
openvpn --genkey --secret ./ta.key
Все созданные ключи, сертификаты и запросы серверной части помещаем в папку /etc/openvpn/keys для удобства (в случае если они были сгенерированы в другом месте). Клиентские ключи и сертификаты передаются соответственно защищенным способом на клиентские машины. При этом для каждого сертификата существует свой закрытый ключ и файл запроса на сертификат:
*.key - закрытый ключ;
*.csr - запрос на сертификат;
*.crt - сертификат;
В идеале клиентские закрытые ключи не должны генерироваться на сервере и затем передаваться клиенту, а должны генерироваться на самом клиенте при помощи какого-либо установленного криптопровайдера (в качестве хранилища закрытого ключа используется например реестр, smart-карта или flash-накопитель). Затем создаётся файл запроса сертификата созданный на основе сгенерированного закрытого ключа, который уже отправляется по сети на сервер сертификации (Удостоверяющий центр), где в ответ по сети передаётся сгенерированный сертификат. (т.к. файл запроса сертификата и сам сертификат шифрования сами по себе не составляют ценности без закрытого ключа, то их можно передавать по незащищённым каналам связи).
14. Копируем пример файла конфигурации VPN-сервера server.conf из разархивированной папки (см п.1) в боевую папку /etc/openvpn
cp ...../openvpn-2.1.4/sample-config-files/server.conf /etc/openvpn/server.conf
и редактируем необходимые параметры:
vi /etc/openvpn/server.conf
ВНИМАНИЕ: Спойлер!
[asterisk.gs.int openvpn]# vi ./server.conf
#################################################
# Sample OpenVPN 2.0 config file for #
# multi-client server. #
# #
# This file is for the server side #
# of a many-clients <-> one-server #
# OpenVPN configuration. #
# #
# OpenVPN also supports #
# single-machine <-> single-machine #
# configurations (See the Examples page #
# on the web site for more info). #
# #
# This config should work on Windows #
# or Linux/BSD systems. Remember on #
# Windows to quote pathnames and use #
# double backslashes, e.g.: #
# "C:\\Program Files\\OpenVPN\\config\\foo.key" #
# #
# Comments are preceded with '#' or ';' #
#################################################
# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d
# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one. You will need to
# open up this port on your firewall.
port 1194 #Порт установления VPN-соединения. Данный порт необходимо открыть на файрволе и "прокинуть" ч/з NAT на стороне сервера. Со стороны клиента ничего дополнительно делать не нужно.
# TCP or UDP server?
;proto tcp
proto udp # Использование протокола UDP для туннелирования
# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one. On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap
# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key). Each client
# and the server must have their own cert and
# key file. The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys. Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca /etc/openvpn/keys/ca.crt
cert /etc/openvpn/keys/server.crt
key /etc/openvpn/keys/server.key # This file should be kept secret
#Пути к ключевым файлам сервера
# Diffie hellman parameters.
# Generate your own with:
# openssl dhparam -out dh1024.pem 1024
# Substitute 2048 for 1024 if you are using
# 2048 bit keys.
dh /etc/openvpn/keys/dh1024.pem # - путь к ключевому файлу Диффи-Хэллмана
# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0
# Maintain a record of client <-> virtual IP address
# associations in this file. If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt
# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface. Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0. Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients. Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100
# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses. You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge
# Push routes to the client to allow it
# to reach other private subnets behind
# the server. Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
push "route 192.168.10.0 255.255.255.0" # - для добавления маршрута на клиенте
;push "route 192.168.20.0 255.255.255.0"
# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).
# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
# iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN. This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.
# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
# ifconfig-push 10.9.0.1 10.9.0.2
# Suppose that you want to enable different
# firewall access policies for different groups
# of clients. There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
# group, and firewall the TUN/TAP interface
# for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
# modify the firewall in response to access
# from different clients. See man
# page for more info on learn-address script.
;learn-address ./script
# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
;push "redirect-gateway def1 bypass-dhcp"
# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"
# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
client-to-client #- для возможности обмена данными между подключенными VPN-клиентами
# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names. This is recommended
# only for testing purposes. For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn
# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
;keepalive 10 120
# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
# openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-auth ta.key 0 # This file is secret - для предварительного установления защищенного канала с использованием симметричного ключа
# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
;cipher BF-CBC # Blowfish (default)
;cipher AES-128-CBC # AES
;cipher DES-EDE3-CBC # Triple-DES
# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
comp-lzo
# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100
# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nobody
# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun
# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log
# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it. Use one
# or the other (but not both).
;log openvpn.log
;log-append openvpn.log
# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3
# Silence repeating messages. At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20
# Включение дополнительного порта мониторинга и управления VPN-сервером. (По умолчанию этой строчки нет в
# конфиге). Эта опция нужна для администратора сервера, для мониторинга количеcтва VPN-соединений,
# VPN-клиентов, для возможности "убить" ту или иную сессию.
# Указывается IP-адрес сетевого интерфейса сервера и TCP порт для мониторинга. Можно указать адрес 0.0.0.0
# для возможности мониторинга со всех интерфейсов.
management Х.Х.Х.Х 8329
#################################################
# Sample OpenVPN 2.0 config file for #
# multi-client server. #
# #
# This file is for the server side #
# of a many-clients <-> one-server #
# OpenVPN configuration. #
# #
# OpenVPN also supports #
# single-machine <-> single-machine #
# configurations (See the Examples page #
# on the web site for more info). #
# #
# This config should work on Windows #
# or Linux/BSD systems. Remember on #
# Windows to quote pathnames and use #
# double backslashes, e.g.: #
# "C:\\Program Files\\OpenVPN\\config\\foo.key" #
# #
# Comments are preceded with '#' or ';' #
#################################################
# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d
# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one. You will need to
# open up this port on your firewall.
port 1194 #Порт установления VPN-соединения. Данный порт необходимо открыть на файрволе и "прокинуть" ч/з NAT на стороне сервера. Со стороны клиента ничего дополнительно делать не нужно.
# TCP or UDP server?
;proto tcp
proto udp # Использование протокола UDP для туннелирования
# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one. On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap
# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key). Each client
# and the server must have their own cert and
# key file. The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys. Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca /etc/openvpn/keys/ca.crt
cert /etc/openvpn/keys/server.crt
key /etc/openvpn/keys/server.key # This file should be kept secret
#Пути к ключевым файлам сервера
# Diffie hellman parameters.
# Generate your own with:
# openssl dhparam -out dh1024.pem 1024
# Substitute 2048 for 1024 if you are using
# 2048 bit keys.
dh /etc/openvpn/keys/dh1024.pem # - путь к ключевому файлу Диффи-Хэллмана
# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0
# Maintain a record of client <-> virtual IP address
# associations in this file. If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt
# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface. Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0. Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients. Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100
# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses. You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge
# Push routes to the client to allow it
# to reach other private subnets behind
# the server. Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
push "route 192.168.10.0 255.255.255.0" # - для добавления маршрута на клиенте
;push "route 192.168.20.0 255.255.255.0"
# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).
# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
# iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN. This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.
# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
# ifconfig-push 10.9.0.1 10.9.0.2
# Suppose that you want to enable different
# firewall access policies for different groups
# of clients. There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
# group, and firewall the TUN/TAP interface
# for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
# modify the firewall in response to access
# from different clients. See man
# page for more info on learn-address script.
;learn-address ./script
# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
;push "redirect-gateway def1 bypass-dhcp"
# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"
# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
client-to-client #- для возможности обмена данными между подключенными VPN-клиентами
# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names. This is recommended
# only for testing purposes. For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn
# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
;keepalive 10 120
# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
# openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-auth ta.key 0 # This file is secret - для предварительного установления защищенного канала с использованием симметричного ключа
# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
;cipher BF-CBC # Blowfish (default)
;cipher AES-128-CBC # AES
;cipher DES-EDE3-CBC # Triple-DES
# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
comp-lzo
# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100
# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nobody
# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun
# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log
# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it. Use one
# or the other (but not both).
;log openvpn.log
;log-append openvpn.log
# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3
# Silence repeating messages. At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20
# Включение дополнительного порта мониторинга и управления VPN-сервером. (По умолчанию этой строчки нет в
# конфиге). Эта опция нужна для администратора сервера, для мониторинга количеcтва VPN-соединений,
# VPN-клиентов, для возможности "убить" ту или иную сессию.
# Указывается IP-адрес сетевого интерфейса сервера и TCP порт для мониторинга. Можно указать адрес 0.0.0.0
# для возможности мониторинга со всех интерфейсов.
management Х.Х.Х.Х 8329
15. Копируем примеры скриптов для запуска и остановки OpenVPN из разархивированной папки (см п.1) в боевую папку /etc/openvpn и правим их в соответствии со своими предпочтениями:
cp ...../openvpn-2.1.4/sample-config-files/openvpn-startup.sh /etc/openvpn
Пример скрипта openvpn-startup.sh:
ВНИМАНИЕ: Спойлер!
#!/bin/sh
# A sample OpenVPN startup script
# for Linux.
# openvpn config file directory. Папка с файлом конфиграции сервера
dir=/etc/openvpn
# load the firewall. Запуск файрвола iptables. Лучше закомментировать данный параметр, если iptables не
# настроен или вообще не используется. В противном случае можно "потерять" все работающие соединения с
# сервером.
#$dir/firewall.sh
# load TUN/TAP kernel module. Загрузка виртуального туннельного интерфейса в ядро.
modprobe tun
# enable IP forwarding. Включение сервиса маршрутизации. Очень важный параметр, без которого не будут
# маршрутизироваться пакеты от VPN-клиента во внутреннюю сеть и обратно.
echo 1 > /proc/sys/net/ipv4/ip_forward
# Invoke openvpn for each VPN tunnel
# in daemon mode. Alternatively,
# you could remove "--daemon" from
# the command line and add "daemon"
# to the config file.
#
# Each tunnel should run on a separate
# UDP port. Use the "port" option
# to control this. Like all of
# OpenVPN's options, you can
# specify "--port 8000" on the command
# line or "port 8000" in the config
# file.
# Можно создать разные конфигурационные файлы для сервера, для одноврменного постороения нескольких
# VPN-туннелей с разными параметрами, например с разными портами
openvpn --cd $dir --daemon --config server.conf #наш созданный файл конфигурации.
#openvpn --cd $dir --daemon --config vpn2.conf
#openvpn --cd $dir --daemon --config vpn2.conf
cp ...../openvpn-2.1.4/sample-config-files/openvpn-stutdown.sh /etc/openvpn
Пример скрипта openvpn-shutdown.sh:
ВНИМАНИЕ: Спойлер!
#!/bin/sh
# stop all openvpn processes
killall -TERM openvpn
16. Запускаем OpenVPN-сервер:
/etc/openvpn/openvpn-startup.sh
и проверяем запустился ли сервис:
netstat -luntp |grep openvp
ВНИМАНИЕ: Спойлер!
[root@asterisk openvpn]# netstat -luntp |grep openvp
tcp 0 0 0.0.0.0:1194 0.0.0.0:* LISTEN 2763/openvpn
tcp 0 0 0.0.0.0:1194 0.0.0.0:* LISTEN 2763/openvpn
На этом этапе серверная часть закончена и готова к установлению туннеля.
Клиентская часть
Т.к. в моём случае на клиенте (компьютере пользователя) стоит ОС Windows, то рассмотрим пример настройки OpenVPN-клиента именно для Windows.
1. Скачиваем дистрибутив OpenVPN для Windows по ссылке swupdate.openvpn.net/community/releases/...pn-2.1.4-install.exe и устанавливаем с опциями "по умолчанию".
При установке дистрибутива система установит также драйвер виртуального VPN-интерфейса:
2. Копируем пример файла конфигурации клиента client.ovpn из папки c:\Program Files\OpenVPN\sample-config в c:\Program Files\OpenVPN\config и редактируем его:
ВНИМАНИЕ: Спойлер!
##############################################
# Sample client-side OpenVPN 2.0 config file #
# for connecting to multi-client server. #
# #
# This configuration can be used by multiple #
# clients, however each client should have #
# its own cert and key files. #
# #
# On Windows, you might want to rename this #
# file so it has a .ovpn extension #
##############################################
# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client
# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel
# if you have more than one. On XP SP2,
# you may need to disable the firewall
# for the TAP adapter.
;dev-node MyTap
# Are we connecting to a TCP or
# UDP server? Use the same setting as
# on the server.
;proto tcp
proto udp
# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
# Прописываем внешний IP-адрес сервера, если он напрямую подключен в интернет (либо адрес файрвола, на
# котором предварительно через NAT/PAT прокинут порт udp 1194 на наш VPN-сервер). Можно указать несколько
# VPN-серверов
remote Х.Х.Х.Х 1194
;remote Y.Y.Y.Y 1194
;remote Z.Z.Z.Z 1195
# Choose a random host from the remote
# list for load-balancing. Otherwise
# try hosts in the order specified.
# Можно включить данную функцию, если используются несколько VPN-серверов, для балансировки нагрузки
# на серверы.
;remote-random
# Keep trying indefinitely to resolve the
# host name of the OpenVPN server. Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite
# Most clients don't need to bind to
# a specific local port number.
# Здесь можно прописать конкретный клиентский локальный порт, на котором будет строиться туннель (полезно,
# если установлен файрвол на компьютере). Если прописано nobind, то локальный порт выбирается автоматически.
nobind
# Downgrade privileges after initialization (non-Windows only)
;user nobody
;group nobody
# Try to preserve some state across restarts.
persist-key
persist-tun
# If you are connecting through an
# HTTP proxy to reach the actual OpenVPN
# server, put the proxy server/IP and
# port number here. See the man page
# if your proxy server requires
# authentication.
;http-proxy-retry # retry on connection failures
;http-proxy [proxy server] [proxy port #]
# Wireless networks often produce a lot
# of duplicate packets. Set this flag
# to silence duplicate packet warnings.
;mute-replay-warnings
# SSL/TLS parms.
# See the server config file for more
# description. It's best to use
# a separate .crt/.key file pair
# for each client. A single ca
# file can be used for all clients.
# Имя файла сертификата CA и файлов сертификата и ключа клиента
ca ca.crt
cert client.crt
key client.key
# Verify server certificate by checking
# that the certicate has the nsCertType
# field set to "server". This is an
# important precaution to protect against
# a potential attack discussed here:
# openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the nsCertType
# field set to "server". The build-key-server
# script in the easy-rsa folder will do this.
ns-cert-type server
# If a tls-auth key is used on the server
# then every client must also have the key.
# предварительного установления защищенного канала с использованием симметричного ключа. На клиенте
# прописывается цифра 1, на сервере - 0. ta.key - имя симметричного ключа.
tls-auth ta.key 1
# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
;cipher x
# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
comp-lzo
# Set log file verbosity.
verb 3
# Silence repeating messages
;mute 20
3. Копируем в папку c:\Program Files\OpenVPN\config\ клиентский ключ client1.key и сертификат client1.crt, сертификат СA.crt (сертификат сервера сертификации), и симметричный ключ ta.key.
4. Запускаем GUI интерфейс из меню "Пуск", либо из c:\Program Files\OpenVPN\bin\openvpn-gui-1.0.3.exe и нажимаем Connect из-под иконки OpenVPN в трее.
Для установления туннеля из командной строки запускаем:
c:\Program Files\OpenVPN\bin\openvpnserv.exe /start
Для автоматического установления VPN-туннеля при загрузке ОС включаем OpenVPN Service в режим автоматического запуска:
Проверяем работоспособность туннеля, маршрутизацию и т.д.
Наслаждаемся результатом!!!

Дополнения.
Для просмотра VPN-соединений на сервере в реальном времени можно зайти по telnet на сервер по порту tcp 8329, если соответствующая строка была прописана в файле server.conf
management 0.0.0.0 8329
и в режиме командной строки смотреть сессии клиентов и если нужно, удалять сессии:
telnet X.X.X.X 8329
Кроме этого можно скачать графическую оболочку для мониторинга VPN-соединений под названием OpenVPN Control по ссылке sourceforge.net/projects/openvpn-control...staller.exe/download
Скриншоты программы OpenVPN Control:
Последнее редактирование: 11 года 3 мес. назад пользователем PNV.
Пожалуйста Войти , чтобы присоединиться к беседе.
Меньше
Больше
- Сообщений: 50
- Спасибо получено: 15
11 года 3 мес. назад #12
от PNV
PNV ответил в теме Re: Установка и настройка OpenVPN
Если при установлении VPN-туннеля в логах клиента появляется следующая ошибка:
Fri Mar 11 16:23:10 2011 VERIFY ERROR: depth=1, error=self signed certificate in certificate chain: /C=RU/ST=SPB/L=SPB/O=Organization/OU=IT/CN=Asterisk/name=Asterisk/emailAddress=myemail@domain.com
Fri Mar 11 16:23:10 2011 TLS_ERROR: BIO read tls_read_plaintext error: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Fri Mar 11 16:23:10 2011 TLS Error: TLS object -> incoming plaintext read error
Fri Mar 11 16:23:10 2011 TLS Error: TLS handshake failed
Fri Mar 11 16:23:10 2011 TCP/UDP: Closing socket
то проблема с некорректно созданными сертификатами клиента/сервера.
Необходимо снова пересоздать сертификаты.
Fri Mar 11 16:23:10 2011 VERIFY ERROR: depth=1, error=self signed certificate in certificate chain: /C=RU/ST=SPB/L=SPB/O=Organization/OU=IT/CN=Asterisk/name=Asterisk/emailAddress=myemail@domain.com
Fri Mar 11 16:23:10 2011 TLS_ERROR: BIO read tls_read_plaintext error: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Fri Mar 11 16:23:10 2011 TLS Error: TLS object -> incoming plaintext read error
Fri Mar 11 16:23:10 2011 TLS Error: TLS handshake failed
Fri Mar 11 16:23:10 2011 TCP/UDP: Closing socket
то проблема с некорректно созданными сертификатами клиента/сервера.
Необходимо снова пересоздать сертификаты.
Пожалуйста Войти , чтобы присоединиться к беседе.
11 года 3 мес. назад - 11 года 3 мес. назад #13
от TOLLIFi
IT и Телеком: IP-телефония, интернет-технологии, программирование, web-сервисы.
TOLLIFi ответил в теме Re: Установка и настройка OpenVPN
Вот перевод на русский язык параметров файла конфигурации OpenVPN (server.conf / client.conf). За точность перевода тех или иных параметров не отвечаю - перевел, как смог
--- TUNNEL OPTIONS >>>
--- CLIENT-MODE OPTIONS >>>
--- DATA CHANNEL ENCRYPTION OPTIONS >>>
--- TLS MODE OPTIONS >>>

--- TUNNEL OPTIONS >>>
ВНИМАНИЕ: Спойлер!
;mode p2p | ;openvpn-режим ('p2p' - 1сервер:1клиент, 'server' - 1сервер:Nклиентов) |
;auto-proxy | ;использовать прокси-сервер (в начале HTTP-Proxy, иначе SOCKS-Proxy, через API вводится пароль, если включен |
resolv-retry infinite | ;'infinite' - постоянно/периодически опрашивать доменное имя сервера; '[сек.]' - через фикс. время (0 - отключить DNS-запросы) |
proto udp | ;протокол по умолчанию ('udp' - на обоих хостах одинаковый д.б.; 'tcp-client' - tcp для клиента; tcp-server - tcp для сервера) |
port 1195 | ;локальный и удаленный TCP/UDP-порт (1194 по умолчанию) |
;lport port | ;локальный TCP/UDP-порт |
;rport port | ;удаленный TCP/UDP-порт |
;local <IP/hostname> | ;слушать VPN-соединения только на указанном IP |
;bind | ;принимать соединения только на заданные локальные порт и IP-адрес |
;nobind | ;принимать соединения не только на заданные локальные порт и IP-адрес |
;remote IP/hostname <port> <proto> | ;удаленный VPN-сервер(клиент)/порт/протокол с которым соединяемся(ждем соединения). Подобие IP-фильтра |
float | ;разрешить хосту 'remote' авторизацию на локальном VPN с другого IP, в случае, если у него динамический IP |
;connect-retry 5 | ;время [сек.] между повторными попытками соединения (только для 'proto tcp-client') |
;connect-retry-max 5 | ;количество попыток повторных соединений (только для 'proto tcp-client') |
;http-proxy <server> <port> <authfile | 'auto'> <auth-method> | ;адрес HTTP-Proxy. ('authfile' - файл с логином и паролем) |
;http-proxy-retry | ;генерировать событие SIGUSR1 (сброс) в случае ошибки при авторизации на HTTP-Proxy. |
;http-proxy-timeout 5 | ;тайм-аут авторизации [сек.] на HTTP-Proxy |
;http-proxy-option type <parm> | ;дополнительные опции HTTP-Proxy ('type': VERSION, AGENT; 'param': 1.0, "User-Agent") |
;socks-proxy server <port> | ;адрес SOCKS5-Proxy/порт |
;socks-proxy-retry | ;генерировать событие SIGUSR1 (сброс) в случае ошибки при авторизации на SOCKS5-Proxy |
;можно указать несколко VPN-серверов для коннекта (только для режима 'client'). В блоке <connection> можно указать след. параметры (они же являются глобальными, если указаны за пределами блоков): | |
;bind, connect-retry, connect-retry-max, connect-timeout, float, http-proxy, http-proxy-option, http-proxy-retry, http-proxy-timeout, local, lport, nobind, port, proto, remote, rport, socks-proxy, socks-proxy-retry | |
<connection> | |
remote www.myserver.com 1195 udp | |
</connection> | |
;<connection> | |
;remote 198.19.36.99 443 tcp | |
;http-proxy 192.168.0.8 8080 | |
;http-proxy-retry | |
;</connection> | |
;remote-random | ;случайным образом выбирать VPN-сервер для коннекта (из списка доступных <connection>) |
;ipchange cmd | ;выполнить команду 'cmd', когда IP <remote>-хоста аутентифицируется или изменяется |
dev tun | ;TUN/TAP-виртуальный интерфейс (д.б. одинаковым на обоих хостах ('tun', 'tap', 'X'), 'X' - указывается, при динамическом назначении интерфейса) |
;dev-type <device-type> | ;тип виртуального интерфейса ('tun' или 'tap') |
;topology net30 | ;режим сетевой топологии, исп. только для 'dev tun' (при 'dev tap' - 'topology subnet' всегда): |
;'net30' - на клиента выделяется подсеть с маской /30 (исп. обычно для Win); | |
;'p2p' - соединение точка-точка (не исп. для Win); | |
;'subnet' - на клиента выделяется подсеть с ззаданной маской. | |
;tun-ipv6 | ;включить совместимость с IPv6 (только для 'dev tun') |
;dev-node <node> | ;задать тип интерфейса отличный от /dev/net/tun, /dev/tun, /dev/tap, и др. |
;lladdr address | ;MAC-адрес интерфейса (только для 'dev tap') |
;iproute <cmd> | ;использовать отличную от 'iproute2' команду для изменения табл.маршрутизации (исп. в особых случаях запуска openvpn...) |
;ifconfig l rn | ;сетевые параетры ('l' - локальный IP-адрес VPN-интерфейса. 'rn' - для TUN - IP-адрес удаленной точки VPN, для TAP... |
;ifconfig-noexec | ;don't actually execute ifconfig/netsh commands, instead pass --ifconfig parameters to scripts using environmental... |
;ifconfig-nowarn | ;не выдавать предупреждения при возможных проблемах с сетевыми настройками |
;route network/IP <netmask> <gateway> <metric> | ;добавление маршрута в табл.маршрутизации при запуске openvpn |
;max-routes <n> | ;максимальное количество 'route', к-ое м.б. добавлено в лок. табл.маршр. |
;route-gateway <gw | 'dhcp'> | ;маршрут по умолчанию ('dhcp' - gw, полученный от DHCP-сервера) |
;route-metric <m> | ;метрика маршрута |
;route-delay 0 <w> | ; Задержка добавления маршрута в ТМ на 'n' сек. (w - доп. параметр ожидания для Win): 1) пустое значение - доб. сразу, но перед тем, как загрузится --user или --group (или выполнится --chroot); 2) 0 - немедленное добавление; 3) n - по истечении n сек. |
;route-up <cmd> | ;выполнить команду cmd, после добавления маршрутов |
;route-noexec | ;не добавлять в авторежиме маршруты. Вместо это направить данные маршруты в скрипт --route-up script |
;route-nopull | ;когда исп. --client или --pull не принимать маршруты от сервера, но все остальные опции будут приняты |
;allow-pull-fqdn | ;позволить принимать доменные имена от сервера |
;redirect-gateway <flag1 flag2 ...> | ;'local', 'def1', 'bypass-dhcp', 'bypass-dns'. |
link-mtu 1500 | ;размер MTU |
;tun-mtu 1463 | ;размер MTU для TUN-интерфейса |
tun-mtu-extra 0 | ;burst MTU. Для TUN по умолчанию - 0, для TAP - 32. |
;mtu-disc type | ;MTU discovery on TCP/UDP (only supported on OSes such as Linux): |
;'no' - Never send DF (Don't Fragment) frames | |
;'maybe' - Use per-route hints | |
;'yes' - Always DF (Don't Fragment) | |
;mtu-test | ;распознать MTU при установке соединения путем посылки ping разных размеров (занимает около 3 мин.). |
;fragment <max> | ;фрагментация UDP пакетов на размеры не более 'max' (включая, 4 доп.байта) |
;mssfix <max> | ;х/з че за хреновина |
sndbuf 65536 | ;TCP/UDP socket send buffer size |
rcvbuf 65536 | ;TCP/UDP socket receive buffer size |
;socket-flags <flag1 flag2 ...> | ;'TCP_NODELAY' (для уменьшения задержек) useful in TCP mode, and causes the kernel to send... |
txqueuelen 100 | ;(Linux only) Set the TX queue length on the TUN/TAP interface. Currently defaults to 100 |
;shaper <n> | ;ограничение исходящего трафика по туннелю до 'n' Байт/сек. 100 bytes/sec <= 'n' <= 100 Mbytes/sec |
inactive 1800 | ;отключить VPN-соединение, если в течении 30 мин. не было передано данных (суммарным размером 'bytes') |
ping 240 | ;пинговать удаленный хост каждые 4 мин. (шифруется, если исп. TLS) |
ping-exit 3600 | ;если по истечении 1 часа не было получено ответов на 'ping' - отключить VPN-соединение |
;ping-restart 7260 | ;если по истечении 2 часов не было получено ответов на 'ping' - переподключить VPN-соединение |
;keepalive 60 300 | ;пинговать каждые 60 сек, если нет ответа после 300 сек. - переподключить VPN-соединение |
;ping-timer-rem | ;run the --ping-exit / --ping-restart timer only if we have a remote address |
persist-tun | не закрывать и переоткрывать TUN/TAP, если поступил сигнал 'SIGUSR1' или 'ping-restart' |
persist-key | ;не считывать заново '*.key' файлы, если поступил сигнал 'SIGUSR1' или 'ping-restart' |
;persist-local-ip | ;сохранить изначальный локальный IP-адрес и порт для соединения, если поступил сигнал 'SIGUSR1' или 'ping-restart' |
;persist-remote-ip | ;сохранить изначальный удаленный IP-адрес и порт для соединения, если поступил сигнал 'SIGUSR1' или 'ping-restart' |
;mlock | ;хранить все секретные данные VPN-соединения в памяти, а не в файле подкачки на HDD |
;up <cmd> | ;выполнить команды 'cmd', после того как TUN/TAP device будет открыт |
;down <cmd> | ;выполнить команды 'cmd', после того как TUN/TAP device будет закрыт |
;down-pre | ;вызвать 'down cmd' перед тем, как TUN/TAP device будет закрыт |
;up-delay | ;задержка передачи данных, пока не закончится аутентификация |
;up-restart | ;выполнять команды 'up cmd' и 'down cmd' также при перезапуске VPN-соединения |
;setenv <name> <value> | ;присвоить переменной 'name' значение 'value' |
;setenv FORWARD_COMPATIBLE 1 | ;игнорировать команды не поддерживаемые данной версией OpenVPN |
;setenv-safe <name> <value> | ;присвоить переменной 'OPENVPN_name' значение 'value' |
script-security 1 execve | ;policy-level control over OpenVPN's usage of external programs and scripts: |
;0 - Strictly no calling of external programs | |
;1 - (Default) Only call built-in executables such as ifconfig, ip, route, or netsh | |
;2 - Allow calling of built-in executables and user-defined scripts | |
;3 - Allow passwords to be passed to scripts via environmental variables (potentially unsafe) | |
;disable-occ | ;игнорировать несоответствия параметров между сервером и клиентом |
user nobody | ;сменить UID демона на 'nobody', после инициализации VPN-соединения |
group nogroup | ;сменить GID демона на 'nogroup', после инициализации VPN-соединения |
cd /etc/openvpn/ | ;сменить директорию на 'dir', перед считыванием файлов секретных ключей и т.п. |
;chroot <dir> | ;сменить корневую директорию на 'dir', выше которой OpenVPN не получит доступа |
;setcon <context> | ;х/з че означает |
;daemon <progname> | ;использовать для логирования демон 'daemon', в кач-ве имени программы в логах исп. 'progname' |
;syslog <progname> | ;логировать все в syslog, в кач-ве имени программы в логах исп. 'progname' |
passtos | ;назначить TOS пакетам VPN-соединения из содержимого TOS шифрованного пакета |
;inetd <wait | nowait> <progname> | ;use this option when OpenVPN is being run from the inetd or xinetd(![]() |
;log <file> | ;логировать все сообщения в файл 'file', при перезагрузке файл очищается |
log-append /var/log/openvpn_tun.log | ;логировать все сообщения в файл '/var/log/openvpn_tun.log', при перезагрузке в файл добавляются очередные логи |
;suppress-timestamps | ;не указывать время в лог-сообщениях |
;writepid /var/run/openpvn.pid | ;записывать OpenVPN's PID в '/var/run/openpvn.pid' |
;nice <n> | ;изменить приоритет процесса OpenVPN после инициализации на 'n'. |
;fast-io | ;активировать быстрые операции I/O (исп. в non-Windows системах, где 'proto udp' и 'shaper' не задействован) |
;multihome | ;для сервера OS Linux only - отсылать пакеты обратно в тот интерфейс, в который пакет пришел |
;echo <parms...> | ;послать сообщение 'params' в лог-файл. |
;remap-usr1 <signal> | ;преобразовавать внутренние или внешние сгенерированные сигналы SIGUSR1 в сигнал 'signal': |
;SIGHUP - перезапуск без учета параметров 'persist..'; | |
;SIGTERM - завершение VPN-соединения и выход | |
verb 3 | ;уровень важности сообщений в логах: |
;0 - No output except fatal errors; | |
;1-4 - Normal usage range | |
;5 - Output R and W characters to the console for each packet read and write | |
;6-11 - Debug info range (see errlevel.h for additional information on debug levels) | |
status openvpn-status_tun.log 120 | ;записывать статус состояния OpenVPN в файл 'openvpn-status_tun.log' каждые 120 сек. |
status-version 1 | ;версия формата файла статуса: 1, 2 или 3 (по умолчанию 1) |
;mute <n> | ;ограничить логирование последовательных сообщений одно типа до 'n'. |
;comp-lzo yes | ;использовать LZO-сжатие пакетов (no, yes, adaptive - по умолчнию) |
;push "comp-lzo yes" | |
;comp-noadapt | ;не использовать адаптивный режим сжатия (исп. при указании режима LZO от сервера) |
management localhost 8888 | ;активировать интерфейс для управления (в качестве IP м.б. указан "tunnel", 'pw-file' - файл с паролем) на порт 8888 |
;management-query-passwords | ;запрашивать пароль при входе интерфейс управления |
;management-forget-disconnect | ;не кэшировать пароли после завершения сеанса управления (выхода из интерфейса управления) |
;management-hold | ;запуск интерфейса управления в режиме ожидания |
;management-signal | ;послать 'SIGUSR1' в OpenVPN при выходе из интерфейса управления |
;management-log-cache <n> | ;кэшировать 'n' последовательных лог-сообщений интерфейса управления |
;management-client-auth | ;дает клиенту интерфейса управления ответственность подтвердить подлинность |
;management-client-pf | ;задействовать фильтр пакетов для клиентов интерфейса управления |
;management-client-user <u> | ;фильтровать доступ к интерфейсу управления (доступ только пользователям 'u') |
;management-client-group <g> | ;фильтровать доступ к интерфейсу управления (доступ только группе пользователей 'g') |
;plugin module-pathname <init-string> | ... |
;plugin /usr/lib/openvpn/openvpn-auth-pam.so login | ... |
--- CLIENT-MODE OPTIONS >>>
ВНИМАНИЕ: Спойлер!
client | ;режим клиента ('client' эквивалентно 'pull' + 'tls-client') |
pull | ;разрешать серверу вносить изменения в локальную таблицу маршрутизации. |
auth-user-pass /etc/openvpn/keys/auth-user-pass | ;авторизация на сервере с использование логина и пароля пользователя в системе сервера |
auth-retry nointeract | Режимы повторной авторизации: |
;'none' - Client will exit with a fatal error (this is the default) | |
;'nointeract' - Client will retry the connection without requerying for an --auth-user-pass username/password | |
;'interact' - Client will requery for an --auth-user-pass username/password and/or private key password before attempting a reconnection | |
;server-poll-timeout 15 | ;по истечении ожидания коннекта с первым, ч/з 15 сек посылать запрос на открытие VPN-соединения с другим VPN-сервером |
explicit-exit-notify 3 | ;послать серверу(клиенту) сигнал о закрытии VPN-соединения |
--- DATA CHANNEL ENCRYPTION OPTIONS >>>
ВНИМАНИЕ: Спойлер!
;secret <file> <direction> | ;Шифрование со статическим ключом (non-TLS). Исп. ключ (2048 bit) в секретном файле, генерируемом командой 'genkey' |
;'direction' - дополнительное штфрование отдельных направлений. '1' - у одного участника соединения, '2' - у обоих | |
auth MD5 | ;authenticate packets with HMAC using message digest algorithm alg. (The default is SHA1) ('none' без аутентификции) |
cipher BF-CBC | ;encrypt packets with cipher algorithm alg. The default is BF-CB (BF-CBC, AES-128-CBC, DES-EDE3-CBC) |
;keysize <n> | ;size of cipher key in bits (optional) |
;prng <alg> <nsl> | ;(advanced) использовать псевдо-случайный генератор чисел, для алгоритма (default=sha1), и (опционально) nsl (default=16) от 16 до... |
;alg=none - отключить встроенный ПСГЧ и исп. ПСГЧ OpenSSL RAND_bytes | |
;engine <engine-name> | ;активировать крипто-движок OpenSSL ('engine-name' - опционально указывается конкретное название) |
;no-replay | ;replay protection is accomplished by tagging each outgoing datagram with an identifier that is guaranteed to be ... |
replay-window 128 <t> | ;use a replay protection sliding-window of size 'n' and a time window of 't' seconds. By default 'n' is 64 (the IPSec default) |
mute-replay-warnings | ;(для Wi-Fi) silence the output of replay warnings, which are a common false alarm on WiFi networks |
;replay-persist <file> | ;persist replay-protection state across sessions using file to save and reload the state |
;no-iv | ;не использовать ПСГЧ (когда все сообщения шифруются одним и тем же секретным ключом) - повышает производительность |
;test-crypto | ;протестировать параметры шифрования, указанные выше: |
;openvpn --test-crypto --secret key | |
;openvpn --test-crypto --secret key --verb 9 |
--- TLS MODE OPTIONS >>>
ВНИМАНИЕ: Спойлер!
ca keys/ca.crt | ;путь к сертификату сервера сертификации |
cert keys/metro.crt | ;путь к собственному сертификату |
key keys/metro.key | ;путь к собственному секретному ключу |
tls-remote MyServer | ;устанавливать TLS-сессии только с сервером MyServer |
ns-cert-type server | ;проверять, что сертификат подписан самим сервером |
;auth-nocache | ;не кэшировать пароль в файле подкачки (т.е. постоянно "ручками" придется вбивать логин и пароль) |
askpass /etc/openvpn/keys/askpass | ;запрашивать пароль на запуск демона OpenVPN (либо вводить с консоли, либо брать из файла '/etc/openvpn/keys/askpass') |
tls-client | ;режим TLS-клиента |
tls-auth keys/ta.key 1 | ;защита от DDoS-атак |
reneg-sec 14400 | ;перепроверять TLS-соединение каждые 4 часа (TLS-handshake - повторный обмен данными аутентификации) |
tls-timeout 240 | ;тайм-аут обмена пакетами TLS-данных 4 мин. (если нет 'ack' от удаленного хоста, то следует повторная передача пакета) |
hand-window 1200 | ;каждые 20 мин. попробовать установить TLS-соединение (если еще не установлено) |
tran-window 3600 | ;через 1 час. больше не использовать старые аутентификационные данные TLS-соединения для передачи данных |
;tls-exit | ;закрыть TLS-соединение и не пытаться его повторно устанавливать по истечении 'tran-window' |
IT и Телеком: IP-телефония, интернет-технологии, программирование, web-сервисы.
Последнее редактирование: 11 года 3 мес. назад пользователем TOLLIFi.
Спасибо сказали: PNV
Пожалуйста Войти , чтобы присоединиться к беседе.
- Вы здесь:
-
Главная
-
Форум
-
IT и телекоммуникации
-
Конфигурация сетевого оборудования
- Установка и настройка OpenVPN