Linux openvpn client systemctl

Настройка OpenVPN клиента

В данной инструкции подробно описан процесс настройки клиента OpenVPN на примере операционных систем Windows и Linux. Также, с ее помощью можно настроить скиента на Android.

Установка

Windows

Заходим на официальную страницу загрузки openvpn и скачиваем клиента для нужной Windows:

Запускаем скачанный файл и устанавливаем программу, нажимая «Далее».

Linux CentOS

Устанавливаем репозиторий EPEL:

yum install epel-release

yum install openvpn

Linux Ubuntu

apt-get install openvpn

Android

Установка выполняется из Google Play. Набираем в поиске OpenVPN Connect — нажимаем установить и принимаем условия.

Настройка

После установки программы конфигурационный файл не создается автоматически и его нужно создать вручную.

В системах Windows создаем файл config.ovpn в папке %programfiles%\OpenVPN\config.

* имя файла может быть любым, расширение должно быть .ovpn.

Для создания конфигурационного файла в Linux выполняем команду:

* чтобы служба openvpn автоматически выполняла соединение, необходимо, чтобы конфигурационный файл назывался client.conf.

Пример конфигурационного файла

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

Параметры конфигурационного файла

Параметр Значения Описание
client Строка говорит о том, что конфигурационный файл описывает клиентское подключение (программа сама устанавливает соединение, а не ждет, как сервер).
dev tap или tun Выбор виртуального сетевого драйвера. TUN — сетевой уровень модели OSI, оперирует IP-пакетами. TAP — эмулирует Ethernet устройство и работает на канальном уровне модели OSI, оперируя кадрами Ethernet. Настраивая OpenVPN клиента, в большинстве случаев, необходимо выбирать tun. TAP необходимо использовать для работы определенных сервисов, например DHCP.
dev-node любая строка Параметр используется в системах Windows в случаях, если имеется несколько сетевых интерфейсов. Значение этого параметра должно содержать название сетевого подключения, через который должен работать OpenVPN.
proto udp или tcp Указывает, какой протокол использовать для передачи данных. В большинстве случаев, лучше использовать UDP, так как данный протокол создает меньше нагрузки на сеть.
remote VPN-сервер и порт Задает сервер, к которому должен подключаться клиент, а также сетевой порт (по умолчанию 1194), на котором OpenVPN принимает запросы. Можно указать несколько строк.
remote-random Если указано несколько строк remote, данный параметр говорит, что необходимо подключаться к удаленным серверам в случайном порядке.
resolv-retry количество секунд или infinite Используется в тех случаях, когда в качестве сервера указано доменное имя. Параметр задает время в секундах для повторного переподключения, если не удалось узнать имя сервера. infinite — держать связь с сервером постоянно.
nobind Клиент использует динамический порт для подключения.
user учетная запись Задает определенного пользователя для работы клиента (только для UNIX-систем).
group группа Задает определенную группу для работы клиента (только для UNIX-систем).
persist-key Не перечитывает ключи при перезагрузке сервиса OpenVPN.
persist-tun Не перечитывает параметры туннеля при перезагрузке сервиса OpenVPN.
http-proxy сервер прокси и порт Использовать прокси-сервер для подключения.
http-proxy-retry Переподключаться к прокси-серверу, если связь была разорвана.
http-proxy-timeout количество секунд Время, через которое выполнять попытки переподключения к прокси-серверу.
mute-replay-warnings Параметр стоит задавать при использовании беспроводного соединения. Он отключит дублирование предупреждений пакетов.
ca пут к сертификату Корневой сертификат удостоверяющего центра. Генерируем на сервере.
cert пут к сертификату Открытый ключ клиента. Генерируем на сервере.
key пут к сертификату Закрытый ключ клиента. Генерируем на сервере.
dh пут к сертификату Ключ с алгоритмом Diffie-Hellman (Диффи-Хеллмана).
remote-cert-tls сервер Исключает возможность mitm атаки, включая верификацию сертификата сервера.
tls-client Указание на то, что это клиент TLS.
tls-auth ta.key 1 Дополнительный уровень аутентификации посредством ключа TLS.
float Удаленный хост может менять IP-адрес в процессе соединения, при этом последнее не будет разорвано.
keepalive секунд1 секунд2 Пинговать каждые секунд1 сервер и если в течение секунд2 не будут получены ответные пакеты, перезапустить подключение.
cipher алгоритм Указывает алгоритм шифрования. Примеры: AES-256-CBC, AES-128-CBC, BF-CBC, DES-EDE3-CBC.
comp-lzo Использовать сжатие.
verb число от 0 до 9 Уровень детализации лога. 0 отключает отладочную информацию.
mute число Указывает сколько лог-сообщений может отображаться для каждой категории события.
auth-user-pass ничего или путь к файлу Говорит клиенту, что необходима аутентификация. Если не указан путь к файлу, клиент выкинет окно для авторизации, иначе прочитает данные из файла.
ipchange команда или путь к скрипту Выполняет команду при смене IP.
connect-retry секунд Переподключиться к серверу через указанное количество секунд, если соединение было разорвано.
connect-retry-max число Сколько раз повторять соединение, если оно было разорвано.
shaper байт Задает максимальную скорость передачи данных для исходящего трафика.
tun-mtu число Задает MTU.
status путь к файлу Путь к фалу хранения статуса.
log путь к файлу Путь к лог-файлу.
askpass путь к файлу Путь к файлу с паролем для приватного ключа (private key password).

Наиболее полный и актуальный список параметров для OpenVPN можно получить командой openvpn —help (в Linux и Windows).

Сертификаты

Клиентские сертификаты генерируются на стороне сервера. Процедура следующая.

Источник

Help Center

In order to configure OpenVPN to autostart for systemd, complete the following steps:

Run the command:

and uncomment, or remove, the “#” in front of

then press ‘Ctrl X’ to save the changes and exit the text editor.

Move the .ovpn file with the desired server location to the ‘/etc/openvpn’ folder:

Edit the .ovpn file you copied in the previous step and change the line ‘auth-user-pass’ to ‘auth-user-pass pass’:

then press ‘Ctrl X’ to save the changes and exit the text editor.

In the ‘/etc/openvpn’ folder, create a text file called pass:

and enter your IVPN Account ID (starts with ‘ivpn’) on the first line and any non-blank text on the 2nd line, then press ‘Ctrl X’ to save the changes and exit the text editor.

(Optional) Change the permissions on the pass file to protect the credentials:

Rename the .ovpn file to ‘client.conf’:

On Ubuntu 16.04 LTS, OpenVPN installs and initiates a service by default. If you are using Ubuntu 16.04 LTS, skip to step 10.
For Ubuntu 18.04 LTS and up, enable the OpenVPN service to run while booting:

Reload the daemons:

Start the OpenVPN service:

Reboot and test if it is working by checking the external IP:

If curl is not installed:

Still have questions?

Get in touch and we’ll get back to you in a few hours.

Interested in privacy?

Read our latest privacy news and keep up-to-date on IVPN services.

Источник

Correct way of systemd for OpenVPN client on 16.04 Server?

I’m about to upgrade from 14.04 LTS to 16.04 LTS, but first I need to sort out the systemd services for most important software I use, like OpenVPN client. I have a perfectly working upstart script for 14.04.

I read a lot about systemd, but have no too much experience. From another post I also understand the following:

OpenVPN is a templatized service under systemd. The services are named openvpn@config.service. So you should be starting your /etc/openvpn/myvpn.conf instance with

systemctl start openvpn@myvpn.service

I compile OpenVPN Client. I just don’t get this, is openvpn@myvpn.service automatically generated, or how? Further to this, how can I add Restart settings (or any other) to this service, in this case openvpn@myvpn.service? I would like to add

Setting this to on-failure is the recommended choice for long-running services, in order to increase reliability by attempting automatic recovery from errors. For services that shall be able to terminate on their own choice (and avoid immediate restarting), on-abnormal is an alternative choice.

My aim is to OpenVPN client to restart always if not stopped by me.

2 Answers 2

Regarding the «openvpn@myvpn.service» part of your question, another example: I have an OpenVPN configuration file named /etc/openvpn/Germany.conf so I start the openvpn daemon with systemctl start openvpn@Germany.service . This is my default config, so it goes into /etc/default/openvpn .

In case my german gateway is down, I have another configuration file /etc/openvpn/Netherlands.conf and to use that I call systemctl start openvpn@Netherlands.service

Regarding the Restart setting, this probably goes into the [Service] section of /etc/systemd/system/multi-user.target.wants/openvpn.service though I haven’t tested that myself.

Note: The above assumes that you use the Ubuntu package via apt-get install openvpn . I’m not sure what happens when you compile the stuff yourself? Also: Why would you do that?

Further to this, how can I add Restart settings (or any other) to this service, in this case openvpn@myvpn.service?

Along with a unit file foo.service, a «drop-in» directory foo.service.d/ may exist. All files with the suffix «.conf» from this directory will be parsed after the file itself is parsed. This is useful to alter or add configuration settings for a unit, without having to modify unit files. Each drop-in file must have appropriate section headers. Note that for instantiated units, this logic will first look for the instance «.d/» subdirectory and read its «.conf» files, followed by the template «.d/» subdirectory and the «.conf» files there. Also note that settings from the «[Install]» section are not honored in drop-in unit files, and have no effect.

In addition to /etc/systemd/system, the drop-in «.d» directories for system services can be placed in /usr/lib/systemd/system or /run/systemd/system directories. Drop-in files in /etc take precedence over those in /run which in turn take precedence over those in /usr/lib. Drop-in files under any of these directories take precedence over unit files wherever located.

Based on above, if you had more than one openvpn configuration and you would like to alter some aspect of configuration for all openvpn services based on these configurations you would need to create /etc/systemd/openvpn@.service.d directory and place there appropriate .conf files.

Источник

How to auto start openvpn (client) on Ubuntu CLI?

I’m using Ubuntu 12.04 64bit. I have an *.ovpn file that works if I type:

Now I would like to start up openvpn when I boot the computer.

How can I do this?

4 Answers 4

Download the OpenVPNConfigFile.ovpn . Note that you can rename the file to anything you like.

Move the ovpn file to /etc/openvpn

cd /etc/openvpn folder and enter sudo nano yourserver.txt

sudo nano OpenVPNConfigFile.ovpn

Find auth-user-pass and add yourserver.txt next to it so that it becomes

This will allow you to skip entering your credentials everytime you start openvpn connection

Rename OpenVPNConfigFile.ovpn to OpenVPNConfigFile.conf

sudo nano /etc/default/openvpn

sudo service openvpn start

You should see a message saying that you are connected. The connection will be established every time you start your computer.

The openvpn package comes with an init script /etc/init.d/openvpn . This script automatically sets up connection for every .conf (mind the extension) file in /etc/openvpn .

If you install OpenVPN via an RPM or DEB package on Linux, the installer will set up an initscript. When executed, the initscript will scan for .conf configuration files in /etc/openvpn, and if found, will start up a separate OpenVPN daemon for each file.

I got a bit stuck on this and ended up writing out all of the instructions for setting it up with systemd manually.

This worked for me using Ubuntu 16.10 and openvpn 2.3.11

Setting up your vpn to run from bash

These examples use expressvpn but most would work the same way

Download your vpn provider’s ovpn config file e.g. my_express_vpn_amsterdam_2.ovpn

move that to /etc/openvpn/ and rename it to end in .conf

Your VPN provider will provide you with a username and password for connecting over openvpn. Save the userename and then password each on their own line

now edit /etc/openvpn/amsterdam-2.conf look for a line that says auth-user-pass and replace it with the path to your credential file

Test your config! Start openvpn like this

openvpn should connect without asking for username or password

Remove existing (broken) service config for openvpn

Set up openvpn to run as a systemd service

The config that came with openvpn was broken so I removed it and created a new one based on this answer

Create systemd service for openvpn

add this config:

the %i is used as a wildcard so that this service can be used for multiple vpn configurations. Set it up for the amsterdam-2.conf file that we created earlier

the systemd service should now be running on the amsterdam vpn. check its status like so

you should see several lines of output ending in Initialization Sequence Completed and your vpn should be running.

Источник

Читайте также:  Windows virtual machine hyper v
Оцените статью