- Настройка OpenVPN клиента
- Установка
- Windows
- Linux CentOS
- Linux Ubuntu
- Android
- Настройка
- Пример конфигурационного файла
- Параметры конфигурационного файла
- Сертификаты
- Есть ли OpenVPN GUI для Linux?
- OpenVPN 3 Client for Linux
- Background
- Installation as Connector for OpenVPN Cloud
- Installation for Debian and Ubuntu
- Installation for Fedora, Red Hat Enterprise Linux, CentOS, or Scientific Linux
- Using .ovpn Profile
- Mandatory Commands
- Optional Commands
- Managing a Running Session
- Changing the OpenVPN Profile of an Autoloading VPN Session
Настройка 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).
Сертификаты
Клиентские сертификаты генерируются на стороне сервера. Процедура следующая.
Источник
Есть ли OpenVPN GUI для Linux?
Название статьи подсказала тема на одном из форумов. Несмотря на то, что с момента возникновения вопроса прошло шесть лет, в этом направлении мало что изменилось. А поскольку в последнее время у меня на слуху постоянно был OpenVPN, то было решено исправить данную ситуацию. Так родилась графическая утилита VpnGUI для создания, редактирования, запуска и контроля выполнения утилиты openvpn.
После запуска утилиты VpnGUI в трее появится иконка (квадрат разбитый на четыре сине-красных квадратика) утилиты:
Трей имеет меню, которое появляется при нажатии правой клавиши мышки, когда курсор мышки находится на трее утилиты VPNGui. Меню имеет два пункта – Restore (развернуть окна) и Stop (завершить работу ). После выбора пункта меню «Restore» на экране появится главное окно утилиты VPNGui:
Разработка велась на python с использованием графического пакета Tkinter и дизайнера Page.
Напомним, что для использования «великого, могучего, правдивого и свободного русского языка!» (И.С. Тургенев), необходимо добавить в файл файл gui_pyton_gen.tcl дизайнера Page после 418 строки следующий код:
Аналогичный код необходимо дабавить также в файл support_python_gen.tcl (после 458 строки).
Для программирования трея был установлен пакет Pystray.
Работа утилиты начинается с выбора пользователем выполняемого файла openvpn или его форков. Утилита проверяет наличие выполняемого файла и заполняет списки перечнем поддерживаемых mac (алгоритмя контроля целостности), ciphers (алгоритмы шифрования) и перечнем поддерживаемых шифрсьютов:
Теперь можно приступать к работе с конфигурационным файлом. Пользователь может создать новый файл или отредактировать существующий, предварительно загрузив его (см. скриншот). После того как файл загружен или новый файл сохранен, пользователь может запустить openvpn:
После ввода пароля в окне «Протокол работы» будут отображаться диагностические сообщения OpenVPN:
До тех пор пока openvpn нормально работает книопка «VPN активен» будет блокирована. Если openvpn по каким-то причинам завершит свою работу или будет остановлен пользователем (кнопка «Стоп VPN»), то кнопка разблокируется и снова станет кнопкой «Старт VPN».
Отметим, что для выпуска клиентских и серверных сертификатов для OpenVPN удобно использовать центр сертификации XCA:
Теперь, когда openvpn нормально работает, можно его убрать в трей. Для этого можно использовать как кнопку «В трей» на окне «Протокол работы» или меню главного окна (Manager → Убрать в трей):
Утилита плафтормонезависима. Бинарный код утилиты можно получить, используя пакет Nuitka.
Источник
OpenVPN 3 Client for Linux
Background
The OpenVPN 3 Linux project is a new client built on top of the OpenVPN 3 Core Library, which is also used in the various OpenVPN Connect clients and OpenVPN for Android (need to be enabled via the settings page in the app).
This client is built around a completely different architecture in regards to usage. It builds heavily on D-Bus and allows unprivileged users to start and manage their own VPN tunnels out-of-the-box. System administrators wanting more control can also control and restrict this access both by hardening the default OpenVPN 3 D-Bus policy or facilitating features in OpenVPN 3 Linux.
Even though the project name carries “Linux”, it doesn’t mean it is restricted to Linux only. Any platform which has D-Bus available should be capable of running this client in theory. But since D-Bus is most commonly used in Linux environments, this will naturally be the primary focus for the project.
The release notes are stored in git tags in the project git repository. They can also be viewed here: https://github.com/OpenVPN/openvpn3-linux/releases (expand the tag to see the full text)
Installation as Connector for OpenVPN Cloud
Installation of OpenVPN 3 client as a Connector for OpenVPN Cloud Host or Network has been simplified and documented here.
Installation for Debian and Ubuntu
Follow these steps in order to install OpenVPN 3 Client on Linux for Debian and Ubuntu:
Open the Terminal by pressing ctrl + alt + T
Type the following command into the Terminal: sudo apt install apt-transport-https . This is done to ensure that your apt supports the https transport. Enter the root password as prompted
Type the following command into the Terminal: sudo wget https://swupdate.openvpn.net/repos/openvpn-repo-pkg-key.pub . This will install the OpenVPN repository key used by the OpenVPN 3 Linux packages
Type the following command into the Terminal: sudo apt-key add openvpn-repo-pkg-key.pub
Type the following command into the Terminal: sudo wget -O /etc/apt/sources.list.d/openvpn3.list https://swupdate.openvpn.net/community/openvpn3/repos/openvpn3-$DISTRO.list . This will install the proper repository. Replace $DISTRO with the release name depending on your Debian/Ubuntu distribution (the table of release names for each distribution can be found below). In this case, focal is chosen since Ubuntu 20.04 is used
Type the following command into the Terminal: sudo apt update
Type the following command into the Terminal: sudo apt install openvpn3 . This will finally install the OpenVPN 3 package
Distribution | Release | Release name ($DISTRO) |
---|---|---|
Debian | 9 | stretch |
Debian | 10 | buster |
Ubuntu | 16.04 | xenial |
Ubuntu | 18.04 | bionic |
Ubuntu | 19.10 | eoan |
Ubuntu | 20.04 | focal |
Installation for Fedora, Red Hat Enterprise Linux, CentOS, or Scientific Linux
Packages for these distributions are provided via a Fedora Copr repository. Supported versions:
Distribution | Release versions |
---|---|
Fedora | 30, 31, 32 |
Red Hat Enterprise Linux / CentOS | 7, 8 |
In order to install the OpenVPN 3 Client for Fedora, Red Hat Enterprise Linux, CentOS, or Scientific Linux, follow the steps below:
- Open Terminal by typing terminal into the search bar
- If you are running Red Hat Enterprise Linux or its clones, you need to install the Fedora EPEL repository first. Here is the list of commands for each version:
(The original article on Fedora EPEL can be found here)
RHEL/CentOS 6: sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
RHEL/CentOS 7: sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
On RHEL 7 it is recommended to also enable the optional, extras, and HA repositories since EPEL packages may depend on packages from these repositories: sudo subscription-manager repos —enable «rhel-*-optional-rpms» —enable «rhel-*-extras-rpms» —enable «rhel-ha-for-rhel-*-server-rpms»
RHEL/CentOS 8: sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
On RHEL 8 it is required to also enable the codeready-builder-for-rhel-8-$-rpms repository since EPEL packages may depend on packages from it: sudo ARCH=$( /bin/arch ) followed by sudo subscription-manager repos —enable «codeready-builder-for-rhel-8-$ -rpms»
On CentOS 8 it is recommended to also enable the PowerTools repository since EPEL packages may depend on packages from it: sudo dnf config-manager —set-enabled PowerTools - You need to install the yum copr module first by running the following command: sudo yum install yum-plugin-copr . Note: Fedora releases usually have the yum/dnf copr module preinstalled.
- With the Copr module available, it is time to enable the OpenVPN 3 Copr repository by running the following command: sudo yum copr enable dsommers/openvpn3
- Finally, the OpenVPN 3 Linux client can be installed by running the following command: sudo yum install openvpn3-client
Using .ovpn Profile
Please note that by this point you should have downloaded a .ovpn profile to your machine.
Mandatory Commands
In order to start a one-shot configuration profile, type the following command into the Terminal: openvpn3 session-start —config $
In order to import a configuration file for re-use and start a VPN session, type the following command into the Terminal: openvpn3 config-import —config $
In order to start a new VPN session from an imported configuration profile, run the following command: openvpn3 session-start —config $
Optional Commands
- To list all available configuration profiles, run this command: openvpn3 configs-list . Important: a configuration file typically contains generic options to be able to connect to a specific server, regardless of the device itself. OpenVPN 3 Linux also supports setting more host-specific settings on a configuration profile as well. This is handled via the `openvpn3 config-manage` interface. Any settings here will also be preserved across boots if the configuration profile was imported with the —persistent argument.
- Note that it is possible to use the D-Bus path to the configuration profile: openvpn3 session-start —config-path /net/openvpn/v3/configuration/. . Note: in either of these cases is it necessary to have access to the configuration profile on disk. As long as configuration profiles are available via openvpn3 configs-list , all needed to start a VPN session should be present.
Managing a Running Session
- Once a VPN session has started, it should be seen in the session list: openvpn3 sessions-list
- Using the openvpn3 session-manage there are a few things which can be done, but most typically it is the –disconnect or –restart alternatives which are most commonly used. openvpn3 session-manage —config $
—restart . This disconnects and re-connects to the server again, re-establishing the connection. The $ is the configuration name as displayed in openvpn3 sessions-list - It is also possible to use the D-Bus path to the session as well: openvpn3 session-manage —session-path /net/openvpn/v3/sessions/. —disconnect . This command above will disconnect a running session. Once this operation has completed, it will be removed from the openvpn3 sessions-list overview. Important: you will be able to start a new session with this or another OpenVPN profile only after you have disconnected from the current session using the command in this step
- It is also possible to retrieve real-time tunnel statistics from running sessions: openvpn3 session-stats —config $
or openvpn3 session-stats —session-path /net/openvpn/v3/sessions/. - And to retrieve real-time log events as they occur, run the following command: openvpn3 log —config $
. This might be quite silent, as it does not provide any log events from the past. Issue an openvpn3 session-manage –restart from a different terminal, and log events will occur. You may want to boost the log-level with –log-level 6. Valid log levels are from 0 to 6, where 6 is the most verbose. Note: VPN sessions are also owned by the user which started it. But the Session Manager also provides its own Access Control List feature via openvpn3 session-acl
Changing the OpenVPN Profile of an Autoloading VPN Session
Please note that every time you start a session, it will load automatically on the system start-up. In order to change the profile of an OpenVPN Session that is autoloaded, follow the steps below:
Источник