Файл tls auth отсутствует
Для удобства настройки заходим под суперпользователем:
Настройка OpenVPN-клиента
Сертификат должен быть сформирован на сервер, после чего перенесен на клиентское устройство. Рассмотрим процесс подробнее.
Параметры конфигурационного файла
Наиболее полный и актуальный список параметров для OpenVPN можно получить командой openvpn --help (в Linux и Windows).
Доступ в Интернет через VPN-сервер
Настройка делает так, что клиенты VPN-сервера начинают использовать последний как шлюз по умолчанию. Таким образом, весь трафик идет через наш сервер.
Открываем на сервере конфигурационный файл:
push "redirect-gateway def1"
push "dhcp-option DNS 77.88.8.8"
systemctl restart openvpn@server
* сервер должен быть настроен в качестве шлюза. Подробнее в инструкции Настройка Интернет шлюза на Ubuntu.
Настройка на сервере
Открываем конфигурационный файл openvpn:
И добавляем следующие строчки:
plugin /usr/lib/openvpn/plugins/openvpn-plugin-auth-pam.so login
tmp-dir /etc/openvpn/tmp
- plugin — путь до библиотеки проверки введенных логина и пароля. Как путь, так и название файла openvpn-plugin-auth-pam.so могут отличаться. Это зависит от версии Linux и OpenVPN. Чтобы найти путь до нужного файла, можно воспользоваться командой find / -name "openvpn-*auth-pam*.so" -print.
- tmp-dir — указание пути до директории хранения временных файлов. Если не указать, то будет использоваться /tmp, однако, на практике это может привести к ошибке Could not create temporary file '/tmp/openvpn_.tmp': No such file or directory (errno=2).
Создаем каталог для временных файлов и задаем на него права:
chmod 777 /etc/openvpn/tmp
systemctl restart openvpn@server
Создаем учетную запись для авторизации:
useradd vpn1 -s /sbin/nologin
Keep the root key (ca.key) on a standalone machine without a network connection
One of the security benefits of using an X509 PKI (as OpenVPN does) is that the root CA key (ca.key) need not be present on the OpenVPN server machine. In a high security environment, you might want to specially designate a machine for key signing purposes, keep the machine well-protected physically, and disconnect it from all networks. Floppy disks can be used to move key files back and forth, as necessary. Such measures make it extremely difficult for an attacker to steal the root key, short of physical theft of the key signing machine.
It seems that the OpenVPN Client on windows does not support TLS-Auth with a separate key file. So instead, you can paste your key contents in your openvpn client’s config file and use some thing like the following (inline ta.key):
When not using the above but using something like:
The server log shows something like:
Thu Apr 18 20 : 55 : 26 2013 TLS Error : incoming packet authentication failed from [ AF_INET ] IP_ADDRESS : 60454
Установка, настройка и запуск VPN-сервера
Обязательные шаги для развертывания сервиса — установка программного обеспечения, генерация сертификатов, настройка OpenVPN. Рассмотрим эти процессы по шагам.
Android
Установка выполняется из Google Play. Набираем в поиске OpenVPN Connect - нажимаем установить и принимаем условия.
tls-auth
The tls-auth directive adds an additional HMAC signature to all SSL/TLS handshake packets for integrity verification. Any UDP packet not bearing the correct HMAC signature can be dropped without further processing. The tls-auth HMAC signature provides an additional level of security above and beyond that provided by SSL/TLS. It can protect against:
- DoS attacks or port flooding on the OpenVPN UDP port.
- Port scanning to determine which server UDP ports are in a listening state.
- Buffer overflow vulnerabilities in the SSL/TLS implementation.
- SSL/TLS handshake initiations from unauthorized machines (while such handshakes would ultimately fail to authenticate, tls-auth can cut them off at a much earlier point).
Using tls-auth requires that you generate a shared-secret key that is used in addition to the standard RSA certificate/key:
This command will generate an OpenVPN static key and write it to the file ta.key. This key should be copied over a pre-existing secure channel to the server and all client machines. It can be placed in the same directory as the RSA .key and .crt files.
In the server configuration, add:
In the client configuration, add:
user/group (non-Windows only)
OpenVPN has been very carefully designed to allow root privileges to be dropped after initialization, and this feature should always be used on Linux/BSD/Solaris. Without root privileges, a running OpenVPN server daemon provides a far less enticing target to an attacker.
Аутентификация пользователей
Позволяет требовать от пользователя ввод логина и пароля при каждом подключении. Также идентификация каждого пользователя необходима для уникальной идентификации каждого из них и выдачи разных IP-адресов.
3. ERROR: Cannot open TUN/TAP dev /dev/net/tun: No such file or directory (errno=2)
Описание: ошибка возникаем при попытке запустить сервис openvpn.
Причина: не загружается модуль tun.
Решение: необходимо перед запуском сервиса openvpn создавать устройство tun. Для этого мы создадим скрипт, который будет создавать устройство при запуске сервера.
Создаем каталог, в который поместим скрипт:
Создадим сам скрипт:
/bin/mkdir /dev/net
/bin/mknod /dev/net/tun c 10 200
* данный скрипт создает каталог /dev/net, а в нем — устройство tun.
Создаем юнит для автозапуска скрипта:
[Service]
Type=oneshot
ExecStart=/bin/sh -c "/scripts/tun.sh"
Перечитываем изменения в systemd:
Разрешаем автозапуск юнита tun и стартуем скрипт:
systemctl enable tun --now
Теперь можно запустить openvpn:
systemctl start openvpn@server
Перезагружаем сервер, чтобы убедиться а работе сервиса после старта компьютера.
With this configuration an OpenVPN 2.2.1 can connect to the server, instead with new andorid "OpenVPN Connect" it's not possible.
The profile and certificates files are in /sdcard/OpenVPN and when I import the profile the client return: "Error reading file referenced by profile: [inline] : cannot open: /sdcard/OpenVPN/[inline]"
Someone can help me?
P.S.: which version of OpenVPn is used in new andorid "OpenVPN Connect"?
Post by jamesyonan » Thu Jan 24, 2013 1:52 am
Post by davide.belloni » Thu Jan 24, 2013 7:42 am
Hi jamesyonan,
thanks for the reply.
With specified configuration the profile can be imported in OpenVPN Connect for Android without errors, but the tls-auth key isn't send (I think) by the client.
In the server log I have:
Post by davide.belloni » Fri Jan 25, 2013 6:56 am
Hi to everyone,
I've seen that this post has been moved from Android to iOS, but this issue is present both Android and iOS software version!
Post by davide.belloni » Fri Jan 25, 2013 8:00 am
Hi,
now I've restarted the server and not reloaded it and works!
But the old clients without key direction don't connect anymore, so I've to revert the configuration
How can I permit connection to clients without key-direction and phone client with?
Post by wvd » Fri Jan 25, 2013 10:15 am
Hi, I started to see the same isue, HMAC authentication seems to fail since the upgrade to the latest openvpn connect client (1.1.8) for ANDROID in combination with v2.2.2 on the server side. As soon as I disable tls-auth on the client and server, it works again.
Jan 25 08:34:38 localhost openvpn[13037]: TLS Error: incoming packet authentication failed f
rom x.x.x.x:xxxx
Jan 25 08:34:40 localhost openvpn[13037]: Authenticate/Decrypt packet error: packet HMAC aut
hentication failed
Post by davide.belloni » Fri Jan 25, 2013 1:03 pm
Hi,
my problem now is tls-auth inclusion in OpenVPN Connect profile with bi-directional key direction.
I think that is something not implemented or not documented
Post by jamesyonan » Sat Jan 26, 2013 3:53 pm
The recommended tls-auth usage is to use "key-direction 0" on the server and "key-direction 1" on the client because that uses different tls-auth keys for the client -> server direction and server -> client direction (somewhat more secure), and it also works on all versions of OpenVPN.
If the server is using tls-auth without the key-direction parameter, such as "tls-auth ta.key"
it's a bit more problematic because then client-side unified profiles would need to have "key-direction bidirectional", however this directive will only be available on 1.0.1 (iOS) and 1.1.9 (Android), and is not currently implemented on the OpenVPN 2.x branch.
Post by wvd » Sun Jan 27, 2013 3:48 pm
jamesyonan wrote: The recommended tls-auth usage is to use "key-direction 0" on the server and "key-direction 1" on the client because that uses different tls-auth keys for the client -> server direction and server -> client direction (somewhat more secure), and it also works on all versions of OpenVPN.
Post by davide.belloni » Thu Jan 31, 2013 10:51 am
If the server is using tls-auth without the key-direction parameter, such as "tls-auth ta.key"
it's a bit more problematic because then client-side unified profiles would need to have "key-direction bidirectional", however this directive will only be available on 1.0.1 (iOS) and 1.1.9 (Android), and is not currently implemented on the OpenVPN 2.x branch.
Hi,
thanks for the reply.
There are possibilities that the directive will be implemented on the OpenVPN 2.x branch in the next future?
Post by fmarzocca » Sat Feb 23, 2013 2:23 pm
I had a similar problem but I have fixed the connection by adding "key direction1" in the client.
Now I have no connection errors, and the log is fine, but still the browser won't find the server. It looks like a DNS problem?
One of the often-repeated maxims of network security is that one should never place so much trust in a single security component that its failure causes a catastrophic security breach. OpenVPN provides several mechanisms to add additional security layers to hedge against such an outcome.
На сервере
Создадим каталог, куда поместим сертификаты для обмена:
* сертификаты будут скопированы в каталог /tmp для удобства их переноса на клиентский компьютер.
Переходим в каталог easy-rsa:
Создаем системные переменные, настроенные ранее в файле vars:
Как в случае формирования сертификата для сервера, наши следующие шаги зависят от версии RSA.
а) Для новой версии (easyrsa)
Создаем сертификат для клиента:
./easyrsa build-client-full client1 nopass
Вводим пароль, который указывали при создании корневого сертификата:
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:
Скопируем ключи во временную директорию:
cp pki/issued/client1.crt pki/private/client1.key pki/ca.crt pki/ta.key /tmp/keys/
Разрешим доступ на чтения всем пользователям:
chmod -R a+r /tmp/keys
б) Для старой версии (build)
Создаем сертификат для клиента:
* на все запросы отвечаем Enter.
В конце отвечаем на два вопроса утвердительно:
Certificate is to be certified until Aug 8 21:49:30 2031 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
Скопируем ключи во временную директорию:
cp keys/client1. keys/ca.crt keys/ta.key /tmp/keys/
Разрешим доступ на чтения всем пользователям:
chmod -R a+r /tmp/keys
Подготовка Ubuntu
Обновляем установленные пакеты:
apt-get update && apt-get upgrade
Устанавливаем утилиту для синхронизации времени:
apt-get install chrony
Разрешаем ее автозапуск и стартуем сервис:
systemctl enable chrony --now
Установим правильную временную зону:
timedatectl set-timezone Europe/Moscow
* в данном примере московское время.
Если в нашей системе используется брандмауэр, открываем порт, на котором будет слушать OpenVPN:
iptables -I INPUT -p udp --dport 443 -j ACCEPT
* в данной инструкции предполагается, что мы настроим VPN-сервер на UDP-порту 443, однако, по-умолчанию, OpenVPN работает на порту 1194.
Для сохранения правила используем iptables-persistent:
apt-get install iptables-persistent
Создание сертификатов
Создаем каталог, в котором разместим готовые сертификаты для OpenVPN:
mkdir -p /etc/openvpn/keys
Создаем каталог, в который будем помещать все сгенерированные сертификаты:
Переходим в созданный нами каталог:
Скопируем в него шаблоны скриптов для формирования сертификатов:
cp -r /usr/share/easy-rsa/* .
Чтобы ускорить процесс создания ключей, откроем на редактирование следующий файл:
и приведем его к следующему виду:
export KEY_COUNTRY="RU"
export KEY_PROVINCE="Sankt-Petersburg"
export KEY_CITY="Sankt-Petersburg"
export KEY_ORG="DMOSK COMPANY"
export KEY_EMAIL="master@dmosk.ru"
export KEY_CN="DMOSK"
export KEY_OU="DMOSK"
export KEY_NAME="name-openvpn-server.dmosk.ru"
export KEY_ALTNAMES="name-openvpn-server"
* где KEY_CN и KEY_OU: рабочие подразделения (например, можно указать название отдела); KEY_NAME: адрес, по которому будет выполняться подключение (можно указать полное наименование сервера); KEY_ALTNAMES — альтернативный адрес.
Запускаем отредактированный файл на исполнение:
Почистим каталог от старых сертификатов:
Для генерирования сертификатов необходим конфигурационный файл openssl.cnf — по умолчанию, он отсутствует, но есть файл openssl-1.0.0.cnf. Создаем на него симлинк:
ln -s openssl-1.0.0.cnf openssl.cnf
* в каталоге /etc/openvpn/easy-rsa может быть несколько разных версий конфигурационного файла openssl-x.x.x.cnf. Чтобы узнать точное имя файла, вводим команду ls /etc/openvpn/easy-rsa.
Следующие действия будут записеть от версии OpenVPN. Более новая позволяет создавать сертификаты на основе Easy RSA 3, старая работает на базе 2-й версии. Понять, какой вариант наш можно посмотрев на содержимое каталога easy-rsa:
Либо мы увидим в нем утилиту easyrsa (новая версия), либо набор утилит, начинающихся на build.
Рассмотрим процесс формирования сертификата с использованием как RSA3, так и RSA2.
а) Если используется новая версия (утилита easyrsa)
1. Инициализируем PKI:
2. Создаем корневой сертификат:
* после вводим дважды пароль.
На запрос «Common Name» можно просто нажать Enter:
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:
3. Создаем запрос на сертификат для сервера:
./easyrsa gen-req server nopass
* nopass можно упустить, если хотим повысить безопасность с помощью пароля на сертификат.
На запрос «Common Name» можно просто нажать Enter:
Common Name (eg: your user, host, or server name) [server]:
4. Генерируем сам сертификат:
./easyrsa sign-req server server
После ввода команды подтверждаем правильность данных, введя yes:
Type the word 'yes' to continue, or any other input to abort.
Confirm request details: yes
и вводим пароль, который указывали при создании корневого сертификата:
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:
Готово. Ключ для сервера создан.
5. Формируем ключ Диффи-Хеллмана:
Создаем ta-ключ командой:
openvpn --genkey --secret pki/ta.key
Скопируем созданные ключи в рабочий каталог:
cp pki/ca.crt /etc/openvpn/keys/
cp pki/issued/server.crt /etc/openvpn/keys/
cp pki/private/server.key /etc/openvpn/keys/
cp pki/dh.pem /etc/openvpn/keys/
cp pki/ta.key /etc/openvpn/keys/
б) Если используется старая версия (утилиты build-)
1. Генерируем последовательность центра сертификации:
На все запросы нажимаем Enter.
2. Запускаем build-dh.bat (сертификат с использованием алгоритма Диффи-Хеллмана):
* команда может выполняться долго — это нормально.
3. Генерируем сертификат для сервера:
* где server — имя сертификата; на все запросы нажимаем Enter.
В конце подтверждаем два раза корректность информации вводом y:
Certificate is to be certified until Aug 8 21:12:24 2031 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
Создаем ta-ключ командой:
openvpn --genkey --secret keys/ta.key
Скопируем созданные ключи в рабочий каталог:
cp keys/ca.crt /etc/openvpn/keys/
cp keys/server. /etc/openvpn/keys/
cp keys/dh2048.pem /etc/openvpn/keys/dh.pem
cp keys/ta.key /etc/openvpn/keys/
Установка
20 Comments
i got this error on openvpn server when connect
Tue Jan 30 13:31:15 2018 WARNING: cannot stat file ‘ta.key’: No such file or directory (errno=2)
Options error: –tls-auth fails with ‘ta.key’: No such file or directory (errno=2)
Options error: Please correct these errors.
Use –help for more information.
i got this error on openvpn server when connect
Tue Jan 30 13:31:15 2018 WARNING: cannot stat file ‘ta.key’: No such file or directory (errno=2)
Options error: –tls-auth fails with ‘ta.key’: No such file or directory (errno=2)
Options error: Please correct these errors.
Use –help for more information.
I confirm this solution as worked.
Do not forget to put these lines:
key-direction 0 (on server)
key-direction 1 (on client)
OpenVPN 2.3.11 (FreeBSD 10.3)
Great post, thank you very much.
I confirm this solution as worked.
Do not forget to put these lines:
key-direction 0 (on server)
key-direction 1 (on client)
OpenVPN 2.3.11 (FreeBSD 10.3)
Great post, thank you very much.
Thank you. This fixed the same problem when connecting to an OpenVPN server on a QNAP (TS239-PRO II) with the client running on Ubuntu server.
Thank you. This fixed the same problem when connecting to an OpenVPN server on a QNAP (TS239-PRO II) with the client running on Ubuntu server.
THANK YOU! I’ve been spending hours trying to figure out this issue… solved it thanks to your post!
THANK YOU! I’ve been spending hours trying to figure out this issue… solved it thanks to your post!
Darn that was good. Hours and hours of troubleshooting: removing keys, rebuilding keys, reinstalling openvpn, changing directories, client setting, server setting the whole lot, just to be your solution. Thank you!
Darn that was good. Hours and hours of troubleshooting: removing keys, rebuilding keys, reinstalling openvpn, changing directories, client setting, server setting the whole lot, just to be your solution. Thank you!
В данной инструкции подробно описан процесс настройки клиента OpenVPN на примере операционных систем Windows и Linux. Также, с ее помощью можно настроить скиента на Android.
Larger RSA keys
The RSA key size is controlled by the KEY_SIZE variable in the easy-rsa/vars file, which must be set before any keys are generated. Currently set to 1024 by default, this value can reasonably be increased to 2048 with no negative impact on VPN tunnel performance, except for a slightly slower SSL/TLS renegotiation handshake which occurs once per client per hour, and a much slower one-time Diffie Hellman parameters generation process using the easy-rsa/build-dh script.
Larger symmetric keys
By default OpenVPN uses Blowfish, a 128 bit symmetrical cipher.
OpenVPN automatically supports any cipher which is supported by the OpenSSL library, and as such can support ciphers which use large key sizes. For example, the 256-bit version of AES (Advanced Encryption Standard) can be used by adding the following to both server and client configuration files:
Возможные проблемы при работе с OpenVPN
На клиенте
Клиент OpenVPN может быть установлен на Windows, Linux, Android и Mac OS. Мы рассмотрим пример работы с Windows.
Заходим на официальную страницу загрузки openvpn и скачиваем клиента для Windows:
Запускаем скачанный файл и устанавливаем программу, нажимая «Далее».
Переходим в папку C:\Program Files\OpenVPN\config. И копируем в нее файлы ca.crt, client1.crt, client1.key, ta.key из каталога /tmp/keys на сервере, например, при помощи программы WinSCP.
После переноса файлов, не забываем удалить ключи из временного каталога на сервере:
Теперь возвращаемся к компьютеру с Windows, открываем блокнот от имени администратора и вставляем следующие строки:
client
resolv-retry infinite
nobind
remote 192.168.0.15 443
proto udp
dev tun
comp-lzo
ca ca.crt
cert client1.crt
key client1.key
tls-client
tls-auth ta.key 1
float
keepalive 10 120
persist-key
persist-tun
verb 0
* где 192.168.0.15 443 — IP-адрес OpenVPN-сервера и порт, на котором он принимает запросы.
* подробнее про настройку клиента OpenVPN.
Сохраняем файл с именем config.ovpn в папке C:\Program Files\OpenVPN\config.
Запускаем с рабочего стола программу «OpenVPN GUI» от имени администратора (это важно).
Нажимаем правой кнопкой по появившемуся в трее значку и выбираем «Подключиться»:
Произойдет подключение и значок поменяет цвет с серого/желтого на зеленый.
2. Постоянно разрывается соединение
Описание: с периодичностью от 1 до 5 минут постоянно рвется соединение с сервером. После нескольких минут переподключается.
Причина: как правило, конфликт IP-адресов. Такая ситуация возникает при случаях, когда подключение выполняется с нескольких компьютеров одновременно с одинаковыми данными авторизации (логином и паролем).
Решение: настройте клиента для подключения к серверу с уникальными логином и паролем.
Доступ к локальной сети
Для настройки доступа к локальной сети, воспользуйтесь инструкцией Настройка доступа к локальной сети клиентам OpenVPN в Linux.
Установка OpenVPN
Устанавливаем необходимые пакеты следующей командой:
apt-get install openvpn easy-rsa
chroot (non-Windows only)
The chroot directive allows you to lock the OpenVPN daemon into a so-called chroot jail, where the daemon would not be able to access any part of the host system's filesystem except for the specific directory given as a parameter to the directive. For example,
would cause the OpenVPN daemon to cd into the jail subdirectory on initialization, and would then reorient its root filesystem to this directory so that it would be impossible thereafter for the daemon to access any files outside of jail and its subdirectory tree. This is important from a security perspective, because even if an attacker were able to compromise the server with a code insertion exploit, the exploit would be locked out of most of the server's filesystem.
Caveats: because chroot reorients the filesystem (from the perspective of the daemon only), it is necessary to place any files which OpenVPN might need after initialization in the jail directory, such as:
- the crl-verify file, or
- the client-config-dir directory.
Пример конфигурационного файла
client
dev tun
proto udp
remote 192.168.0.15 443
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client.crt
key client.key
dh dh2048.pem
tls-client
tls-auth ta.key 1
float
keepalive 10 120
comp-lzo
verb 0
Статические IP для клиентов
На сервере для каждого клиента генерируем свой сертификат. Например, для client2 вводим следующие команды:
После чего переходим к каталог keys, где находятся новые сертификаты и копируем их на клиентский компьютер. Полный список файлов, которые необходимо копировать:
- ca.crt
- client2.crt
- client2.key
- dh2048.pem
- ta.key
Также на сервере открываем следующий файл и заносим статический адрес для клиента:
* в данном примере клиент client будет получать IP 172.16.10.4, а client2 — 172.16.10.24.
В конфигурационном файле server.conf должна быть строчка:
systemctl restart openvpn@server
Теперь на клиенте не забываем указать правильные названия файлов в конфигурационном файле клиента:
cert client2.crt
key client2.key
proto udp
While OpenVPN allows either the TCP or UDP protocol to be used as the VPN carrier connection, the UDP protocol will provide better protection against DoS attacks and port scanning than TCP:
Настройка OpenVPN-сервера
Создаем конфигурационный файл:
И вставляем в него следующее:
local 192.168.0.15
port 443
proto udp
dev tun
ca keys/ca.crt
cert keys/server.crt
key keys/server.key
dh keys/dh.pem
tls-auth keys/ta.key 0
server 172.16.10.0 255.255.255.0
ifconfig-pool-persist ipp.txt
keepalive 10 120
max-clients 32
persist-key
persist-tun
status /var/log/openvpn/openvpn-status.log
log-append /var/log/openvpn/openvpn.log
verb 4
mute 20
daemon
mode server
tls-server
comp-lzo
- local — IP-адрес, на котором будет обрабатывать запросы OpenVPN;
- port — сетевой порт (443 позволит избежать проблем при использовании Интернета в общественных местах, но может быть любым из свободных. Порт 1194 является стандартным для OpenVPN).
- proto — используемый транспортный протокол.
- dev — виртуальный сетевой адаптер, который будет создан для работы OpenVPN.
- ca — путь до сертификата корневого центра сертификации.
- cert — путь до открытого сертификата сервера.
- key — путь до закрытого сертификата сервера.
- dh — путь до ключа Диффи - Хеллмана.
- tls-auth — путь до tls-ключа.
- server — задаем IP-адрес сервера в сети VPN.
- ifconfig-pool-persist — путь к файлу для хранения клиентских IP-адресов.
- keepalive X Y — каждые X секунд отправляется ping-запрос на удаленный узел. Если за Y секунд не получено ответа — перезапускать туннель.
- max-clients — максимум одновременных подключений.
- persist-key — не перезагружать ключи при повторной загрузки из-за разрыва соединения.
- persist-tun — не изменять устройства tun/tap при перезапуске сервера.
- status — путь до журнала статусов.
- log-append — путь до файла лога с дополнительным выводом информации.
- verb — уровень логирования событий. От 0 до 9.
- mute — ограничение количества подряд отправляемых в лог событий.
- daemon — работа в режиме демона.
- mode — в каком режиме работает openvpn (сервер или клиент).
- tls-server — указывает, что данный сервер работает с использованием TLS.
- comp-lzo — использовать сжатие.
Создадим каталог для логов:
Разрешаем автоматический старт сервиса vpn и запускаем его:
systemctl enable openvpn@server --now
Автоматический запуск клиента
Если необходимо, чтобы клиент OpenVPN запускался при старте операционной системы Windows и подключался к серверу, просто открываем службы и находим OpenVPNService. Переводим его в режим автозапуска:
Linux CentOS
Устанавливаем репозиторий EPEL:
yum install epel-release
yum install openvpn
Настройка на клиенте
В конфигурационный файл клиента добавляем:
Можно пробовать подключаться.
Если необходимо настроить авторизацию, но автоматизировать вход клиента, открываем конфигурационный файл последнего и строку для авторизации меняем на:
* где auth.txt — файл, в котором мы будем хранить логин и пароль.
Создаем текстовый файл auth.txt в той же папке, где находится файл конфигурации со следующим содержимым:
* где username — логин пользователя, а password — пароль.
Описанный метод аутентификации является базовым и требует наличие обычной системной учетной записи. Если необходима более сложная авторизация на базе LDAP, можно воспользоваться инструкцией
Настройка
После установки программы конфигурационный файл не создается автоматически и его нужно создать вручную.
В системах Windows создаем файл config.ovpn в папке %programfiles%\OpenVPN\config.
* имя файла может быть любым, расширение должно быть .ovpn.
Для создания конфигурационного файла в Linux выполняем команду:
* чтобы служба openvpn автоматически выполняла соединение, необходимо, чтобы конфигурационный файл назывался client.conf.
Linux Ubuntu
apt-get install openvpn
Windows
Заходим на официальную страницу загрузки openvpn и скачиваем клиента для нужной Windows:
Запускаем скачанный файл и устанавливаем программу, нажимая «Далее».
1. failed to start openvpn robust and highly flexible tunneling application on server
Описание: при запуске сервера получаем данную ошибку.
Причина: как правило, связано с отсутствием сертификата.
Решение: открываем лог /var/log/openvpn/openvpn.log и смотрим, с каким сертификатом проблема. Проверяем, что все файлы скопированы и что мы не забыли сгенерировать все сертификаты.
Unprivileged mode (Linux only)
On Linux OpenVPN can be run completely unprivileged. This configuration is a little more complex, but provides best security.
In order to work with this configuration, OpenVPN must be configured to use iproute interface, this is done by specifying --enable-iproute2 to configure script. sudo package should also be available on your system.
This configuration uses the Linux ability to change the permission of a tun device, so that unprivileged user may access it. It also uses sudo in order to execute iproute so that interface properties and routing table may be modified.
- Write the following script and place it at: /usr/local/sbin/unpriv-ip:
- Execute visudo, and add the followings to allow user 'user1' to execute /sbin/ip:
- Add the following to your OpenVPN configuration:
- Run OpenVPN in the context of the unprivileged user.
-
Please note that you must select constant X and specify tun or tap not both.
Further security constraints may be added by examining the parameters at the /usr/local/sbin/unpriv-ip script.
Сертификаты
Клиентские сертификаты генерируются на стороне сервера. Процедура следующая.
Читайте также:
-
You can also enable a group of users with the following command: