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

OpenVPN – это набор open source программ, который заслуженно является одним из самых популярных и легких решений для реализации защищенной VPN сети. OpenVPN

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 FilesOpenVPN.

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

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

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

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

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

cd C:Program FilesOpenVPNeasy-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 FilesOpenVPNeasy-rsapkica.crt»
  • Ключ центра сертификации «C:Program FilesOpenVPNeasy-rsapkiprivateca.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 FilesOpenVPNeasy-rsapkiissuedserver.crt»)

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

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

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

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

cd C:Program FilesOpenVPNbin
openvpn --genkey secret ta.key

Должен появиться файл «C:Program FilesOpenVPNbinta.key». Переместите его в каталог C:Program FilesOpenVPNeasy-rsapki

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

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

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

пароль для защиты ключа клиента easyrsa

Данный ключ («C:Program FilesOpenVPNeasy-rsapkiprivatekbuldogov.key») нужно передать клиенту и сообщить пароль. Клиент может снять защиту паролем для ключа:

openssl rsa -in "C:Program FilesOpenVPNeasy-rsapkiprivatekbuldogov.key"-out "C:Program FilesOpenVPNeasy-rsapkiprivatekbuldogov_use.key"

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

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

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

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

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

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

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

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

copy "C:Program FilesOpenVPNsample-configserver.ovpn" "C:Program FilesOpenVPNconfig-autoserver.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 FilesOpenVPNlogserver.log»

сетевой адаптер openvpn wintun

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

Options error: In C:Program FilesOpenVPNconfig-autoserver.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 «HKLMSYSTEMCurrentControlSetServicesTcpipParameters» /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 в openvpn клиент

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

Если все настроено правильно, появится такая картинка. подключение к openvpn установлено

Проверьте теперь лог OpenVPN на клиенте «C:Program FilesOpenVPN Connectagent.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 FilesOpenVPNlogopenvpn.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

Обновлено Обновлено: 04.01.2023
Опубликовано Опубликовано: 25.01.2017

OpenVPN позволяет настроить VPN-сервер как на платформе Windows Server, так и версии для рабочего компьютера (Windows 10, 8, 7).

Установка сервера
Создание сертификатов
Настройка OpenVPN
Настройка клиента
Доступ к локальной сети
Решение проблем

Установка OpenVPN Server

Переходим на официальный сайт OpenVPN и скачиваем последнюю версию программы для соответствующей версии Windows:

Скачиваем OpenVPN для Windows

Запускаем скачанный файл — нажимаем NextI Agree — и выставляем галочку EasyRSA 2/3 Certificate Management Scripts (нужен для возможности сгенерировать сертификаты):

Во время установки, ставим галочку EasyRSA 2 Certificate Management Scripts

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

… снова Next и Install — начнется установка. В процессе мастер может выдать запрос на подтверждение установки виртуального сетевого адаптера — соглашаемся (Install/Установить).

После завершения нажимаем Next — снимаем галочку Show ReadmeFinish.

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

Новая версия OpenVPN позволяет создавать сертификаты на основе Easy RSA 3, старая работает на базе 2-й версии. Наши действия будут различаться в зависимости от данной версии. Рассмотрим процесс формирования сертификата с использованием как RSA3, так и RSA2.

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

1. Переходим в папку установки OpenVPN (по умолчанию, C:Program FilesOpenVPN) и создаем каталог ssl.

2. После переходим в папку C:Program FilesOpenVPNeasy-rsa, переименовываем файл vars.example в vars, открываем его на редактирование и правим одну строку:

set_var EASYRSA_TEMP_DIR «$EASYRSA_PKI/temp»

* мы снимаем комментарий и добавляем temp в конце $EASYRSA_PKI. Если это не сделать, то при попытке сформировать корневого сертификата мы получим ошибку Failed create CA private key.

3. Запускаем командную строку от имени администратора:

Запуск командной строки от имени администратора

4. Переходим в каталог easy-rsa:

cd %ProgramFiles%OpenVPNeasy-rsa

5. Запускаем команду:

EasyRSA-Start.bat

Мы окажемся в среде EasyRSA Shell.

6. Инициализируем PKI:

./easyrsa init-pki

Если система вернет ошибку, выходим из оболочки EasyRSA Shell:

exit

И заходим снова:

EasyRSA-Start.bat

Мы должны увидеть:

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

7. Генерируем корневой сертификат (CA):

./easyrsa build-ca

… после ввода Enter обязательно задаем пароль дважды. На запрос ввести Common Name можно просто нажать ввод или написать свое имя:

Common Name (eg: your user, host, or server name) [Easy-RSA CA]:

8. Создаем ключ Диффи-Хеллмана:

./easyrsa gen-dh

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

./easyrsa gen-req cert nopass

* на запрос ввода Common Name просто вводим Enter.

… и на его основе — сам сертификат:

./easyrsa sign-req server cert

После ввода команды подтверждаем правильность данных, введя yes:

  Confirm request details: yes

… и вводим пароль, который указывали при создании корневого сертификата.

10. Сертификаты сервера готовы и находятся в каталоге pki. Переносим в C:Program FilesOpenVPNssl следующие файлы:

  • ca.crt
  • issued/cert.crt
  • private/cert.key
  • dh.pem

б) Создание сертификатов с RSA 2 (для старых версий OpenVPN)

1. Переходим в папку установки OpenVPN (по умолчанию, C:Program FilesOpenVPN) и создаем каталог ssl.

2. После переходим в папку C:Program FilesOpenVPNeasy-rsa, создаем файл vars.bat, открываем его на редактирование и приводим к следующему виду:

set «PATH=%PATH%;%ProgramFiles%OpenVPNbin»
set HOME=%ProgramFiles%OpenVPNeasy-rsa
set KEY_CONFIG=openssl-1.0.0.cnf
set KEY_DIR=keys
set KEY_SIZE=2048
set KEY_COUNTRY=RU
set KEY_PROVINCE=Sankt-Petersburg
set KEY_CITY=Sankt-Petersburg
set KEY_ORG=Organization
set KEY_EMAIL=master@dmosk.ru
set KEY_CN=DMOSK
set KEY_OU=DMOSK
set KEY_NAME=server.domain.ru
set PKCS11_MODULE_PATH=DMOSK
set PKCS11_PIN=12345678

* в каталоге easy-rsa уже есть файл vars.bat.sample — можно переименовать и использовать его.
** значение HOME не меняем, если оставили путь установки программы по умолчанию; KEY_DIR — каталог, куда будут генерироваться сертификаты; KEY_CONFIG может быть разным — его лучше посмотреть в файле vars.bat.sample или по названию соответствующего файла в папке easy-rsa; KEY_NAME желательно, чтобы соответствовал полному имени VPN-сервера; остальные опции можно заполнить произвольно.

3. Запускаем командную строку от имени администратора:

Запуск командной строки от имени администратора

4. Переходим в каталог easy-rsa:

cd %ProgramFiles%OpenVPNeasy-rsa

4. Запускаем vars.bat:

vars.bat

5. Чистим каталоги от устаревшей информации:

clean-all.bat

* данная команда выполняется один раз, когда на сервере нет информации по ранее созданным сертификатам.

6. Снова запускаем vars.bat (после clean переопределяются некоторые переменные):

vars.bat

Переходим к созданию ключей.

7. Генерируем последовательность центра сертификации:

build-ca.bat

На все запросы нажимаем Enter.

8. Запускаем build-dh.bat (сертификат с использованием алгоритма Диффи-Хеллмана):

openssl dhparam -out keysdh.pem 2048

* команда может выполняться долго — это нормально.

9. Генерируем сертификат для сервера:

build-key-server.bat cert

* где cert — имя сертификата; на все запросы нажимаем Enter. В конце подтверждаем два раза корректность информации вводом y.

10. После переносим из папки C:Program FilesOpenVPNeasy-rsakeys в C:Program FilesOpenVPNssl следующие файлы:

  • ca.crt
  • cert.crt
  • cert.key
  • dh.pem

Настройка сервера

Переходим в папку C:Program FilesOpenVPNconfig-auto (или для старой версии C:Program FilesOpenVPNconfig) и создаем файл server.ovpn. Открываем его на редактирование и приводим к следующему виду:

port 443
proto udp
dev tun
dev-node «VPN Server»
dh «C:\Program Files\OpenVPN\ssl\dh.pem»
ca «C:\Program Files\OpenVPN\ssl\ca.crt»
cert «C:\Program Files\OpenVPN\ssl\cert.crt»
key «C:\Program Files\OpenVPN\ssl\cert.key»
server 172.16.10.0 255.255.255.0
max-clients 32
keepalive 10 120
client-to-client
compress
fast-io
cipher AES-256-GCM
persist-key
persist-tun
status «C:\Program Files\OpenVPN\log\status.log»
log «C:\Program Files\OpenVPN\log\openvpn.log»
verb 4
mute 20

* где port — сетевой порт (443 позволит избежать проблем при использовании Интернета в общественных местах, но может быть любым из свободных, например 1194, занятые порты в Windows можно посмотреть командой netstat -a); dev-node — название сетевого интерфейса; server — подсеть, в которой будут работать как сам сервер, так и подключенные к нему клиенты.
** так как в некоторых путях есть пробелы, параметр заносится в кавычках.
*** при использовании другого порта необходимо проверить, что он открыт в брандмауэре или на время тестирования отключить его.

В сетевых подключениях Windows открываем управление адаптерами — TAP-адаптер переименовываем в «VPN Server» (как у нас указано в конфигурационном файле, разделе dev-node):

Переименовываем сетевой интерфейс в Windows

Теперь открываем службы Windows и находим «OpenVpnService». Открываем ее, настраиваем на автозапуск и включаем:

Настраиваем автозапуск OpenVpnService и включаем ее

Если служба в запущенном состоянии, то перезапускаем ее.

Ранее переименованный сетевой интерфейс должен включиться:

Включенный TAP адаптер

VPN-сервер работает. Проверьте, что сетевой адаптер VPN Server получил IP 172.16.10.1. Если он получает что-то, на подобие, 169.254…, выключаем сетевой адаптер — перезапускаем службу OpenVpnService и снова включаем сетевой адаптер.

Если в нашей системе включен брандмауэр, необходимо открыть порт для OpenVPN. Это быстрее всего сделать из командной строки — открываем ее от администратора и вводим:

netsh advfirewall firewall add rule name=»ALLOW OpenVPN» dir=in action=allow protocol=UDP localport=443

* где 443 — наш порт, который мы решили задействовать под OpenVPN; UDP — протокол, который мы настроили в конфигурационном файле сервера.

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

На сервере

На сервере генерируем сертификат для клиента. Для этого сначала чистим файл index.txt в папке C:Program FilesOpenVPNeasy-rsakeys.

Затем запускаем командную строку от имени администратора:

Запуск командной строки от имени администратора

Переходим в каталог easy-rsa:

cd %ProgramFiles%OpenVPNeasy-rsa

Далее наши действия зависят от версии RSA.

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

Запускаем команду:

EasyRSA-Start.bat

Мы окажемся в среде EasyRSA Shell.

Создаем клиентский сертификат:

./easyrsa gen-req client1 nopass

./easyrsa sign-req client client1

Мы должны увидеть запрос на подтверждение намерения выпустить сертификат — вводим yes:

  Confirm request details: yes

* в данном примере будет создан сертификат для client1.

После вводим пароль, который указывали при создании корневого сертификата.

Теперь из папки pki копируем файлы:

  • issued/client1.crt
  • private/client1.key
  • ca.crt
  • dh.pem

… и переносим их на клиентский компьютер.

б) Создание сертификатов с RSA 2 (для очень старых версий OpenVPN)

Запускаем vars.bat:

vars.bat

И генерируем сертификат первого пользователя:

build-key.bat client1

* на все запросы наживаем Enter, кроме Common Name — в данном поле вводим имя клиента (в нашем случае, просто client1). В конце подтверждаем введенную информацию — y.
** На каждого клиента нужно сгенерировать свой сертификат, в противном случае, им будет присваиваться один и тот же IP-адрес, что будет приводить к конфликту.

Получиться, что-то на подобие:

Country Name (2 letter code) [RU]:
State or Province Name (full name) [Sankt-Petersburg]:
Locality Name (eg, city) [Sankt-Petersburg]:
Organization Name (eg, company) [Organization]:
Organizational Unit Name (eg, section) [DMOSK]:
Common Name (eg, your name or your server’s hostname) [DMOSK]:client1
Name [server.domain.ru]:
Email Address [master@dmosk.ru]:

По умолчанию, для Common Name будет подставляться значение из vars.bat — но с ним сертификат не будет создаваться. Необходимо при создании каждого ключа подставлять значение, равное имени сертификата. Например, как выше — подставлено client1.

Теперь из папки keys копируем файлы:

  • client1.crt
  • client1.key
  • ca.crt
  • dh.pem

… и переносим их на клиентский компьютер.

На клиенте

Заходим на официальную страницу загрузки openvpn и скачиваем клиента для Windows:

Скачиваем OpenVPN для Windows

* по сути, это тот же файл, который скачивался для сервера.

Запускаем скачанный файл и устанавливаем программу, нажимая «Далее».

Переходим в папку C:Program FilesOpenVPNconfig. И копируем в нее сертификаты, которые перенесли с сервера.

Теперь открываем блокнот от имени администратора и вставляем следующие строки:

client
resolv-retry infinite
nobind
remote 192.168.0.15 443
proto udp
dev tun
compress
fast-io
cipher AES-256-GCM
ca ca.crt
cert client1.crt
key client1.key
dh dh.pem
float
keepalive 10 120
persist-key
persist-tun
verb 0

* где 192.168.0.15 443 — IP-адрес OpenVPN-сервера и порт, на котором он принимает запросы. Для боевой среды это будет внешний адрес.

Сохраняем файл с именем config.ovpn в папке C:Program FilesOpenVPNconfig.

Запускаем с рабочего стола программу «OpenVPN GUI» от имени администратора (это важно).

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

Запуск подключения openvpn-клиента к серверу

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

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

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

1. Настройка реестра

Для включения IP маршрутизации в Windows необходимо в ветке реестра HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters найти параметр IPEnableRouter и задать ему значение 1. Это можно сделать в утилите редактирования реестра (regedit) или командой:

reg add «HKLMSYSTEMCurrentControlSetServicesTcpipParameters» /v IPEnableRouter /t REG_DWORD /d 1 /f

* командную строку необходимо запускать от администратора.

2. Настройка OpenVPN Server

В конфигурационный файл OpenVPN добавим:

push «route 172.16.10.0 255.255.255.0»
push «route 192.168.2.0 255.255.255.0»

* где 172.16.10.0 — VPN сеть; 192.168.2.0 — локальная сеть, в которую необходимо «попасть» пользователям openvpn.

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

push «dhcp-option DNS 192.168.0.15»
push «dhcp-option DNS 192.168.0.16»
push «dhcp-option DOMAIN dmosk.local»

* где 192.168.0.15 и 192.168.0.16 — внутренние DNS-серверы; dmosk.local — домен, который будет добавляться к узлам, обращение к которым идет по неполному имени.

Если нам нужно, чтобы все запросы клиента (в том числе, Интернет) ходили через сервер OpenVPN, добавляем:

push «redirect-gateway def1»

* в таком случае, нам не обязательно добавлять push route, который мы использовали выше.

Перезагружаем службу OpenVpnService.

3. Разрешаем доступ к локальной сети

Заходим в управление сетевыми подключениями (Панель управленияСеть и ИнтернетСетевые подключения). Кликаем правой кнопкой мыши по адаптеру локальной сети — Свойства:

Открываем свойства сетевого адаптера для локальной сети

На вкладке Доступ ставим галочку Разрешить другим пользователям сети использовать подключение к Интернету данного компьютера:

Скачиваем OpenVPN для Windows

… и сохраняем настройки.

Возможные проблемы

Большая часть проблем решается при помощи логов, которые находятся в папке C:Program FilesOpenVPNlog. Уровень детализации лога контролируется параметром verb в конфигурационном файле сервера или клиента.

Также возможны следующие часто возникающие проблемы:

  1. Проблема: клиент постоянно пытается подключиться к серверу, но соединения не происходит или подключение зависает.
    Причина: сервер блокирует подключения по настроенному порту VPN (в нашем примере, 443).
    Решение: на сервере необходимо добавить 443 порт в исключения брандмауэра или отключить последний.
     
  2. Проблема: при попытке подключиться к серверу выскакивает ошибка «Не удалось подключиться к config».
    Причина: ошибка в настройках.
    Решение: перепроверьте каждую строчку файла конфигурации. Проверьте наличие всех файлов, на которые ссылаетесь в настройках.
     
  3. Проблема: клиенты получают одинаковые IP-адреса.
    Причина: подключение выполняется под одним и тем же пользователем.
    Решение: сервер выдает одинаковые адреса одинаковым клиентам. Необходимо настроить авторизацию на сервере и выдать каждому клиенту индивидуальные настройки.
     
  4. Проблема: соединение происходит, но через несколько минут связь прерывается.
    Причина: дублирование IP-адресов.
    Решение: данная проблема описана выше (пункт 3).

Возможно, Вы это тоже захотите попробовать

  1. Настройка OpenVPN-сервера с аутентификацией через LDAP (Active Directory) на Ubuntu Server
  2. Установка и настройка OpenVPN на Linux CentOS 7

Установим и настроим OpenVPN сервер. На сервере используется операционная система Windows Server 2019.

OpenVPN — бесплатная реализация технологии виртуальной частной сети (VPN) для создания зашифрованных каналов связи между компьютерами типа точка-точка или сервер-клиенты за NAT и Firewall.

Установка OpenVPN Server

Скачиваем дистрибутив для установки OpenVPN:

Community Downloads

vpn

Прокручиваем вниз, выбираем стабильную версию. Я буду использовать версию 2.4.9.

Для операционной системы Windows доступны два пакета:

  • WINDOWS 7/8/8.1/SERVER 2012R2 INSTALLER (NSIS)
  • WINDOWS 10/SERVER 2016/SERVER 2019 INSTALLER (NSIS)

Для Windows Server 2019 подходит второй вариант, скачиваю.

vpn

Запускаем инсталлятор OpenVPN.

vpn

Открывается мастер установки. Next.

vpn

Принимаем лицензионное соглашение. I Agree.

vpn

Выбираем компоненты. Выделите EasyRSA 2 Certificate Management Scripts. Для сервера OpenVPN GUI можно не устанавливать, если вы планируете запускать OpenVPN в качестве службы. Next.

vpn

Выбираем путь установки, я оставляю по умолчанию C:Program FilesOpenVPN. Install.

vpn

Начинается процесс установки OpenVPN.

vpn

Установка успешно завершена. Next.

vpn

Finish.

vpn

Установка выполнена в директорию C:Program FilesOpenVPN.

vpn

После установки у нас появляется новый сетевой адаптер TAP-Windows Adapter V9.

vpn

Адаптер отключён. Если по каким-то причинам нужно добавить несколько таких адаптеров, то загляните в папку C:Program FilesTAP-Windowsbin.

vpn

Здесь есть скрипты для установки адаптера, добавления адаптера и удаления всех адаптеров.

vpn

Пример установки адаптера. В командной строке под администратором:

cd "C:Program FilesTAP-Windowsbin"
"C:Program FilesTAP-Windowsbintapinstall.exe" install "C:Program FilesTAP-WindowsdriverOemVista.inf" tap0901

В большинстве случаев дополнительно настраивать сетевой адаптер не требуется.

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

Запускаем командную строку под администратором и переходим в рабочую директорию C:Program FilesOpenVPNeasy-rsa.

cd C:Program FilesOpenVPNeasy-rsa

В этой папке есть всё необходимое для генерации сертификатов.

vpn

Выполняем:

init-config.bat
copy vars.bat.sample vars.bat

Создаётся файл vars.bat с настройками и примером готовых параметров для создания CSR запроса сертификатов. Заполним его. Открываем vars.bat блокнотом.

notepad vars.bat

vpn

Открывается vars.bat.

vpn

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

vpn

Заполняем переменные в нижней части файла, указываем:

  • KEY_COUNTRY — страна
  • KEY_PROVINCE — область
  • KEY_CITY — город
  • KEY_ORG — организация
  • KEY_EMAIL — e-mail
  • KEY_CN — (Common Name) имя сервера
  • KEY_NAME — (Name) имя сервера
  • KEY_OU — (Organization Unit) отдел
  • PKCS11_MODULE_PATH — для токенов двухфакторной аутентификации, нам не требуется, укажу имя сервера
  • PKC11_PIN — ПИН для токенов двухфакторной аутентификации, нам не требуется, укажу 1234

Для каждого сертификата нужно будет указывать свои NAME и COMMON NAME, можно их не указывать в vars.bat, потому как при генерации все параметры будут запрашивать.

Обращаем внимание на строку:

set KEY_KONFIG=openssl-1.0.0.cnf

Это имя конфигурационного файла. Находим его в рабочей директории.

vpn

Откроем блокнотом.

vpn

Внутри есть параметр default_days, в котором можно указать срок действия будущих сертификатов. По умолчанию у меня стоит 3650 дней, это 10 лет. Меня устраивает. Вероятно, кому-то при генерации клиентских сертификатов может понадобиться уменьшить этот срок.

Сохраняем все изменения и возвращаемся к командной строке. Подгружаем утверждённые нами переменные:

vars.bat

vpn

Очищаем директорию с ключами:

clean-all.bat

vpn

Сертификаты, которые мы будем создавать, появятся в папке C:Program FilesOpenVPNeasy-rsakeys. Сейчас эта папка очистилась, в ней два файла: index.txt и serial.

vpn

Генерируем ключ и сертификат центра сертификации:

build-ca.bat

vpn

В процессе генерации сертификата нас будут спрашивать все те же параметры, которые мы указали в vars.bat. Если параметр нас устраивает (а он нас устраивает), просто нажимаем ввод и переходим к следующему вопросу. После завершения работы скрипта в папке C:Program FilesOpenVPNeasy-rsakeys появляется два файла:

  • ca.crt — сертификат центра сертификации
  • ca.key — ключ центра сертификации

Ключ секретный, никому не передавайте, он будет храниться на сервере.

vpn

Генерируем ключ Диффи-Хеллмана:

build-dh.bat

vpn

В папке C:Program FilesOpenVPNeasy-rsakeys появляется файл:

  • dh2048.pem

vpn

Генерируем ключ и сертификат сервера, назовём сервер именем «server«:

build-key-server.bat server

vpn

В процессе генерации серверного сертификата нас будут спрашивать те же параметры, которые мы указали в vars.bat. Если параметр нас устраивает (а он нас снова устраивает), просто нажимаем ввод и переходим к следующему вопросу. На вопрос Sign the certificate отвечаем y. На вопрос 1 out of 1 certificate requests certified, commit отвечаем y.

После завершения работы скрипта в папке C:Program FilesOpenVPNeasy-rsakeys появляется четыре файла:

  • 01.pem — не понадобится
  • server.crt — сертификат сервера
  • server.csr — запрос сертификата сервера, не понадобится
  • server.key — ключ сервера

Ключ секретный, никому не передавайте, он будет храниться на сервере.

vpn

Генерируем ключ и сертификат первого клиента. Для каждого клиента нужно указывать своё имя файла, Name и Common Name. Назовём первого клиента именем «client«:

build-key.bat client

vpn

В процессе генерации клиентского сертификата нас будут спрашивать те же параметры, которые мы указали в vars.bat. Нас устраивают все параметры кроме NAME и COMMON NAME, на них отвечаем client. Помним, что для другого клиента имя должно быть другим. На вопрос Sign the certificate отвечаем y. На вопрос 1 out of 1 certificate requests certified, commit отвечаем y.

После завершения работы скрипта в папке C:Program FilesOpenVPNeasy-rsakeys появляется четыре файла:

  • 02.pem — не понадобится
  • client.crt — сертификат первого клиента
  • client.csr — запрос сертификата первого клиента, не понадобится
  • client.key — ключ первого клиента

vpn

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

В настройках сервера можно потом включить настройку duplicate-cn, которая позволяет подключаться всем клиентам по одному общему сертификату, но это небезопасно и не рекомендуется. Используйте только в тестовых целях.

# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names. This is recommended
# only for testing purposes. For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE «COMMON NAME»,
# UNCOMMENT THIS LINE OUT.
;duplicate-cn

Я на сервере собираюсь использовать tls-auth для дополнительной проверки целостности, это обеспечит дополнительный уровень безопасности протокола SSL/TLS при создании соединения:

  • Сканирование прослушиваемых VPN-сервером портов
  • Инициация SSL/TLS-соединения несанкционированной машиной на раннем этапе
  • DoS-атаки и флуд на порты OpenVPN
  • Переполнение буфера SSL/TLS

При использовании tls-auth на клиенте не понадобится ключ Диффи-Хеллмана, но пусть будет. Генерируем ключ tls-auth:

openvpn --genkey --secret keys/ta.key

vpn

В папке C:Program FilesOpenVPNeasy-rsakeys появляется файл:

  • ta.key

vpn

Минимальный набор сертификатов сгенерирован.

Настройка OpenVPN сервера

Чтобы случайно всё не удалить, создадим папку C:Program FilesOpenVPNssl и скопируем в неё сертификаты. Это будет рабочая папка сервера.

mkdir "C:Program FilesOpenVPNssl"
copy "C:Program FilesOpenVPNeasy-rsakeys" "C:Program FilesOpenVPNssl"

vpn

Создадим конфигурационный файл сервера C:Program FilesOpenVPNconfigserver.ovpn:

copy "C:Program FilesOpenVPNsample-configserver.ovpn" "C:Program FilesOpenVPNconfigserver.ovpn"

Открываем блокнотом и редактируем:

notepad "C:Program FilesOpenVPNconfigserver.ovpn"

Лучше изучить конфигурационный файл, я предлагаю свой вариант конфига:

port 1194
proto udp
dev tun
ca "C:\Program Files\OpenVPN\ssl\ca.crt"
cert "C:\Program Files\OpenVPN\ssl\server.crt"
key "C:\Program Files\OpenVPN\ssl\server.key"  # This file should be kept secret
dh "C:\Program Files\OpenVPN\ssl\dh2048.pem"
server 10.8.0.0 255.255.255.0
tls-auth "C:\Program Files\OpenVPN\ssl\ta.key" 0 # This file is secret
keepalive 10 120
comp-lzo
persist-key
persist-tun
cipher AES-256-CBC
status "C:\Program Files\OpenVPN\log\status.log"
log "C:\Program Files\OpenVPN\log\openvpn.log"
verb 4
mute 20

Указываем параметры сервера, пути к ключам и сертификатам. Здесь же пути к логам. Для тестирования можно использовать tcp протокол:

proto tcp

Переходим к службам:

services.msc

vpn

Находим службу OpenVPNService.

vpn

Настраиваем на автоматический запуск при загрузке сервера.

vpn

Запускаем службу.

vpn

Согласно настройкам сервера в папке C:Program FilesOpenVPNlog должны появиться логи. Это один из инструментов администратора OpenVPN сервера.

vpn

Активировался сетевой адаптер TAP-Windows Adapter V9.

vpn

Согласно настройкам сервера IP адрес 10.8.0.1.

vpn

Проверяем поднялся ли порт tcp 1194:

netstat -tan | find "1194"

Порт должен прослушиваться.

vpn

Теперь нужно настроить firewall. Открываем Windows Defender Firewall with Advanced Security.

vpn

Переходим в Inbound Rules.

vpn

Создаём правило — New Rule…

vpn

Тип правила — Port. Next.

vpn

Протоколы и порты — UDP 1194. Как в настройках сервера. Next.

vpn

Действия — Allow the connection. Next.

vpn

Для всех сетей. Next.

vpn

Указываем название правила — OpenVPN. Next.

Правило создано, теперь firewall не блокирует входящие UDP соединения на 1194 порту.

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

На компьютере клиента устанавливаем OpenVPN точно также как на сервер. Галку EasyRSA 2 Certificate Management Scripts не указываем. Галку OpenVPN GUI указываем.

vpn

Я устанавливаю OpenVPN на клиенте в папку по умолчанию. C:Program FilesOpenVPN.

Копируем в отдельную папку for_client (её содержимое отправим потом на компьютер клиента) на сервере файлы для клиента:

  • ca.crt
  • client.crt
  • client.key
  • dh2048.pem
  • ta.key

vpn

Туда же из папки C:Program FilesOpenVPNsample-config копируем client.ovpn

vpn

Переименовываю client.ovpn в config.ovpn. Можно использовать любое имя, лучше созвучное с названием организации. Вот такой получился набор.

vpn

Редактируем файл config.ovpn.

client
dev tun
proto udp
remote internet-lab.ru 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca "C:\Program Files\OpenVPN\config\ca.crt"
cert "C:\Program Files\OpenVPN\config\client.crt"
key "C:\Program Files\OpenVPN\config\client.key"
tls-auth "C:\Program Files\OpenVPN\config\ta.key" 1
#dh "C:\Program Files\OpenVPN\config\dh2048.pem"
cipher AES-256-CBC
comp-lzo
verb 0
connect-retry-max 25

Здесь указываем пути к ключам и сертификатам клиента. Не забываем про адрес и порт сервера, куда подключаться, для примера я указал internet-lab.ru UDP 1194.

Отправляем подготовленные файлы на компьютер клиента и копируем в C:Program FilesOpenVPNconfig.

vpn

На клиента запускаем OpenVPN GUI.

vpn

В трее появляется значок OpenVPN.

vpn

Правой кнопкой — подключиться.

vpn

Устанавливается соединение.

vpn

Значок позеленел, назначен адрес 10.8.0.6.

vpn

Можно подключаться к серверу, если есть доступы.

vpn

Для второго и последующего клиента генерируем свой набор клиентских сертификатов.

vpn

Отзыв сертификата

Иногда нужно отозвать сертификат, выданный клиенту. Кто-то увольняется, кто-то палит сертификаты.

cd "C:Program FilesOpenVPNeasy-rsa"
vars.bat
revoke-full client

Где client — это имя клиента.

В папке C:Program FilesOpenVPNkeys появляется файл:

  • crl.pem

Копируем его с заменой в рабочую директорию сервера C:Program FilesOpenVPNssl.

Добавляем строчку в конфигурационный файл сервера:

crl-verify "C:\Program Files\OpenVPN\keys\crl.pem"  

Перезапускаем службу OpenVPN сервера.

net stop OpenVPNService
net start OpenVPNService

Если в конфигурационном файле уже был ранее указан путь к crl.pem, то службу можно не перезапускать, OpenVPN перечитывает CRL один раз в час. Но в течении этого часа клиенты с отозванными сертификатами смогут продолжать подключаться и работать.

Для клиента с отозванным сертификатом процесс подключения будет «зависать». В логе можно увидеть:

TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)
TLS Error: TLS handshake failed

Чтобы клиент не стучался постоянно на сервер, у него в конфиге есть опция:

connect-retry-max 25

Передать эту опцию при отзыве сертификата нельзя, поэтому указывайте её всем клиентам заранее.

Ссылки

OpenVPN 2.5.1 сервер на Windows

Skip to content

Cloud Orchestration Logo

How to Install and Configure OpenVPN on Windows 10

How to Install and Configure OpenVPN on Windows 10

  • View Larger Image

Introduction

In this blog article we are going to discuss about How to Install and Configure OpenVPN on Windows 10. A VPN is short form of virtual private network, which gives us a privacy, anonymity and security over public internet. A VPN service masks our ISP IP so your online actions are virtually untraceable. A VPN can also be used to connect computers to isolated remote computer networks that is usually inaccessible, by using the Internet or another intermediate network.

We can define OpenVPN as a full-featured SSL VPN. OpenVPN uses OSI layer 2 or 3 secure network extension using the industry standard SSL/TLS protocol. OpenVPN supports flexible client authentication methods based on certificates, smart cards and username/password credentials. OpenVPN is not a web application proxy and does not operate through a web browser. OpenVPN server process over a single TCP or UDP port. The default port number is 1194. OpenVPN 2.3 includes a large number of improvements, including full IPv6 support and PolarSSL support.

OpenVPN is also the name of the open source project started by our co-founder and which uses the GPL license. He developed the OpenVPN project that used to encrypt and secure point-to-point or site-to-site connection between two machines over the public Internet. In other word using OpenVPN we can create a secure Private network over public Internet and will have Remote access to internal services of your IT infrastructure.

Use Cases of OpenVPN

Secure Remote Access
Site-to-site , Users-to-Site or Users-to-Users connectivity to bring networks together
Protect screen sharing and remote desktop communications
Encrypt sensitive IoT communications
Secure Access to Cloud-Based Systems

OpenVPN available as Below.

  1. OpenVPN Community Edition, which is a free and open-source version
  2. OpenVPN Access Server (OpenVPN-AS), is based on the Community Edition, but provides additional paid and proprietary features like LDAP integration, Easy Management Admin Portal ,cluster option etc.
  3. OpenVPN-as-a-Service, solution eliminates the need for VPN server installation. By Purchasing OpenVPN Cloud we can simply connect to our hosted service with regions around the globe.

Apart from OpenVPN Community Edition, the other two OpenVPN editions has Economical licensing model that is based only on the number of simultaneous VPN connecting users or devices.

The OpenVPN Community Edition totally free to use and there is no user limitations. OpenVPN community edition server can be installed on Linux or Windows Based systems.

OpenVPN for Windows

It can be installed from the self-installing exe file which is called OpenVPN GUI. OpenVPN GUI is a graphical fronted for OpenVPN running on Windows. It creates an icon in the notification area from which you can control OpenVPN to start/stop your VPN tunnels, view the log and do other useful things.

OpenVPN Connect client

It is the OpenVPN client software packages installing on client PC. This client package used to connect to the OpenVPN server. OpenVPN Connect client supported on Windows, Linux, MacOS, IOS and Android.

Setting Up OpenVPN Server.

In this article will show you how to Setup up a OpenVPN Server ( Community Edition) On Windows 10 to forward incoming traffic to the internet, then route the responses back to the client. This is a Users-to-Site Model.Which means settings up a OpenVPN  Server to tunnel clients internet traffic through OpenVPN server. Those clients that successfully connected to the OpenVPN server will have their ISP IP Address will show as servers Public IP address.Commonly, a VPN tunnel is used to privately access the internet, evading censorship or Geo location by shielding your computer’s web traffic when connecting through entrusted hotspots, or connections.

Section 1. Installing OpenVPN Server

Let’s get Started. First thing is Download the latest Windows 64-bit MSI installer for OpenVPN Community edition from official OpenVPN Website, under community section.

The OpenVPN executable should be installed on both server and client machines, since the single executable provides both client and server functions.

Once Downloaded right click the installer exe file and choose install option.

The following screen will appear, click “Customise”  to start the installation.

Make sure to choose all features by clicking the icon next to each features and selecting the option “Entire feature will be installed on local hard drive”.  Below are the two features which will not be installed by default and we need to select during install.

Openssl utilities , EasyRSA 3 Certificate Management scripts

OpenVPN service.

Click Install Now button after selecting all features.

The install will get completed and we will get below screen. Click Close. The default  install location will be C:Program FilesOpenVPN

We will get a warning message as ” No readable connection profiles ( config files ) found. Its fine , click OK.

This Completes the OpenVPN MSI Package install. After the install,  Under Windows 10 “Network and Internet ” settings  >>  Under Ethernet >> Change adaptor options >> We can see a new network adaptor named OpenVPN TAP device created.

Now we can manage  the OpenVPN service either  from Windows Start Menu -> Control Panel -> Administrative Tools -> Services section.

As of OpenVPN version 2.5.0,While starting the OpenVPN wrapper service the OpenVPN will look for .ovpn configuration file under folder “C:Program FilesOpenVPNconfig-auto” to auto-start OpenVPN service when ever our Windows 10 reboots.

Another option to start/stop OpenVPN service is  Click on Windows hidden notification area from task bar , there we can see the OpenVPN icon, right click on it and you will see multiple options including Connect and Disconnect.

If you don’t see the OpenVPN icon in the Windows task bar notification area, double click the OpenVPN icon available in the desktop and that will make the OpenVPN icon available at the windows task bar notification area.

For better understanding refer below screenshot.

As I mentioned earlier As of OpenVPN version 2.5.0,  when we start the OpenVPN service using the GUI component under windows task bar notification area, the OpenVPN will look for .ovpn configuration file under folder “C:Program FilesOpenVPNconfig”.

This Concludes the OpenVPN Package install on Windows 10 for Server and for the Client PC. Now lets move to the next section.

Section 2. Setup Master Certificate Authority (CA) and Generate Certificates and keys for OpenVPN Server and Clients.

OpenVPN uses public-key infrastructure (PKI) for certificate generation and Management. It is the technology behind digital certificates. There for, PKI is the technology that allows you to encrypt data, digitally sign documents, and authenticate yourself using certificates.

The PKI consists of:

  1. A separate certificate (also known as a public key) and private key for the server and each client, and
  2. A master Certificate Authority (CA) certificate and key which is used to sign each of the server and client certificates.

For PKI management,  The latest version of OpenVPN packages provided  easy-rsa 3, a set of scripts which is bundled with OpenVPN MSI.

The easy-rsa3 scripts folder location should be “C:Program FilesOpenVPNeasy-rsa”.  Also the Easy-RSA 3 runs POSIX shell code, so use on Windows has some additional
requirements such as  an OpenSSL installation, and a usable shell environment but  Windows packages of EasyRSA 3.0.7+ include an OpenSSL binary and libraries that will be used by default. So basically we don’t need to perform the OpenSSL install separately in our Windows Install.

Additionally The Easy-RSA 3 Windows release includes a ready-to-use shell environment  where we can run the commands that needed to issue SSL/TSL certificates. So lets proceed with the SSL/TLS certificate creation along with CA certificate using easy-rsa3 scripts.

First thing is go the folder “C:Program FilesOpenVPNeasy-rsa” using Windows File explorer.  Copy the file named “vars.example” to file named “vars“.

The “vars “ file contains built-in  Easy-RSA configuration settings.  The default settings are fine unless if we need any custom changes.  Few configurable options given in below table.

Variables Default Value Usage
set_var EASYRSA
C:Program FilesOpenVPNeasy-rsa Defines the folder location of easy-rsa scripts
set_var EASYRSA_OPENSSL C:Program FilesOpenVPNbinopenssl.exe Defines the OpenSSL binary path
set_var EASYRSA_PKI C:Program FilesOpenVPNeasy-rsapki The folder location of SSL/TLS file exists after creation
set_var EASYRSA_DN
cn_only
This is used to adjust what elements are included in the Subject field as the DN
set_var EASYRSA_REQ_COUNTRY “US” Our Organisation Country
set_var EASYRSA_REQ_PROVINCE “California” Our Organisation Province
set_var EASYRSA_REQ_CITY “San Francisco” Our Organisation City
set_var EASYRSA_REQ_ORG “Copyleft Certificate Co” Our Organisation Name
set_var EASYRSA_REQ_EMAIL “me@example.net” Our Organisation contact email
set_var EASYRSA_REQ_OU “My Organizational Unit” Our Organisation Unit name
set_var EASYRSA_KEY_SIZE
2048
Define the key pair size in bits
set_var EASYRSA_ALGO
rsa The default crypt mode
set_var EASYRSA_CA_EXPIRE
3650 The CA key expire days
set_var EASYRSA_CERT_EXPIRE
825 The Server certificate key expire days
set_var EASYRSA_NS_SUPPORT
“no” Support deprecated Netscape extension
set_var EASYRSA_NS_COMMENT “HAKASE-LABS CERTIFICATE AUTHORITY” Defines NS comment
set_var EASYRSA_EXT_DIR
"$EASYRSA/x509-types"
Defines the x509 extension directory
set_var EASYRSA_SSL_CONF
"$EASYRSA/openssl-easyrsa.cnf"
Defines the openssl config file location
set_var EASYRSA_DIGEST
"sha256"
Defines the cryptographic digest to use

So if you need to edit above default values, un-comment corresponding lines and make necessary changes. The “var”  also have other configurable options but I only mentioned few important variables.  So in our case we are fine with the default values and the default values  will be used  during certificate generation.

Now Open the windows command prompt and go the directory “C:Program FilesOpenVPNeasy-rsa”.  After that Launch EasyRSA shell. For that issue below commands.

Now we have entered the easy-rsa3 shell prompt and from there we will be able to issue easy-rsa3 scripts. Attached  a screenshot for reference.

Now Initiate the Public Key Infrastructure PKI directory. For that issue below command in the EasyRSA Shell.

Below the screenshot for reference. From there we can see the PKI directory is set to “C:Program FilesOpenVPNeasy-rsapki”

Now build the certificate authority (CA ) key using the command below.  This CA root certificate file later will be used to sign other certificates and keys. The option “nopass”  we  used is to disable password locking the CA certificate.

The command will be asked to enter the common name. Here I entered my VPN server Hostname which is OPENVPNSERVER, and it is a common practice. Here we are free to use any name or values.  Also the created the CA certificate will be saved to folder “C:Program FilesOpenVPNeasy-rsapki” with file name as “ca.crt”.  Refer below screenshot.

Now Build a server certificate and key using below command.   Here Replace <SERVER> with your own server name.  Also I used Option nopass for disabling password locking the key.

Attached a screenshot for your reference.  The issued server certificate will be in the folder “C:Program FilesOpenVPNeasy-rsapkiissued” with file name as SERVER.crt.

After that we can verify the issued server certificate using below openssl command in the EasyRSA shell itself. The Status Ok indicate that the certificate is fine.

Now Build a client certificate and key using below command. From that Replace <CLIENT> with your client name.  Also used Option nopass for disabling password locking the key.

Attached a screenshot for your reference. The issued client certificate will also be saved to folder “C:Program FilesOpenVPNeasy-rsapkiissued” with file name as “CLIENT.crt”.

After that we can verify the issued client certificate using below openssl command. The Ok indicate that the certificate is fine.

This Completed the CA certificate, Sever and Client Certificate Generation along with Key. These keys will be used to authenticate between OpenVPN server and with the Client.

Now Generate a shared-secret key that is used in addition to the standard RSA certificate/key. The file name is tls-auth.key.

Using this key we enable  tls-auth directive Which adds an additional HMAC signature to all SSL/TLS handshake packets for integrity verification. Any UDP packet not bearing the correct HMAC signature can be dropped without further processing.

Enabling the tls-auth will protect us from

  • DoS attacks or port flooding on the OpenVPN UDP port.
  • Port scanning to determine which server UDP ports are in a listening state.
  • Buffer overflow vulnerabilities in the SSL/TLS implementation.
  • SSL/TLS handshake initiations from unauthorised machines.

So first Download Easy-TLS   using the GitHub link https://github.com/TinCanTech/easy-tls. It is an Easy-RSA extension utility that we are using to generate tls-auth key.

Click the Download zip option which is available under code tab.  Refer below screenshot.

After that unzip the easy-tls-master folder and copy the files named “easytls”and “easytls-openssl.cnf” file to “C:Program FilesOpenVPNeasy-rsa” directory. Check below screenshot for reference.

Now go back to the EasyRSA  shell prompt and issue below command. This will initialise the easy-tls script utility.

Now after that generate the tls-auth key using below command.

The command will generate the tls-auth key file named “tls-auth.key”  under the folder “C:Program FilesOpenVPNeasy-rsapkieasytls”.  Refer below screenshot.

Now we need to Generate Diffie Hellman parameters.

Diffie Hellman parameters must be generated for the OpenVPN server.

These parameters define how OpenSSL performs the Diffie-Hellman (DH) key-exchange. Diffie–Hellman key exchange is a method of securely exchanging cryptographic keys over a public channel

Issue below command for generating Diffie Hellman parameters from the EasyRSA shell.

The command will create the DH file under folder “C:Program FilesOpenVPNeasy-rsapki” with file name as “dh.pem”.  Refer below screenshot.

This completes the generation of necessary SSL/TLS key files needed for OpenVPN service. We will be able to find the created files under below folders.

Folder Path Content
C:Program FilesOpenVPNeasy-rsapki CA file, DH file and other OpenSSL related files like config file
C:Program FilesOpenVPNeasy-rsapkiprivate Include the private key files of CA, Server and Client certificates
C:Program FilesOpenVPNeasy-rsapkieasytls Contains the tls-auth key
C:Program FilesOpenVPNeasy-rsapkiissued Contains issued Server and Client certificates

Refer below screenshot.

Also below is the short explanation of the relevant files.

Filename Needed By Purpose Secret
ca.crt server + all clients Root CA certificate No
ca.key Server Only Root CA key YES
dh.pem server only Diffie Hellman parameters No
SERVER.crt server only Server Certificate No
SERVER.key server only Server Key Yes
CLIENT.crt Client only Client Certificate No
CLIENT.key client only Client Key Yes
tls-auth.key server + all clients Used for tls-auth directive No

Now its the time to copy Certificate files ca.crt, CLIENT.crt, CLIENT.key  and tls-auth.key  from OpenVPN server to the OpenVPN client PC.  Make sure to copy secret files over a secure channel like SFTP.

Okay, this completes the creation of SSL/TLS certificates for the OpenVPN service. Now lets move to the next section.

Section 3 . Create configuration files for server

In this section, we create the OpenVPN Server configuration file and Make Necessary changes in it.

First Open Windows Explorer and go the folder “C:Program FilesOpenVPNsample-config” and copy file named “server.ovpn” to “C:Program FilesOpenVPNconfig”.

Refer Below Screenshot.

Now open the config file using any Text editor and make changes to below values accordingly.

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”

push “redirect-gateway def1 bypass-dhcp”

push “dhcp-option DNS 208.67.222.222”

push “dhcp-option DNS 208.67.220.220”

tls-auth “C:\Program Files\OpenVPN\easy-rsa\pki\easytls\tls-auth.key” 0

cipher AES-256-CBC

In that first four values defines the location of ca, cert , key and Diffie hellman parameters certificate locations.

The Next three lines enforce the clients to redirect their all traffic through OpenVPN server once they successfully connected to OpenVPN server.

Using “tls-auth” parameter, we enable HMAC firewall. Its an extra layer of security used to prevent DDos attack.

The last one “data-ciphers AES-256-CBC” enables a cryptographic cipher.

Refer below screenshots and then you will get an idea about how these parameters looks in server.ovpn config file.

This Completes the OpenVPN config file Setup. Now open the UDP Port 1194 in the Windows firewall using below power shell command.

Now start the OpenVPN server service by click on Windows Show hidden icons section >> right click the OpenVPN icon >> Choose Connect.

The OpenVPN service will start automatically and you will see a green colour inside OpenVPN icon. This means that our OpenVPN service is running.

Another Option to confirm the running of OpenVPN service is , take windows cmd and list all network interfaces. We will see now the OpenVPN TUN/TAP interface is assigned with private IP 10.8.0.1, which is the default private IP address range assigned to server and with clients as per the config settings.

Section 4. Enable Internet Connection Sharing (ICS) in Windows 10

As I mentioned in the introduction section we are setting up our OpenVPN server , to route clients all IP traffic such as Web browsing and DNS lookups through VPN Server itself. For that we need to share  the  public internet through OpenVPN server Public Interface that already have internet access to OpenVPN TUN/TAP Network interface.

  • So lets see how this can be accomplished. For that first go to the windows services section and Right-click “Routing and Remote Access” service. Choose Properties and make the startup type as Automatic. After that start the service.
  • After that go to VPN Server “Network and Internet ” settings >> Under Ethernet >> Change adaptor options >>  Right click the Network Adaptor name which is having Public Internet access and choose properties.

  • Choose Sharing tab and from there Tick the box “Allow other network users to connect through this computer’s Internet connection” option
  • From the drop-down list select “OpenVPN Tap-Windows6”, or whatever is the connection name of your TAP server connection.
  • Also if you needed you can tick the box next to ” Allow other network users to control or disable the shared internet connection” option
  • Click Ok and confirm the changes

  • Now edit the below registry  key value. For that run the  “regedit” in Windows Run.
Key Value Type Data
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters IPEnableRouter REG_DWORD 0x00000001 (1)

Okay, this completes Enable Internet Connection Sharing (ICS) in Windows 10. Now lets move to the next section. Also reconnect the OpenVPN connection again to take effect the changes.

Section 5 . Setup OpenVPN Client.

In this section we first install the OpenVPN MSI installer on Client PC like Windows 10. After that we will setup OpenVPN client config files.  Finally start the the OpenVPN connection and test it out.

Section 5 a . OpenVPN Client MSI Install

For OpenVPN MSI installation on Client PC, follow the same steps described on Section 1. The OpenVPN Community Edition MSI Installer can be used on both Server side and with the client side.

After the OpenVPN MSI installation. Open Windows Explorer and go the folder “C:Program FilesOpenVPNsample-config” and copy file named “client.ovpn” to “C:Program FilesOpenVPNconfig”.

Move already downloaded ca.crt, CLIENT.crt, CLIENT.key and tls-auth.key to folder “C:Program FilesOpenVPNconfig”.

Refer below screenshot for better understanding on file structure.

Section 5 b . Configure Client Config File.

Go to the folder “C:Program FilesOpenVPNconfig” and open client.ovpn file using any text editor and define below parameters accordingly.

remote 185.210.137.214 1194

ca “C:\Program Files\OpenVPN\config\ca.crt”

cert “C:\Program Files\OpenVPN\config\CLIENT.crt”

key “C:\Program Files\OpenVPN\config\CLIENT.key”

remote-cert-tls server

tls-auth “C:\Program Files\OpenVPN\config\tls-auth.key” 1

cipher AES-256-CBC

In that first value defines The hostname/IP and port of the OpenVPN server

The Next three ca, cert , key values defines the location of CA and client certificate locations.

Using “remote-cert-tls server” , the OpenVPN client will verify the server certificate extendedKeyUsage.

Using “tls-auth” parameter, we enable HMAC firewall. Its an extra layer of security used to prevent DDos attack.

The last one “cipher AES-256-CBC” enables a cryptographic cipher.

Below picture shows how these parameters looks in the client config file.

This Completes the Client Setup. Now test the VPN Connection from client side. Make sure to open UDP port 1194 in the client side windows firewall too.

Section 5 c . Testing the OpenVPN connection.

Under windows Hidden Notification area , right click on OpenVPN icon and Click Connect.

The OpenVPN connection will establish automatically. After the successful connection , try to ping to the private IP of OpenVPN server and make sure its reachable. Also test the internet connection of your client PC.

Also on a Successfully connected OpenVPN Client PC, if we lookup the what is my IP on web browser, we will see its our VPN Server IP. This means that all our web traffic is routing through OpenVPN server.

Conclusion.

We have successfully completed the OpenVPN setup On Windows 10 and successfully connected from a Windows 10 OpenVPN client PC. Also we have seen how to route all IP traffic from client side through OpenVPN server. I hope this article is informative. Leave your thoughts at the comment box.

Share This Story, Choose Your Platform!

Related Posts

17 Comments

  1. darp
    February 20, 2022 at 2:18 pm — Reply

    Hi,
    Cannot find easytls-openssl.cnf in zip.
    Thx.

    • admin
      March 13, 2022 at 4:44 am — Reply

      Yes, correct. Its not available in the updated zip and we don’t need to copy that file now. The command easytls will work with out that file.

  2. JJ
    March 14, 2022 at 6:10 pm — Reply

    Thank you for this clear tutorial, I followed every step, but am stuck with these errors in the log file:
    Can you please help!?

    2022-03-14 14:01:00 WARNING: –topology net30 support for server configs with IPv4 pools will be removed in a future release. Please migrate to –topology subnet as soon as possible.

    2022-03-14 14:01:00 DEPRECATED OPTION: –cipher set to ‘AES-256-CBC’ but missing in –data-ciphers (AES-256-GCM:AES-128-GCM). Future OpenVPN version will ignore –cipher for cipher negotiations. Add ‘AES-256-CBC’ to –data-ciphers or change –cipher ‘AES-256-CBC’ to –data-ciphers-fallback ‘AES-256-CBC’ to silence this warning.

    2022-03-14 14:01:00 Cannot pre-load keyfile (“C:Users[removed]OpenVPNtls-auth.key”)
    [ in server.ovpn it is with \, but the .log file shows !?]

    2022-03-14 14:01:00 Exiting due to fatal error

    • admin
      March 23, 2022 at 11:24 am — Reply

      As suggested try to use –data-ciphers-fallback ‘AES-256-CBC’. Normally it should work.
      Cannot preload the tls-auth key, some how the path is not correct or may be related to permission related or may be the double quotes symbol is wrong somehow.

  3. DoctorMagic
    March 22, 2022 at 9:43 pm — Reply

    All ok, I follow all instructions but when i connect give me an error:
    Unrecognized option or missing or extra parameter(s) is server.ovpn:78: ca (2.5.6)
    why?

    • admin
      March 23, 2022 at 11:25 am — Reply

      It could be possible that the double quotes symbol got changed somehow. Try to manually type it.

    • Alan Tibbetts
      April 2, 2022 at 11:59 pm — Reply

      Regarding the error
      Unrecognized option or missing or extra parameter(s) is server.ovpn:78: ca (2.5.6)
      why?

      I found that using Notepad++ to replace all the standalone n symbols in the sample server and client files cured the problem. It took two passes. Replace n with rn first, followed by replace rnn with rn. I also changed the encoding from UTF-8-BOM to ANSI. It really looks like the samples were really not tested well, perhaps being copied from another OS without changing the end of line syntax appropriately.

  4. DoctorMagic
    March 23, 2022 at 9:34 am — Reply

    this is the line 78
    ca “C:\Program Files\OpenVPN\easy-rsa\pki\ca.crt”

  5. DoctorMagic
    March 23, 2022 at 1:08 pm — Reply

    it works
    the problem is “(keyboard input) not ” (web copy)
    Thanks
    Idol

  6. DoctorMagic
    March 24, 2022 at 6:28 pm — Reply

    Hello again
    Routing is enabled
    i ping 10.8.0.1 and 172.16.1.11 (ip windows 10) correctly from client
    but i not surf in internet on client.
    I don’t ping any address of server 172.16.1.11
    Where is the error?
    Thanks again

  7. DoctorMagic
    March 24, 2022 at 6:43 pm — Reply

    Hello again.
    I disable the iCS and then enable
    Its works
    all ok

  8. Alan Tibbetts
    April 2, 2022 at 11:47 pm — Reply

    I had these same problems. I just copied the line above into Notepad++ and used the HEX-editor plugin to look at it in hex, I saw that the double quotes were e2 80 9c for the leading quote and e2 80 9d for the trailing quote, not the ANSI double quote (hex 22) with which they are visually identical. My solution was to replace the bogus quotes with the ANSI apostrophe (hex 27). It takes two passes through the file to replace the leading and then the trailing offensive characters. Not offensive to me, offensive to OpenVPN.

  9. DoctorMagic
    April 3, 2022 at 11:57 am — Reply

    Hello, can i execute a script on server when a client is connected?
    For example when a generic client is connected i send a message to admin
    Thanks

    • admin
      April 12, 2022 at 6:20 am — Reply

      Yes, from my understanding its possible and I believe you need to look at the –script-security option available for openvpn

  10. Vlad
    August 11, 2022 at 2:27 pm — Reply

    Awesome! Thanks for the detailed explanation, all works fine.

  11. Vlad
    September 9, 2022 at 5:56 pm — Reply

    It connects, but can’t open websites in a browser. Any clues?

    • admin
      September 15, 2022 at 2:05 pm — Reply

      Try to restart the openvpn service and see if that helps.

Page load link

Go to Top

OpenVPN is an open-source software suite that is really 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 (Linux OpenVPN deployment example). 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.

install WinTun driver and EasyRSA tools

Complete the installation.

By default, OpenVPN is installed to C:Program FilesOpenVPN.

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.

OpentVPN network adapter wintun userspace tunnel

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 FilesOpenVPNeasy-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 "admin@woshub.com"
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 FilesOpenVPNeasy-rsapkica.crt
  • A Certification Authority key: C:Program FilesOpenVPNeasy-rsapkiprivateca.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 FilesOpenVPNeasy-rsapkiissuedserver.crt).

openvpn server certififate fil in the issued folder

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

easyrsa gen-dh generate Diffie-Hellman keys

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 FilesOpenVPNbin
openvpn --genkey secret ta.key

The C:Program FilesOpenVPNbinta.key file will appear. Move it to C:Program FilesOpenVPNeasy-rsapki 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

easyrsa sign certificare request

Copy the key file (C:Program FilesOpenVPNeasy-rsapkiprivatetestuser1.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 FilesOpenVPNeasy-rsapkiprivatetestuser1.key"-out "C:Program FilesOpenVPNeasy-rsapkiprivatetestuser1_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 FilesOpenVPNeasy-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 FilesOpenVPNsample-configserver.ovpn" "C:Program FilesOpenVPNconfig-autoserver.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 on the server. You can open the port in Windows Defender using PowerShell.
Firewal 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 commands 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 FilesOpenVPNlogserver.log.

OpenVPN Wintun virtual adapter on Windows

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

Options error: In C:Program FilesOpenVPNconfig-autoserver.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 "HKLMSYSTEMCurrentControlSetServicesTcpipParameters" /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 config file to OpenVPN Connect for Windows

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

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

openvpn client successfully connected to server

Check the OpenVPN connection log on the client: C:Program FilesOpenVPN Connectagent.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 FilesOpenVPNlogopenvpn.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

Понравилась статья? Поделить с друзьями:
  • Как установить ntp сервер на windows
  • Как установить pytorch на windows 10
  • Как установить physxloader dll для windows 10 64 bit
  • Как установить openvpn server на windows 10
  • Как установить python через консоль windows