- linux-notes.org
- Установка OpenVPN клиента на CentOS/RedHat/Fedora
- linux-notes.org
- Установка openvpn на RedHat/CentOS/Fedora
- Создадим параметр Диффи Хеллмана
- Удаление доступа клиентов к серверу VPN
- Настройка VPN сервера
- IP экспедирование(forwarding) и маршрутизация (routing) конфигурации
- Конфигурация OpenVPN на стороне клиента
- Install OpenVPN on Fedora 26
- NB! server corresponts with the configuration file name in /etc/openvpn/server such as server.conf. So if you have myserver.conf you have to replace server with myserver
- Client setup
- 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
linux-notes.org
Установка OpenVPN клиента на CentOS/RedHat/Fedora
Недавно я рассказывал в своей статье «Установка openvpn на RedHat/CentOS/Fedora» как установить OpenVPN сервер для CentOS, Fedora или RedHat, а сейчас, в своей новой статье «Установка OpenVPN клиента на CentOS/RedHat/Fedora» я хотел бы рассказать как же установить OpenVPN клиент и подключиться к серверу.
1. Для начала стоит прочитать и установить OpenVPN сервер, вот вам хороший и подробный мануал:
Установка openvpn на RedHat/CentOS/Fedora
2. Введите следующую команду из терминала для установки OpenVPN пакета для вашей машины:
Как говорилось в статье о настройке и установке OpenVPN, что нужно скопировать ключи, НЕ ЗАБЫВАЕМ ЭТО СДЕЛАТЬ:
Эти сертификаты тоже необходимо скачать на машину клиента:
Качаем ключ для клиента ( мы его генерировали, когда устанавливали сервер с OpenVPN):
Тек же скачиваем и сам конфиг с клиентом:
Проверяем его на ошибки:
Если все хорошо, то он начнет проверять все и выдаст много информации, а если у вас будут ошибки, то читаем в интернете и фиксим. Думаю что их не должно быть, я же все проверял на своей машине =)
После установки OpenVPN, запустите службу и сделайте так чтобы для автоматически она запускалась при каждой перезагрузке вашей ОС:
Теперь проверьте, tun0 (интерфейс VPN) создается:
Смотрим что нам выдаст, если все хорошо, то должен появится сетевой интерфейс tun ( у меня это tun0 с таким вот ИП адресом 10.8.0.6, собственно на сервере у меня 10.8.0.1). Чтобы окончательно проверить работу клиент-сервера, то выполните пинг:
ПРИМЕЧАНИЕ! Не забываем скопировать все нужные файлы на вашу машину ( я описывал что нужно скопировать в статье об установке OpenVPN).
После того как убедитесь что нормально вывелось в ifconfig-е, попробуйте пингануть OpenVPN сервер.
Источник
linux-notes.org
Установка openvpn на RedHat/CentOS/Fedora
OpenVPN является полнофункциональной утилитой с открытыми исходниками для решение VPN, что позволяет использовать широкий диапазон конфигураций, в том числе удаленного доступа, Wi-Fi безопасности и многое другое. OpenVPN предлагает экономическое и эффективное решение — это альтернативное решение других технологий VPN, которая целенаправленна для разных предприятий. В статье «Установка openvpn на RedHat/CentOS/Fedora» хотел бы рассказать как можно объединить группу компьютеров двух или более разных сетей для совместного использования на примере установки openVPN для RedHat, CentOS а так же для Fedora.
И так имеем, у меня есть сервер на которой установлена ОС — CentOSи у нее имеется ИП адрес 78.140.189.243. На этот сервер мы сейчас и установим наш OpenVPN сервер.
До всей установки нужно подключить repo EPEL:
1. Устанавливаем OpenPN сервер, к нему и будем подключаться ( на том компьютере с которого мы будем подключаться мы установим клиентскую ее часть, но об этом немного попозже):
Как только все установится нужно скопировать файлы в созданную папку:
Но это уже не работает в новых версиях OpenVPN (в него уже не входит этот пакет), по этому нужно сделать «финт ушами», по этому мы установим вручную:
После этого мы создаем папку и скопируем нужные данные в нее:
После того как мы скопировали нужные для работы файлы, нам еще нужно сгенерировать ключики и так же сертификаты, делаем по следующей схеме:
Переходим в директорию и начнем работу:
Введите следующие команды для инициализации центра сертификации:
Затем выполните следующую команду, чтобы создать сертификат и ключ CA:
Нас попросят ввести данные ( но нам это не интересно, т.к мы это все уже прописать немного выше), но мы просто на каждый вопрос нажимаем «Enter»
Далее создаем сертификат и ключик для моего сервера my_server:
Нас просят ввести кое какие данные, я привел то что нужно нажимать на следующем скриншоте:
Создадим сертификат и ключ для VPN клиентов:
Если вы хотите создать сертификат и файлы ключей для каждого клиента, вы должны заменить параметр клиента своим уникальным идентификатором! Но т.к я буду использовать его сам, то мне хватит и 1 клиентского сертификата.
Отвечаем на вопросы точно так же как и на предыдущем рисунке:
Создадим параметр Диффи Хеллмана
Введите следующую команду, чтобы создать параметр DH:
Запустится генерация и это займет определенное время ( не более 1 мин).
Нужные ключики и сертификаты будут генерироваться в /etc/openvpn/easy-rsa/keys/. Скопируйте следующие сертификаты и файлы ключей в каталог/etc/openvpn/:
Чтобы это сделать, перейдите в папку и скопируем все это:
И потом, вы должны скопировать все сертификаты клиентов и ключики к удаленным клиентам VPN для аутентификации на сервере VPN. В нашем случае, мы сформировали сертификаты и ключи только для одного клиент, поэтому мы должны скопируйте следующие файлы клиенту VPN:
Убедитесь, что вы установили OpenVPN пакет на клиентских системах. Затем скопируйте вышеуказанные файлы в вашу систему VPN клиента, выполняем:
Или можно это сделать по отдельности!
Если не знаете как пользоваться SCP, то следующий материал поможет Вам:
Удаление доступа клиентов к серверу VPN
Если вы хотите удалить доступ пользователя(ей) к серверу VPN, введите и выполните:
Эти команды служат для удаления пользователей, которые имеют сертификаты для доступа к серверу VPN.
Настройка VPN сервера
Теперь, мы должны настроить наш сервер VPN. Скопируйте файл server.conf в /etc/openvpn/, для этого выполните:
Сейчас отредактируем данный конфигурационный файл и настроим мы его под себя:
Сохраните и закройте файл.
ПС: Если у Вас не будет что то работать, то проверьте правильность ключей ( именно их расположение) и если что пропишите полный путь к ключам. Можно проверить работоспособность нашего конфига, для этого служит следующая команда:
Тогда нам нужно скопировать и отредактировать файл client.conf. Этот файл должны быть передан в VPN клиентам. Во-первых скопируйте файл в любое место (напр./home/your_user/ ).
И сейчас я его поправлю:
ПС: Если у Вас не будет что то работать, то проверьте правильность ключей ( именно их расположение) и если что пропишите полный путь к ключам.
Здесь 78.140.189.243 мой IP адрес сервера VPN. Затем Скопируйте файл client.conf на машину клиента:
IP экспедирование(forwarding) и маршрутизация (routing) конфигурации
Нужно отредактировать sysctl.conf и внести некоторые изменения:
Найдите следующую строку и установить значение «1», чтобы включить переадресацию IP.
Выполните следующую команду, чтобы применить изменения Sysctl:
Отрегулируйте IPTables для передачи трафика через VPN должным образом, для этого введите следующие команды один за другим:
Сохраните изменения в IPTABLES с помощью:
После чего перезапускаем:
Наконец, запустите сервис OpenVPN и сделайте чтобы стартавал при запуске вашей ОС:
В это время, вы должны иметь работающий сервер OpenVPN. Далее, давайте перейдем к конфигурации на стороне клиента.
Убедитесь, что интерфейс VPN (tun0) создается с помощью команды Ifconfig:
Должно быть что то типа этого!
Конфигурация OpenVPN на стороне клиента
2. Если клиентская машина использует Debian, Ubuntu или Linux Mint
Источник
Install OpenVPN on Fedora 26
There are serveral tutorials in the internet (this and this). Which describes
installation process OpenVPN on linux.
They both not so applicable for Fedora 26 because from moment they was written it has been several years and there are many discrepancies.
And when I ended them up and faced several issues:
- Why I can ping but cannot access internet/local network behind the vpn server?
- Where keys should be placed?
- how to use Easy-RSA v3 instead v2?
- how to omit password on service start up?
1) First of all install necessary dependencies
2) Copy rsa scripts to the home folder
3) According to this start a new PKI and build a CA keypair/cert
4) Build Server certificate, key
5) Build Client certificate, key
you can omitt nopass on steps 3,4,5 if you need to
6) Generate a strong Diffie-Hellman keys
7) Generate HMAC signature to strengthen the server’s TLS integrity verification capabilities
8) Before openvpn server setting up we need to put appropriate keys ca.crt ca.key server.crt server.key ta.key dh.pem into /etc/openvpn/server/keys folder
9) Now we need to set up the server itself, firstly copy configurations
10) Modify several lines in that configuration file
add this lines at the end of the file:
remove ; symbol to uncomment following lines
10’)[optional] In order to to Redirect All Traffic Through the VPN, remove ; from following lines
10’’)[optional] Adjust port and protocol if you don’t wish to use default
and if you have server.crt and server.key with the different name point to them here
11) Allow IP Forwarding. This is fairly essential to the functionality we want our VPN server to provide.
and drop a line there
12) Set up firewalld to work with OpenVPN
13) Now we are going to set up our systemd service.
NB! server corresponts with the configuration file name in /etc/openvpn/server such as server.conf. So if you have myserver.conf you have to replace server with myserver
14) Now we are ready to start OpenVPN service
Done! We successfully deployed our OpenVPN server, and we are ready to move on and set up the client
Client setup
As you remember we have already generated client1.crt and client1.key at the step 5. And now we need combine them with our general Certificates of Authority in order to build client config file.
1) First of all we need generate Client Configurations. Lets create client-configs directory and prepare with the keys
2) Next we need to copy base configuration from examples
3) Open this file in your text editor
4) and modify as following
next uncomment (by removing ; )
NB: If you are using CentOS, change the group from nogroup to nobody to match the distribution’s available groups
and comment out the lines because we place them directly in client’s config
add this lines at the end of the file
5) Next, we will create a simple script to compile our base configuration with the relevant certificate, key, and encryption files. This will place the generated configuration in the
/client-configs/ files directory.
make that file executable
6) Execute that file with client1 input parameter
If everything went well, we should have a client1.ovpn file in our
7) Now that file can be used on the client machine
Источник
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:
Источник