Openvpn install service windows

When OpenVPN runs as a service it will start a separate OpenVPN process for each configuration file it finds in the \Program Files\OpenVPN\config-auto directory and will output a logfile of the same name to the \Program Files\OpenVPN\log directory.

When installed as a service, OpenVPN will default to Automatic Start mode. You can go to the «Services» control panel in Control Panel -> Administrative Tools to stop and start the service or change its system startup behavior.

Sample config files for client or server functionality have been provided in \Program Files\OpenVPN\sample-config and these can be adapted to your needs.

Service Notes:

When you install OpenVPN as a service, you are actually installing openvpnserv2.exe which is a service wrapper for OpenVPN, i.e. it reads the config file directory and starts up a separate OpenVPN process for each config file. openvpnserv2.exe performs the same function under windows as the /etc/init.d/openvpn startup script does under linux.

When you stop the OpenVPN service, it will send a terminate signal to all OpenVPN processes which were started by it.

If the OpenVPN service wrapper (openvpnserv2.exe) encounters fatal errors, it will write them to the windows event log, which can be viewed in Control Panel -> Administrative Tools -> Event Viewer -> Application Log.

If the OpenVPN processes themselves encounter errors, they will write them to their respective log files in the log file directory.

There is a one-to-one correspondence between an OpenVPN process, an OpenVPN config file, an OpenVPN log file, and a TAP-Win32 adapter which represents an endpoint of a VPN tunnel.

OpenVPN tunnels are point-to-point in their simplest form, but can be made point-to-multi-point through the use of bridging or routing (see below).

Multiple OpenVPN processes can run concurrently, each on a different TAP-Windows adapter.

openvpn.exe gets all configuration information from its config file, not from the registry.

The openvpnserv2.exe program (the service wrapper) gets several string parameters from the registry which can be modified by the user. If you change any of these parameters, you should be able to upgrade OpenVPN to a new version without the installer overwriting your changes: HKEY_LOCAL_MACHINE\SOFTWARE\OpenVPN

autostart_config_dir
configuration file directory to scan, defaults to «\Program Files\OpenVPN\config-auto»
config_ext
file extension on configuration files, defaults to «ovpn»
exe_path
path to openvpn.exe, defaults to «\Program Files\OpenVPN\bin\openvpn.exe»
log_dir
log file directory, defaults to «\Program Files\OpenVPN\log»
log_append
if set to «1», multiple instantiations of an OpenVPN process will append onto the same log file, if set to «0» (default), each new instantiation will truncate the previous log file priority the windows priority class for each instantiated OpenVPN process, can be one of:
  • «IDLE_PRIORITY_CLASS»
  • «BELOW_NORMAL_PRIORITY_CLASS»
  • «NORMAL_PRIORITY_CLASS» (default)
  • «ABOVE_NORMAL_PRIORITY_CLASS»
  • «HIGH_PRIORITY_CLASS»

OpenVPN – это набор open source программ, который заслуженно является одним из самых популярных и легких решений для реализации защищенной VPN сети. OpenVPN позволяет объединить в единую сеть сервер и клиентов (даже находящиеся за NAT или файерволами), или объединить сети удаленных офисов. Серверную часть OpenVPN можно развернуть практически на всех доступных операционных системах (пример настройки OpenVPN на Linux). Вы можете установить OpenVPN сервер даже на обычный компьютер с десктопной редакцией Windows 10.

В этой статье, мы покажем, как установить OpenVPN сервер на компьютер с Windows 10, настроить OpenVPN клиент на другом Windows хосте и установить защищенное VPN подключение.

Содержание:

  • Установка службы OpenVPN сервера в Windows
  • Создаем ключи шифрования и сертификаты для OpenVPN
  • Конфигурационный файл OpenVPN сервера в Windows
  • Настройка OpenVPN клиента в Windows

Установка службы OpenVPN сервера в Windows

Скачайте MSI установщик OpenVPN для вашей версии Windows с официального сайта (https://openvpn.net/community-downloads/). В нашем случае это OpenVPN-2.5.5-I602-amd64.msi (https://swupdate.openvpn.org/community/releases/OpenVPN-2.5.5-I602-amd64.msi).

Запустите установку.

Если вы планируете, OpenVPN сервер работал в автоматическом режиме, можно не устанавливать OpenVPN GUI. Обязательно установите OpenVPN Services.

установка openvpn сервера в windows 10

Начиная с версии OpenVPN 2.5, поддерживается драйвер WinTun от разработчиков WireGuard. Считается, что этот драйвер работает быстрее чем классический OpenVPN драйвер TAP. Установите драйвер Wintun, откажитесь от установки TAP-Windows6.

Установите OpenSSL утилиту EasyRSA Certificate Management Scripts.

WinTun драйвер openvpn

Запустите установку.

По умолчанию OpenVPN устаналивается в каталог C:\Program Files\OpenVPN.

После окончания установки появится новый сетевой адаптер типа Wintun Userspace Tunnel. Этот адаптер отключен, если служба OpenVPN не запущена.

сетевой адаптер Wintun Userspace Tunnel

Создаем ключи шифрования и сертификаты для OpenVPN

OpenVPN основан на шифровании OpenSSL. Это означает, что для обмена трафиком между клиентом и серверов VPN нужно сгенерировать ключи и сертификаты с использованием RSA3.

Откройте командную строку и перейдите в каталог easy-rsa:

cd C:\Program Files\OpenVPN\easy-rsa

Создайте копию файла:

copy vars.example vars

Откройте файл vars с помощью любого текстового редактора. Проверьте пути к рабочим директориям.

Обязательно поправьте переменную EASYRSA_TEMP_DIR следующим образом:

set_var EASYRSA_TEMP_DIR "$EASYRSA_PKI/temp"

EASYRSA_TEMP_DIR

Можете заполнить поля для сертификатов (опционально)

set_var EASYRSA_REQ_COUNTRY "RU"
set_var EASYRSA_REQ_PROVINCE "MSK"
set_var EASYRSA_REQ_CITY "MSK"
set_var EASYRSA_REQ_ORG "IT-Company"
set_var EASYRSA_REQ_EMAIL " [email protected] "
set_var EASYRSA_REQ_OU " IT department "

конфигурационный файл vars при установке сертфикатов easyrsa

Срок действия сертификатов задается с помощью:

#set_var EASYRSA_CA_EXPIRE 3650
#set_var EASYRSA_CERT_EXPIRE 825

Сохраните файл и выполните команду:

EasyRSA-Start.bat

Следующие команды выполняются в среде EasyRSA Shell:

Инициализация PKI:

./easyrsa init-pki

Должна появится надпись:

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: C:/Program Files/OpenVPN/easy-rsa/pki

Теперь нужно сгенерировать корневой CA:

./easyrsa build-ca

Задайте дважды пароль для CA:

CA creation complete and you may now import and sign cert requests.

Данная команда сформировала:

  • Корневой сертификат центра сертификации: «C:\Program Files\OpenVPN\easy-rsa\pki\ca.crt»
  • Ключ центра сертификации «C:\Program Files\OpenVPN\easy-rsa\pki\private\ca.key»

Теперь нужно сгенерировать запрос сертификата и ключ для вашего сервера OpenVPN:

./easyrsa gen-req server nopass

Утилита сгенерирует два файла:

req: C:/Program Files/OpenVPN/easy-rsa/pki/reqs/server.req
key: C:/Program Files/OpenVPN/easy-rsa/pki/private/server.key

Подпишем запрос на выпуск сертификата сервера с помощью нашего CA:

./easyrsa sign-req server server

Подтвердите правильность данных, набрав yes.

Затем введите пароль CA от корневого CA.

В каталоге issued появится сертификат сервера («C:\Program Files\OpenVPN\easy-rsa\pki\issued\server.crt»)

сертификат сервера openvpn

Теперь можно создать ключи Диффи-Хеллмана (займет длительное время):
./easyrsa gen-dh

Для дополнительной защиты VPN сервера желательно включить tls-auth. Данная технология позволяет использовать подписи HMAC к handshake-пакетам SSL/TLS, инициируя дополнительную проверку целостности. Пакеты без такой подписи будут отбрасываться VPN сервером. Это защитит вас от сканирования порта VPN сервера, DoS атак, переполнения буфера SSL/TLS.

Сгенерируйте ключ tls-auth:

cd C:\Program Files\OpenVPN\bin
openvpn --genkey secret ta.key

Должен появиться файл «C:\Program Files\OpenVPN\bin\ta.key». Переместите его в каталог C:\Program Files\OpenVPN\easy-rsa\pki

Теперь можно сформировать ключи для клиентов OpenVPN. Для каждого клиента, который будет подключаться к вашему серверу нужно создать собственные ключи.

Есть несколько способов генерации ключей и передачи их клиентам. В следующем примере, мы создадим на сервере ключ клиента и защитим его паролем:

./easyrsa gen-req kbuldogov
./easyrsa sign-req client kbuldogov

Данный ключ («C:\Program Files\OpenVPN\easy-rsa\pki\private\kbuldogov.key») нужно передать клиенту и сообщить пароль. Клиент может снять защиту паролем для ключа:

openssl rsa -in "C:\Program Files\OpenVPN\easy-rsa\pki\private\kbuldogov.key"-out "C:\Program Files\OpenVPN\easy-rsa\pki\private\kbuldogov_use.key"

снять защиту паролем с ключа клиента

Если вы хотите сгенерировать ключ, не защищенный паролем, нужно выполнить команду:

./easyrsa gen-req имяклиента nopass

На сервере с OpenVPN вы можете создать неограниченное количество ключей и сертификатов для пользователей. Аналогичным образом сформируйте ключи и сертфикаты для других клиентов.

Вы можете отохвать скомпрометированные сертификаты клиентов:
cd C:\Program Files\OpenVPN\easy-rsa
EasyRSA-Start.bat
./easyrsa revoke kbuldogov

Итак, мы сгенерировали набор ключей и сертификатов для OpenVPN сервера. Теперь можно настроить и запустить службу OpenVPN.

Конфигурационный файл OpenVPN сервера в Windows

Скопируйте типовой конфигурационный файл OpenVPN сервера:

copy "C:\Program Files\OpenVPN\sample-config\server.ovpn" "C:\Program Files\OpenVPN\config-auto\server.ovpn"

Откройте файл server.ovpn в любом текстовом редакторе и внесите свои настройки. Я использую следующий конфиг для OpenVPN:

# Указываем порт, протокол и устройство
port 1194
proto udp
dev tun
# Указываем пути к сертификатам сервера
ca "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\ca.crt"
cert "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\issued\\server.crt"
key "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\private\\server.key"
dh "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\dh.pem"
# Указываем настройки IP сети, адреса из которой будет будут получать VPN клиенты
server 10.24.1.0 255.255.255.0
#если нужно разрешить клиентам подключаться под одним ключом, нужвно включить опцию duplicate-cn (не рекомендуется)
#duplicate-cn
# TLS защита
tls-auth "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\ta.key" 0
cipher AES-256-GCM
# Другая параметры
keepalive 20 60
persist-key
persist-tun
status "C:\\Program Files\\OpenVPN\\log\\status.log"
log "C:\\Program Files\\OpenVPN\\log\\openvpn.log"
verb 3
mute 20
windows-driver wintun

Сохраните файл.

OpenVPN позволяет использовать как TCP, так и UDP для подключения. В этом примере я запустил OpenVPN на 1194 UDP. Рекомендуется использовать протокол UDP, это оптимально как с точки зрения производительности, так и безопасности.

Не забудьте открыть на файерволе порты для указанного вами порта OpenVPN на клиенте и на сервере. Можно открыть порты в Windows Defender с помощью PowerShell.
Правило для сервера:

New-NetFirewallRule -DisplayName "AllowOpenVPN-In" -Direction Inbound -Protocol UDP –LocalPort 1194 -Action Allow

Правило для клиента:

New-NetFirewallRule -DisplayName "AllowOpenVPN-Out" -Direction Outbound -Protocol UDP –LocalPort 1194 -Action Allow

Теперь нужно запустить службу OpenVPN и изменить тип ее запуска на автоматический. Воспользуйтесь таким командами PowerShell, чтобы включить службу:

Set-Service OpenVPNService –startuptype automatic –passthru
Get-Service OpenVPNService| Start-Service

запуск службы OpenVPNService

Откройте панель управления, и убедитесь, что виртуальный сетевой адаптер OpenVPN Wintun теперь активен. Если нет, смотрите лог «C:\Program Files\OpenVPN\log\server.log»

Если при запуске OpenVPN вы видите в логе ошибку:

Options error: In C:\Program Files\OpenVPN\config-auto\server.ovpn:1: Maximum option line length (256) exceeded, line starts with..

Смените в файле server.ovpn символы переноса строки на Windows CRLF (в notepad++ нужно выбрать Edit -> EOL Conversion -> Windows CR LF). Сохраните файл, перезапустите службу OpevVPNService.

Данный конфиг позволит удаленным клиентам получить доступ только к серверу, но другие компьютеры и сервисы в локальной сети сервера для них недоступны. Чтобы разрешить клиентам OpenVPN получить доступ к внутренней сети нужно:

Включить опцию IPEnableRouter в реестре (включает IP маршрутизацию в Windows, в том числе включает маршрутизацию меду сетями Hyper-V): reg add «HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters» /v IPEnableRouter /t REG_DWORD /d 1 /f

Добавьте в конфгурационный файл сервера OpenVPN маршруты до внутренней IP сети:

push "route 10.24.1.0 255.255.255.0"
push "route 192.168.100.0 255.255.255.0"

Если нужно, назначьте клиенту адреса DNS серверов:

push "dhcp-option DNS 192.168.100.11"
push "dhcp-option DNS 192.168.100.12"

Если нужно завернуть все запросы клиента (в том числе Интернет трафик) на ваш OpenVPN сервер, добавьте опцию:

push "redirect-gateway def1"

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

Создайте на сервере шаблонный конфигурационный файла для клиента VPN (на базе iшаблона client.ovpn) со следующими параметрами (имя файла kbuldovov.ovpn)

client
dev tun
proto udp
remote your_vpn_server_address 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert kbuldogov.crt
key kbuldogov.key
remote-cert-tls server
tls-auth ta.key 1
cipher AES-256-GCM
connect-retry-max 25
verb 3

В директиве remote указывается публичный IP адрес или DNS имя вашего сервера OpenVPN.

Скачайте и установите клиент OpenVPN Connect для Windows (https://openvpn.net/downloads/openvpn-connect-v3-windows.msi).

установка openvpn connect в windows

Теперь на компьютер с клиентом OpenVPN нужно с сервера скопировать файлы:

  • ca.crt
  • kbuldogov.crt
  • kbuldogov.key
  • dh.pem
  • ta.key
  • kbuldogov.ovpn

Теперь импортируйте файл с профилем *.ovpn и попробуйте подключиться к вашему VPN серверу.

Если все настроено правильно, появится такая картинка.

Проверьте теперь лог OpenVPN на клиенте «C:\Program Files\OpenVPN Connect\agent.log»

Mon Dec 27 08:09:30 2021 proxy_auto_config_url
Mon Dec 27 08:09:31 2021 TUN SETUP
TAP ADAPTERS:
guid='{25EE4A55-BE90-45A0-88A1-8FA8FEF24C42}' index=22 name='Local Area Connection'
Open TAP device "Local Area Connection" PATH="\\.\Global\{25EE4A55-BE90-45A0-88A1-8FA8FEF24C42}.tap" SUCCEEDED
TAP-Windows Driver Version 9.24
ActionDeleteAllRoutesOnInterface iface_index=22
netsh interface ip set interface 22 metric=1
Ok.
netsh interface ip set address 22 static 10.24.1.6 255.255.255.252 gateway=10.24.1.5 store=active
IPHelper: add route 10.24.1.1/32 22 10.24.1.5 metric=-1

Клиент успешно подключится к OpenVPN серверу и получил IP адрес 10.24.1.6.

Проверьте теперь лог на сервере («C:\Program Files\OpenVPN\log\openvpn.log»). Здесь также видно, что клиент с сертификатом kbuldogov успешно подключится к вашему серверу.

2021-12-27 08:09:35 192.168.13.202:55648 [kbuldogov] Peer Connection Initiated with [AF_INET6]::ffff:192.168.13.202:55648
2021-12-27 08:09:35 kbuldogov/192.168.13.202:55648 MULTI_sva: pool returned IPv4=10.24.1.6, IPv6=(Not enabled)
2021-12-27 08:09:35 kbuldogov/192.168.13.202:55648 MULTI: Learn: 10.24.1.6 -> kbuldogov/192.168.13.202:55648
2021-12-27 08:09:35 kbuldogov/192.168.13.202:55648 MULTI: primary virtual IP for kbuldogov/192.168.13.202:55648: 10.24.1.6

You can configure our assessment VPN’s to start everytime a machine boots, thus it will be connected all the time and doesn’t require any interaction from you. We will only need this if we are utilising OpenVPN for your assessment.

The OpenVPN client can be installed as a service, however, you will need to have your auto-login profile downloaded and available to install the service. Even if you have setup the OpenVPN for manual activation by importing the profile, you will need that file again for this process.

You will need administrative access to the system to be able to complete these tasks.

We suggest you create (and for this example are using) a directory/folder in the OpenVPN installation directory called «config» 

Copy your client.ovpn (downloaded from the assessment platform website) into the newly created config folder: C:\Program Files\OpenVPN Connect\config.

You then need to start an administrative command prompt

Move from the default C:\WINDOWS\system32> location to the OpenVPN folder by typing:

cd\ {then press enter}

cd\

cd «program files» {then press enter}

cd "program files"

cd «OpenVPN Connect» {then press enter}

cd "OpenVPN Connect"

You will now be in the installation folder for the OpenVPN application

From here we first need to install the OpenVPN application as a service, type:

ovpnconnector.exe install {and press enter}

ovpnconnector install

If all goes well you should receive confirmation (as above) that the OpenVPN has been installed as a service. You should note that the service does not use any of your desktop application configuration and you will need to tell the service what profile to use.

If you receive an error «CreateService failed with (1073)» this indicates that the OpenVPN is already installed as a service

We now need to tell the OpenVPN service what profile to use when it starts, type:

ovpnconnector.exe set-config profile «c:\program files\openvpn connect\config\client.ovpn»

ovpnconnector.exe set-config profile "c:\program files\openvpn connect\config\client.ovpn"

Unfortunately, this particular command, writes some configuration into the OpenVPN service but doesn’t tell you if what you have typed is correct or not, therefore you will not actually know until you try and connect the VPN.

To start the VPN, or service, using the configuration file you have specified, you now type:

ovpnconnector start {and press enter}

ovpnconnector.exe start

At this point you may well receive an error message if you have previously started the OpenVPN client on the machine. 

You will need to exit the desktop application which may be hidden in your taskbar, click on the ^ symbol near the clock on your machine and then right click on the OpenVPN symbol 

Selecting «Exit«

Switch back to your Admin Command Prompt Window and re-run the service start command

If you receive the Service started successfully messgage, you hopefully will be connected to the VPN — check with the Cyber Tec Security Assessment team who will be able to confirm for you.

Your VPN will now start and connect each time the device is rebooted.

Данная инструкция предназначена для системных администраторов и IT-специалистов, которые планируют развернуть сервер OpenVPN для создания защищенного VPN-соединения. OpenVPN является одним из самых надежных и популярных решений для организации виртуальной частной сети, обеспечивающего высокий уровень безопасности и производительности.

Установка OpenVPN сервера в Windows

Запустите скачанный ранее MSI установщик. Нажмите Customize:

Установка OpenVPN Server на Windiws.

Рисунок 1 – Установка OpenVPN Server на Windiws.

OpenVPN GUI можно не устанавливать. Обязательно установите OpenVPN Services.

Wintun и OpenSSL

Рисунок 2 – Установка Wintun и OpenSSL.

Установите драйвер Wintun и OpenSSL утилиту EasyRSA 3 Certificate Management Scripts. От установки TAP-Windows6 можно отказаться:

Установка OpenVPN Services на Windiws

Рисунок 3 – Установка OpenVPN Services на Windiws.

Запустите установку нажав Install Now.

Создание ключей шифрования и сертификатов для OpenVPN

Откройте командную строку от имени администратора и перейдите в каталог easy-rsa:

cd C:\Program Files\OpenVPN\easy-rsa

Создайте копию файла vars:

Откройте файл vars в любом текстовом редакторе. Проверьте пути к рабочим директориям. Можете по желанию заполнить поля для сертификатов:

Редактирование файла vars

Рисунок 4 – Редактирование файла vars.

Срок действия сертификатов можно задать с помощью:

#set_var EASYRSA_CA_EXPIRE 3650
#set_var EASYRSA_CERT_EXPIRE 825

Сохраните файл и выполните команду:

Следующие команды выполняются в среде EasyRSA Shell. Инициализация PKI:

Должна появится надпись:

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: C:/Program Files/OpenVPN/easy-rsa/pki

Теперь нужно сгенерировать корневой CA:

Задайте и повторите пароль для CA, должна появится надпись:

CA creation complete. Your new CA certificate is at:
* C:/Program Files/OpenVPN/easy-rsa/pki/ca.crt

Данная команда сформировала:

  • корневой сертификат центра сертификации: C:\Program Files\OpenVPN\easy-rsa\pki\ca.crt;
  • ключ центра сертификации C:\Program Files\OpenVPN\easy-rsa\pki\private\ca.key

Теперь нужно сгенерировать запрос сертификата и ключ для вашего сервера OpenVPN:

./easyrsa gen-req server nopass

Утилита сгенерирует два файла:

  • req: C:/Program Files/OpenVPN/easy-rsa/pki/reqs/server.req
  • key: C:/Program Files/OpenVPN/easy-rsa/pki/private/server.key

Подпишем запрос на выпуск сертификата сервера с помощью нашего CA:

./easyrsa sign-req server server

Подтвердите правильность данных, набрав yes. Затем введите пароль CA от корневого CA. В каталоге issued появится сертификат сервера C:\Program Files\OpenVPN\easy-rsa\pki\issued\server.crt

Теперь можно создать ключи Диффи-Хеллмана:

Далее желательно включить tls-auth.

cd C:\Program Files\OpenVPN\bin
openvpn --genkey secret ta.key

Должен появиться файл C:\Program Files\OpenVPN\bin\ta.key. Переместите его в каталог C:\Program Files\OpenVPN\easy-rsa\pki

Теперь можно сформировать ключи для клиентов OpenVPN.

./easyrsa gen-req client1 nopass
./easyrsa sign-req client client1

Итак, мы сгенерировали набор ключей и сертификатов для OpenVPN сервера. Теперь можно настроить и запустить службу OpenVPN.

Конфигурационный файл OpenVPN сервера в Windows

Скопируйте типовой конфигурационный файл OpenVPN сервера:

copy "C:\Program Files\OpenVPN\sample-config\server.ovpn" "C:\Program Files\OpenVPN\config-auto\server.ovpn"

Откройте файл server.ovpn в любом текстовом редакторе и внесите свои настройки.

Пример конфигурации для OpenVPN:

# Указываем порт и протокол
port 1194
proto udp
dev tun
# Указываем пути к сертификатам сервера
ca "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\ca.crt"
cert "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\issued\\server.crt"
key "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\private\\server.key"
dh "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\dh.pem"
# Указываем настройки сети
server 10.45.139.0 255.255.255.0
# TLS защита
tls-auth "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\ta.key" 0
cipher AES-256-GCM
# Другая параметры
keepalive 20 60
persist-key
persist-tun
status "C:\\Program Files\\OpenVPN\\log\\status.log"
log "C:\\Program Files\\OpenVPN\\log\\openvpn.log"
verb 3
mute 20
windows-driver wintun

Сохраните файл.

Теперь нужно перезапустить службу OpenVPNService. Откройте панель управления, и убедитесь, что виртуальный сетевой адаптер OpenVPN Wintun теперь активен.

Рисунок 5 – Настройка OpenVPN Server и сетевого адаптера.

После успешного выполнения всех шагов инструкции у вас должен быть работающий VPN-сервер, готовый к использованию.

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

Создайте из шаблона client.ovpn клиентский конфигурационный файл со следующим содержимым:

client
dev tun
proto udp
remote адрес вашего сервера 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client1.crt
key client1.key
remote-cert-tls server
tls-auth ta.key 1
cipher AES-256-GCM
connect-retry-max 25
verb 3

На клиентском ПК скачайте и установите OpenVPN Connect. Скопируйте на клиента следующие файлы:

ca.crt
client1.crt
client1.key
dh.pem
ta.key
client1.ovpn

Запустите OpenVPN Connect, откройте вкладку UPLOAD FILE и перетащите туда файл client1.ovpn, после чего нажмите кнопку CONNECT:

Рисунок 6 – Настройка OpenVPN Connect, шаг 1.

Рисунок 7 – Настройка OpenVPN Connect, шаг 2.

Готово. Если все настроено правильно, то вы подключитесь к своему OpenVPN серверу.

OpenVPN is an open-source software suite that is one of the most popular and easiest solutions for implementing a secure VPN. OpenVPN allows you to combine a server and clients (even those behind a NAT or firewall) into a single network, or to connect networks of remote offices. You can deploy a server part of OpenVPN almost in all available operating systems, including Linux, Windows, MacOS, and *BSD. You can install an OpenVPN server on Windows Server 2022/20119/2016/2012R2 or even on a computer running desktop Windows edition (Windows 10 or 11).

In this article, we will show how to install and configure an OpenVPN server on a computer running Windows 10, set up an OpenVPN client on another Windows device, and establish a secure VPN connection.

Contents:

  • How to Install OpenVPN Server Service on Windows
  • Create OpenVPN Encryption Keys and Certificates
  • OpenVPN Server Configuration File for Windows
  • Configuring OpenVPN Client on Windows

OpenVPN is extremely popular in the SOHO segment to provide access to remote employees: you don’t need to buy any special hardware, licenses to build a VPN server based on Windows Server, expose RDP port to the Internet, and can easily protect against RDP brute force attacks.

How to Install OpenVPN Server Service on Windows

Download the OpenVPN MSI installer for your Windows version from the official website (https://openvpn.net/community-downloads/). In our case, this is OpenVPN-2.5.7-I602-amd64.msi (https://swupdate.openvpn.org/community/releases/OpenVPN-2.5.7-I602-amd64.msi).

Run the setup and select OpenVPN Service to install. If you want your OpenVPN server to start automatically, you may not install OpenVPN GUI.

installing OpenVpn Server on Windows

OpenVPN 2.5 (and newer) supports the WinTun driver from the WireGuard developers. This driver is faster that the default TAP OpenVPN driver. We recommend installing Wintun driver instead of TAP-Windows6.

Install the EasyRSA Certificate Management Scripts OpenSSL utility.

Complete the installation.

By default, OpenVPN is installed to C:\Program Files\OpenVPN.

When the installation is complete, you will see a new network adapter Wintun Userspace Tunnel. This adapter is disabled if the OpenVPN service is not running.

Create OpenVPN Encryption Keys and Certificates

OpenVPN is based on OpenSSL encryption. This means that RSA3 keys and certificates must be used to establish a network connection between the client and the VPN server.

Open the command prompt and go to easy-rsa directory:

cd "C:\Program Files\OpenVPN\easy-rsa"

Create a copy of the file:

copy vars.example vars

Open the vars file in any text editor. Check the paths to the OpenVPN and EaseRSA working folders.

Be sure to edit the EASYRSA_TEMP_DIR variable as shown below:

set_var EASYRSA_TEMP_DIR "$EASYRSA_PKI/temp"

set_var EASYRSA_TEMP_DIR

You may fill in the certificate fields (optional):

set_var EASYRSA_REQ_COUNTRY "DE"
set_var EASYRSA_REQ_PROVINCE "BY"
set_var EASYRSA_REQ_CITY "MUN"
set_var EASYRSA_REQ_ORG "WOSHUB-Com"
set_var EASYRSA_REQ_EMAIL "[email protected]"
set_var EASYRSA_REQ_OU "IT dept"

Set certificate expiration dates:

set_var EASYRSA_CA_EXPIRE 3650
set_var EASYRSA_CERT_EXPIRE 825

Save the file and run the command:

EasyRSA-Start.bat

All of the following commands must be run in the EasyRSA shell:

Initialize PKI:

./easyrsa init-pki

You should see this message:

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: C:/Program Files/OpenVPN/easy-rsa/pki

Then generate the root CA:

./easyrsa build-ca

Enter a CA password twice:

CA creation is complete and you may now import and sign cert requests.

The command above has created:

  • A root certificate of the Certification Authority: C:\Program Files\OpenVPN\easy-rsa\pki\ca.crt
  • A Certification Authority key: C:\Program Files\OpenVPN\easy-rsa\pki\private\ca.key

Then generate a certificate request and a key for your OpenVPN server:

./easyrsa gen-req server nopass

The tool will generate two files:

req: C:/Program Files/OpenVPN/easy-rsa/pki/reqs/server.req
key: C:/Program Files/OpenVPN/easy-rsa/pki/private/server.key

Sign the request to issue a server certificate using your CA:

./easyrsa sign-req server server

Confirm the data by typing yes.

Then enter the CA password for your root CA.

The server.crt file will appear in the issued folder (C:\Program Files\OpenVPN\easy-rsa\pki\issued\server.crt).

openvpn server certififate fil in the issued folder

Then you can generate Diffie-Hellman keys (takes a long time):
./easyrsa gen-dh

To provide additional protection for your VPN server, it is recommended to enable tls-auth. This feature allows using HMAC signatures in SSL/TLS handshake, thus initiating an extra integrity check. Packets without such a signature will be dropped by the VPN server. This will protect you against VPN server port scanning, DoS attacks, SSL/TLS buffer overflows, etc.

Generate a tls-auth key:

cd C:\Program Files\OpenVPN\bin
openvpn --genkey secret ta.key

The C:\Program Files\OpenVPN\bin\ta.key file will appear. Move it to C:\Program Files\OpenVPN\easy-rsa\pki folder.

Then you can generate keys for your OpenVPN clients. Each client connecting to your VPN server must have its own key pair.

There are several ways to generate OpenVPN keys and distribute them to clients.

In the example below, we will create a client key on the server and protect it with a password (PEM pass phrase):

./easyrsa gen-req testuser1
./easyrsa sign-req client testuser1

Copy the key file (C:\Program Files\OpenVPN\easy-rsa\pki\private\testuser1.key) to the client computer tell the user the password (voice, email, SMS). The client can disable the password protection for the key:

openssl rsa -in "C:\Program Files\OpenVPN\easy-rsa\pki\private\testuser1.key"-out "C:\Program Files\OpenVPN\easy-rsa\pki\private\testuser1_use.key"

openssl rsa disable PEM pass phrase

If you want to generate a key that is not password protected, you need to run the command:

./easyrsa gen-req testuser2 nopass

You may create any number of keys and certificates for users on your VPN server. Generate keys and certificates for other clients in the same way.

You can revoke compromised client certificates:
cd C:\Program Files\OpenVPN\easy-rsa
EasyRSA-Start.bat
./easyrsa revoke testuser2

Therefore, we have generated a set of keys and certificates for the OpenVPN server. Now you can configure and run your VPN service.

OpenVPN Server Configuration File for Windows

Copy the configuration file template for the OpenVPN server:

copy "C:\Program Files\OpenVPN\sample-config\server.ovpn" "C:\Program Files\OpenVPN\config-auto\server.ovpn"

Open server.ovpn in any text editor and make your settings. I am using the following OpenVPN configuration:

# Specify a port, a protocol and a device type
port 1194
proto udp
dev tun
# Specify paths to server certificates
ca "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\ca.crt"
cert "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\issued\\server.crt"
key "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\private\\server.key"
dh "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\dh.pem"
# Specify the settings of the IP network your VPN clients will get their IP addresses from
server 10.24.1.0 255.255.255.0
# If you want to allow your clients to connect using the same key, enable the duplicate-cn option (not recommended)
# duplicate-cn
# TLS protection
tls-auth "C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\ta.key" 0
cipher AES-256-GCM
# Other options
keepalive 20 60
persist-key
persist-tun
status "C:\\Program Files\\OpenVPN\\log\\status.log"
log "C:\\Program Files\\OpenVPN\\log\\openvpn.log"
verb 3
mute 20
windows-driver wintun

Save the file.

OpenVPN allows you to use both TCP and UDP protocols. In this example, we have run OpenVPN on UDP port 1194. It is recommended to use UDP as it is optimal for both performance and security.

Remember to open ports in the firewall for the OpenVPN port number you have specified on the client and the server. You can open the port in Windows Defender using PowerShell.
Firewall rule for the OpenVPN server:

New-NetFirewallRule -DisplayName "AllowOpenVPN-In" -Direction Inbound -Protocol UDP –LocalPort 1194 -Action Allow

The rule for the client:

New-NetFirewallRule -DisplayName "AllowOpenVPN-Out" -Direction Outbound -Protocol UDP –LocalPort 1194 -Action Allow

Then run the OpenVPN service and change its startup type to automatic. Use the PowerShell to enable the service:

Set-Service OpenVPNService –startuptype automatic –passthru
Get-Service OpenVPNService| Start-Service

start OpenVPNService in Windows

Open the network connections dialog (ncpa.cpl) and make sure that OpenVPN Wintun virtual adapter is now enabled. If it is not, check the log file C:\Program Files\OpenVPN\log\server.log.

If you see the following error in the log when starting OpenVPN:

Options error: In C:\Program Files\OpenVPN\config-auto\server.ovpn:1: Maximum option line length (256) exceeded, line starts with…

Change line break character to Windows CRLF (in Notepad++, select Edit -> EOL Conversion -> Windows CR LF) in server.ovpn. Save the file and restart the OpenVPNService.

This OpenVPN configuration allows remote clients to access the server resources only. Other computers and services in the server‘s local network are not available for remote clients. In order to allow OpenVPN clients to access the internal LAN, enable the IPEnableRouter option in the registry (enables IP routing in Windows including routing between Hyper-V networks, and allows you to use port-forwarding):

reg add "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /v IPEnableRouter /t REG_DWORD /d 1 /f

Add the routes to your local IP network to the server configuration file:

push "route 10.24.1.0 255.255.255.0"
push "route 192.168.31.0 255.255.255.0"

If needed, assign DNS server addresses to the client:

push "dhcp-option DNS 192.168.31.10"
push "dhcp-option DNS 192.168.31.11"

If you want to redirect all client requests (including the Internet traffic) to your OpenVPN server, add the option:

push "redirect-gateway def1"

Configuring OpenVPN Client on Windows

Create a template configuration file for a VPN client (based on client.ovpn template) on your server with the following settings (the file name is testuser1.ovpn):

client
dev tun
proto udp
remote your_vpn_server_address 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert testuser1.crt
key testuser1.key
remote-cert-tls server
tls-auth ta.key 1
cipher AES-256-GCM
connect-retry-max 25
verb 3

Specify a public IP address or a DNS name of your OpenVPN server in the remote directive.

Download and install OpenVPN Connect for Windows (https://openvpn.net/downloads/openvpn-connect-v3-windows.msi).

install OpenVPN Client Connect for Windows

Then copy the following files from your server to the computer with the installed OpenVPN client:

  • ca.crt
  • testuser1.crt
  • testuser1.key
  • dh.pem
  • ta.key
  • testuser1.ovpn

Import *.ovpn profile file and try to connect to your VPN server.

If you have set it correctly, you will see the image below:

Check the OpenVPN connection log on the client: C:\Program Files\OpenVPN Connect\agent.log

Mon Jul 17 08:09:30 2022 proxy_auto_config_url
Mon Jul 17 08:09:31 2022 TUN SETUP
TAP ADAPTERS:
guid='{25EE4A55-BE90-45A0-88A1-8FA8FEF24C42}' index=22 name='Local Area Connection'
Open TAP device "Local Area Connection" PATH="\\.\Global\{25EE4A55-BE90-45A0-88A1-8FA8FEF24C42}.tap" SUCCEEDED
TAP-Windows Driver Version 9.24
ActionDeleteAllRoutesOnInterface iface_index=22
netsh interface ip set interface 22 metric=1
Ok.
netsh interface ip set address 22 static 10.24.1.10 255.255.255.252 gateway=10.24.1.5 store=active
IPHelper: add route 10.24.1.1/32 22 10.24.1.5 metric=-1

The client has successfully connected to the VPN server and received the IP address 10.24.1.10.

Now check the OpenVpn log on the server-side (C:\Program Files\OpenVPN\log\openvpn.log). Here you can also see that the client with the testuser1 certificate has successfully connected to the server.

2022-07-17 08:09:35 192.168.13.20:55648 [tesuser1] Peer Connection Initiated with [AF_INET6]::ffff:192.168.13.20:55648
2022-07-17 08:09:35 tesuser1/192.168.13.20:55648 MULTI_sva: pool returned IPv4=10.24.1.10, IPv6=(Not enabled)
2022-07-17 08:09:35 tesuser1/192.168.13.20:55648 MULTI: Learn: 10.24.1.10 -> testuser1/192.168.13.20:55648
2022-07-17 08:09:35 tesuser1/192.168.13.20:55648 MULTI: primary virtual IP for tesuser1/192.168.13.20:55648: 10.24.1.10

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как зайти в буфер обмена на компьютере на windows 11
  • Untrusted system file c windows system32 nvapi64 dll
  • Как убрать windows loader xe при загрузке виндовс
  • Windows server 2008 установка с флешки
  • Отваливается bluetooth мышь windows 11