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 — использовать сжатие.
Читайте также:  Как переставить windows с флешки

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

Разрешаем автоматический старт сервиса 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-адресов.

Источник

VPN Software Repository & Packages

Linux is the operating system of choice for the OpenVPN Access Server self-hosted business VPN software, and is available as software packages for Ubuntu LTS, Debian, Red Hat Enterprise Linux, CentOS and Amazon Linux Two.

To install or update your existing deployment of OpenVPN Access Server software, please use our repository. Separate package downloads are also available if you need to install on an offline system. Select your platform of choice to get started.

Choose Your Software Package

Select Your Operating System

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Читайте также:  Как удалить папку профиля пользователя windows 10

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Читайте также:  Стал тормозит компьютер что делать при windows

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

The recommended method to install the OpenVPN Access Server is to use the official OpenVPN Access Server software repository. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to add the repository to your system, and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. Installing the package ‘openvpn-as’ will automatically pull in the required client bundle as well.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

Note: from version 2.9.2 we now use a new software repository for Amazon Linux 2.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Option 2: Manually download packages

If for some reason you can or will not use the recommended installation via the official OpenVPN Access Server software repository, you can instead download the packages separately to your server and install them. You will need to be logged on to your Linux system either on the console or via SSH, and have root privileges. Then copy and paste the commands below to download the necessary package installer files and install the OpenVPN Access Server client bundle and the OpenVPN Access Server package itself. You may also use the buttons below to download the package files manually to your computer.

Note: these steps are suitable for a fresh install and for upgrading an existing installation.

After these steps, your Access Server should be installed and awaiting further configuration. Consult our quick start guide for further instructions on how to configure and use your Access Server.

Источник

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