Openvpn linux ������ ���������

Настройка и использование OpenVPN на Ubuntu

Для удобства настройки заходим под суперпользователем:

Подготовка 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

Установка, настройка и запуск VPN-сервера

Обязательные шаги для развертывания сервиса — установка программного обеспечения, генерация сертификатов, настройка OpenVPN. Рассмотрим эти процессы по шагам.

Установка OpenVPN

Устанавливаем необходимые пакеты следующей командой:

apt-get install openvpn easy-rsa

Создание сертификатов

Создаем каталог, в котором разместим готовые сертификаты для 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/

Настройка 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 — использовать сжатие.
Читайте также:  Oracle client ��� linux

Создадим каталог для логов:

Разрешаем автоматический старт сервиса vpn и запускаем его:

systemctl enable openvpn@server —now

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

Сертификат должен быть сформирован на сервер, после чего перенесен на клиентское устройство. Рассмотрим процесс подробнее.

На сервере

Создадим каталог, куда поместим сертификаты для обмена:

* сертификаты будут скопированы в каталог /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

На клиенте

Клиент 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» от имени администратора (это важно).

Нажимаем правой кнопкой по появившемуся в трее значку и выбираем «Подключиться»:

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

Доступ к локальной сети

Для настройки доступа к локальной сети, воспользуйтесь инструкцией Настройка доступа к локальной сети клиентам OpenVPN в Linux.

Аутентификация пользователей

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

Источник

Installing OpenVPN Access Server on a Linux system

Operating systems supported

The OpenVPN Access Server is distributed via our software repository on a number of popular Linux distributions such as Ubuntu, Debian, CentOS, and Red Hat, and Amazon Linux 2. You can easily deploy Access Server on any x86-64 system that can run those operating systems using our software repository. To install the repository and install Access Server check the software repository download page on our website for instructions.

There are also options for installing Access Server using a prepared image containing the Ubuntu operating system and the OpenVPN Access Server program in it. These are available for Microsoft Hyper-V, VMWare ESXi, Amazon AWS, Microsoft Azure, Google Cloud Platform, and other virtualization solutions. We have a preference to use the latest Ubuntu 64 bits Long Term Support version for our prepared images.

Читайте также:  Аналог cleanmymac для windows

Installation requirements and preparation

You will need to have access to a working supported Linux operating system installation that you have root level access to. It doesn’t matter if this is through the console directly or through an SSH session using for example a tool like PuTTY, and it doesn’t matter if you must log on as an unprivileged user first, and then can ‘sudo up’ to gain root privileges. As long as at the end you have root privileges, then you will be able to proceed.

It is important that the time and date on your server are accurate. This is necessary for both certificate generation and verification as well Google Authenticator multi-factor authentication which is time-based. If you are using a modern operating system like Ubuntu 18 or higher, it will usually already have time synchronization software built in. Usually you only need to worry about setting the timezone. You can use the ‘date’ command to see what the current time and date and timezone are.

The OpenVPN Access Server can function entirely within an environment where no Internet access is possible, but this does make licensing the server much more complicated and will require that you contact our support department. And if the Access Server doesn’t have Internet access it obviously can’t accept connections from clients from the Internet either of course.

It’s best to have the Access Server connected to the Internet, and we recommend doing this behind a firewall system with only ports TCP 443, TCP 943, TCP 945, and UDP 1194 forwarded from the public Internet to the private address of the Access Server behind the firewall. It is also important to check that DNS resolution is working as expected, so that pinging for example www.google.com will result in the server being able to resolve this to an IP address. If DNS resolution doesn’t work right it can slow down the web interface, cause problems with VPN clients that want to redirect their Internet traffic through the VPN server, and prevents successful licensing of the Access Server.

Access Server since version 2.7.5 gets distributed via a software repository now. So if your system is isolated from the Internet, it will be more work to install it without Internet access. We do still offer the option to download software packages separately, but Access Server now comes in 2 packages. The OpenVPN Connect client software bundle, and the OpenVPN Access Server. Both must be installed for Access Server to successfully install. On top of that, various dependencies are required which must be installed separately as well. You can find these instructions also on our software repository page by selecting the manual installation option.

Install repository, then upgrade

The upgrade procedure via repository is fairly simple. You need to first know which operating system you have. If you don’t know what it is, you can use the information below to determine this. Then you install the software repository and install Access Server using the instructions from our software repository page. So in short these are the steps that you need to take:

  • Determine your operating system.
  • Run the instructions for your OS from our website to install the repository.
  • Those instructions will also install the latest version of OpenVPN Access Server.

To determine your operating system:

This should output some useful information. If you encounter some failure with some of these commands, that is not a problem. We provide these 3 commands and at least one of them should succeed and provide the necessary information. Below is an example of output from an older Access Server on Amazon AWS:

Now we know that we’re running Ubuntu 16.04.2 LTS on an x86_64 platform. With the information that we have now, we can determine the operating system name, version number, and whether it’s x86 (32 bits) or x86_64 (64 bits).

Based on those three things, look up the repository installation instructions on our software repository page on our website. Select the operating system that you use, which version of operating system from the choices, and a list of instructions will then be visible.

The instructions give you commands to run on your server’s command line. It will set up the software repository for you, download and install the latest Access Server version, and if there is an existing Access Server installation, it will upgrade it for you automatically while retaining your licensing information and your users and settings.

Читайте также:  Перезагрузка finder mac os

After adding the repository, when you run apt update and apt upgrade in the future to update packages on your operating system, it will also update Access Server at the same time.

For the final step, we recommend rebooting your server:

This completes the installation and upgrade process.

NOTE: If your operating system is so old that it isn’t even listed anymore, do not proceed. You may need to consider updating your whole system. For example, we no longer offer downloads for CentOS 5 as it could not handle functions we support today for IPv6. Trying to install the CentOS 7 version on it would not work. Installing OpenVPN Access Server on an older platform than it was designed for will result in failure.

Finishing configuration and using the product

Once the program is installed it will automatically configure itself with default settings unless it detected a previous installation — then it just keeps those settings from the existing installation. If you install fresh, the installation process will tell you where to find the client web service, which is the web based GUI that you can use to log on and connect to the Access Server, and where to find the admin web service, which is where you can log on as an administrative user and manage the configuration, certificate, users, etcetera, in the web based GUI.

Usually the client UI is at the address of your server, as an example it may be at https://192.168.70.222/.

The admin UI is usually at the /admin/ address, for example https://192.168.70.222/admin/.

Please note that the web services by default actually run on port TCP 943, so using our example IP address, you can add that to the end: https://192.168.70.222:943/. The OpenVPN TCP daemon that runs on TCP port 443 redirects incoming browser requests so that it is easier for users to open the web interface — they won’t have to specify that port number.

Initially a single administrative user is added to the system. But it has no password set and therefore cannot be used yet. To use it a password must be set first:

You can now point your web browser at the admin UI web interface. Because the Access Server comes with a self-signed SSL certificate to begin with, you will receive a warning in the browser like “Invalid certificate» or “Cannot verify identity of the server». You will have to confirm that you wish to continue to the web interface (these warnings may be a little scary but can be resolved later by installing a properly signed web SSL certificate in the Access Server). You will then see the login screen and you can then enter the username openvpn and the password you have just set with the “passwd openvpn» command.

Once you are logged in to the Admin UI you can select which authentication system to use. The available choices are LOCAL, PAM, RADIUS, and LDAP. The default is LOCAL which lets you manage the users directly from the web interface.

You can also use another external system like RADIUS or LDAP server, for example to connect to a Windows Server Active Directory using an LDAP or RADIUS connector. If you do connect to Windows AD, we recommend that you use LDAP for best results.

If you are managing only a limited amount of users and don’t want things to be too complicated you can just stay with LOCAL authentication mode. Almost everything can then be configured purely from the Admin UI, although some advanced options are only available in the command line tools. We recommend that if you choose to use PAM that you look at the command line authentication options documentation specifically to learn how to add/remove users and manage passwords.

Further documentation is available to configure specific functions and configuration options for the OpenVPN Access Server.

Limitations of an unlicensed OpenVPN Access Server

When the OpenVPN Access Server is installed without a license key it goes into a sort of demonstration mode. There is no time limit or functionality limit on this mode. The only difference between a licensed Access Server and an unlicensed one is the amount of simultaneous OpenVPN tunnel connections the Access Server allows. An unlicensed server will only ever allow 2 simultaneous connections and that’s it. To unlock more connections you can purchase a license key to unlock more connections. We suggest you read the licensing frequently asked questions page and the pricing overview page to learn more.

Источник

Оцените статью