Установим и настроим OpenVPN сервер. На сервере используется операционная система Windows Server 2019.
OpenVPN — бесплатная реализация технологии виртуальной частной сети (VPN) для создания зашифрованных каналов связи между компьютерами типа точка-точка или сервер-клиенты за NAT и Firewall.
Установка OpenVPN Server
Скачиваем дистрибутив для установки OpenVPN:
Прокручиваем вниз, выбираем стабильную версию. Я буду использовать версию 2.4.9.
Для операционной системы Windows доступны два пакета:
- WINDOWS 7/8/8.1/SERVER 2012R2 INSTALLER (NSIS)
- WINDOWS 10/SERVER 2016/SERVER 2019 INSTALLER (NSIS)
Для Windows Server 2019 подходит второй вариант, скачиваю.
Запускаем инсталлятор OpenVPN.
Открывается мастер установки. Next.
Принимаем лицензионное соглашение. I Agree.
Выбираем компоненты. Выделите EasyRSA 2 Certificate Management Scripts. Для сервера OpenVPN GUI можно не устанавливать, если вы планируете запускать OpenVPN в качестве службы. Next.
Выбираем путь установки, я оставляю по умолчанию C:Program FilesOpenVPN. Install.
Начинается процесс установки OpenVPN.
Установка успешно завершена. Next.
Finish.
Установка выполнена в директорию C:Program FilesOpenVPN.
После установки у нас появляется новый сетевой адаптер TAP-Windows Adapter V9.
Адаптер отключён. Если по каким-то причинам нужно добавить несколько таких адаптеров, то загляните в папку C:Program FilesTAP-Windowsbin.
Здесь есть скрипты для установки адаптера, добавления адаптера и удаления всех адаптеров.
Пример установки адаптера. В командной строке под администратором:
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
В этой папке есть всё необходимое для генерации сертификатов.
Выполняем:
init-config.bat
copy vars.bat.sample vars.bat
Создаётся файл vars.bat с настройками и примером готовых параметров для создания CSR запроса сертификатов. Заполним его. Открываем vars.bat блокнотом.
notepad vars.bat
Открывается vars.bat.
Здесь стоит обратить внимание на пути к рабочим директориям. Например, вы можете указать свой путь к openssl.exe, если установили OpenVPN в другую директорию. Здесь же можно изменить длину ключей шифрования.
Заполняем переменные в нижней части файла, указываем:
- 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
Это имя конфигурационного файла. Находим его в рабочей директории.
Откроем блокнотом.
Внутри есть параметр default_days, в котором можно указать срок действия будущих сертификатов. По умолчанию у меня стоит 3650 дней, это 10 лет. Меня устраивает. Вероятно, кому-то при генерации клиентских сертификатов может понадобиться уменьшить этот срок.
Сохраняем все изменения и возвращаемся к командной строке. Подгружаем утверждённые нами переменные:
vars.bat
Очищаем директорию с ключами:
clean-all.bat
Сертификаты, которые мы будем создавать, появятся в папке C:Program FilesOpenVPNeasy-rsakeys. Сейчас эта папка очистилась, в ней два файла: index.txt и serial.
Генерируем ключ и сертификат центра сертификации:
build-ca.bat
В процессе генерации сертификата нас будут спрашивать все те же параметры, которые мы указали в vars.bat. Если параметр нас устраивает (а он нас устраивает), просто нажимаем ввод и переходим к следующему вопросу. После завершения работы скрипта в папке C:Program FilesOpenVPNeasy-rsakeys появляется два файла:
- ca.crt — сертификат центра сертификации
- ca.key — ключ центра сертификации
Ключ секретный, никому не передавайте, он будет храниться на сервере.
Генерируем ключ Диффи-Хеллмана:
build-dh.bat
В папке C:Program FilesOpenVPNeasy-rsakeys появляется файл:
- dh2048.pem
Генерируем ключ и сертификат сервера, назовём сервер именем «server«:
build-key-server.bat server
В процессе генерации серверного сертификата нас будут спрашивать те же параметры, которые мы указали в 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 — ключ сервера
Ключ секретный, никому не передавайте, он будет храниться на сервере.
Генерируем ключ и сертификат первого клиента. Для каждого клиента нужно указывать своё имя файла, Name и Common Name. Назовём первого клиента именем «client«:
build-key.bat client
В процессе генерации клиентского сертификата нас будут спрашивать те же параметры, которые мы указали в 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 — ключ первого клиента
Для каждого нового клиента, который будет подключаться к серверу 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
В папке C:Program FilesOpenVPNeasy-rsakeys появляется файл:
- ta.key
Минимальный набор сертификатов сгенерирован.
Настройка OpenVPN сервера
Чтобы случайно всё не удалить, создадим папку C:Program FilesOpenVPNssl и скопируем в неё сертификаты. Это будет рабочая папка сервера.
mkdir "C:Program FilesOpenVPNssl"
copy "C:Program FilesOpenVPNeasy-rsakeys" "C:Program FilesOpenVPNssl"
Создадим конфигурационный файл сервера 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
Находим службу OpenVPNService.
Настраиваем на автоматический запуск при загрузке сервера.
Запускаем службу.
Согласно настройкам сервера в папке C:Program FilesOpenVPNlog должны появиться логи. Это один из инструментов администратора OpenVPN сервера.
Активировался сетевой адаптер TAP-Windows Adapter V9.
Согласно настройкам сервера IP адрес 10.8.0.1.
Проверяем поднялся ли порт tcp 1194:
netstat -tan | find "1194"
Порт должен прослушиваться.
Теперь нужно настроить firewall. Открываем Windows Defender Firewall with Advanced Security.
Переходим в Inbound Rules.
Создаём правило — New Rule…
Тип правила — Port. Next.
Протоколы и порты — UDP 1194. Как в настройках сервера. Next.
Действия — Allow the connection. Next.
Для всех сетей. Next.
Указываем название правила — OpenVPN. Next.
Правило создано, теперь firewall не блокирует входящие UDP соединения на 1194 порту.
Настройка OpenVPN клиента
На компьютере клиента устанавливаем OpenVPN точно также как на сервер. Галку EasyRSA 2 Certificate Management Scripts не указываем. Галку OpenVPN GUI указываем.
Я устанавливаю OpenVPN на клиенте в папку по умолчанию. C:Program FilesOpenVPN.
Копируем в отдельную папку for_client (её содержимое отправим потом на компьютер клиента) на сервере файлы для клиента:
- ca.crt
- client.crt
- client.key
- dh2048.pem
- ta.key
Туда же из папки C:Program FilesOpenVPNsample-config копируем client.ovpn
Переименовываю client.ovpn в config.ovpn. Можно использовать любое имя, лучше созвучное с названием организации. Вот такой получился набор.
Редактируем файл 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.
На клиента запускаем OpenVPN GUI.
В трее появляется значок OpenVPN.
Правой кнопкой — подключиться.
Устанавливается соединение.
Значок позеленел, назначен адрес 10.8.0.6.
Можно подключаться к серверу, если есть доступы.
Для второго и последующего клиента генерируем свой набор клиентских сертификатов.
Отзыв сертификата
Иногда нужно отозвать сертификат, выданный клиенту. Кто-то увольняется, кто-то палит сертификаты.
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
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 2.5, поддерживается драйвер WinTun от разработчиков WireGuard. Считается, что этот драйвер работает быстрее чем классический OpenVPN драйвер TAP. Установите драйвер Wintun, откажитесь от установки TAP-Windows6.
Установите OpenSSL утилиту EasyRSA Certificate Management Scripts.
Запустите установку.
По умолчанию OpenVPN устаналивается в каталог C:Program FilesOpenVPN.
После окончания установки появится новый сетевой адаптер типа Wintun Userspace Tunnel. Этот адаптер отключен, если служба OpenVPN не запущена.
Создаем ключи шифрования и сертификаты для 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"
Можете заполнить поля для сертификатов (опционально)
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 "
Срок действия сертификатов задается с помощью:
#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»)
Теперь можно создать ключи Диффи-Хеллмана (займет длительное время):
./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
Данный ключ («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
Откройте панель управления, и убедитесь, что виртуальный сетевой адаптер OpenVPN Wintun теперь активен. Если нет, смотрите лог «C:Program FilesOpenVPNlogserver.log»
Если при запуске 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 нужно с сервера скопировать файлы:
- ca.crt
- kbuldogov.crt
- kbuldogov.key
- dh.pem
- ta.key
- kbuldogov.ovpn
Теперь импортируйте файл с профилем *.ovpn и попробуйте подключиться к вашему VPN серверу.
Если все настроено правильно, появится такая картинка.
Проверьте теперь лог 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
If you want to protect your online privacy or encrypt your information on the web so that it does not fall into the hands of hackers; you should use a VPN. The main element of any VPN is the VPN protocol used by it. In this article, we will teach you how to install OpenVpn on Windows Server 2019. Most VPNs support several protocols such as IKEv2, L2TP, and SSTP, but the OpenVPN protocol is known as the most popular and best VPN protocol in the world. In this article, we will teach you How to Setup OpenVPN On Windows Server 2019. If you want to purchase your own RDP, you can check out the packages offered on the Eldernode website.
What is OpenVPN?
Openvpn is currently the most popular and widely used protocol as a VPN. Unlike other IPSec-based tunneling protocols (such as L2tp), Openvpn relies on SSL / TLS for authentication and data encryption. This standard security technology is for making secure, remote connections from one place to another or from one point to another. The use of SSL to protect financial transactions, data transfers, emails, and other things is very popular.
OpenVPN is compatible with all major operating systems such as Windows, Android, iOS, Mac, and Linux. It is open source and supports up to 256-bit encryption.
Available OpenVPNs is as follows:
–> OpenVPN Community Edition: It is an open-source and free version and doesn’t have user limitations.
–> OpenVPN Access Server: It is based on the Community Edition but provides additional paid and proprietary features such as Easy Management Admin Portal, LDAP integration and etc.
–> OpenVPN-as-a-Service: It is a solution that eliminates the need for VPN server installation. You can connect to your hosted service with regions around the world simply by purchasing OpenVPN Cloud.
In this step from the Windows training tag, you will learn how to install OpenVPN on Windows Server 2019.
Prerequisites
– Access to port 1194 to connect to the same network
– Windows Server 2019
You can do this by allowing UDP traffic on port 1194 by adding a rule to your Firewall.
How to Install OpenVPN on Windows Server 2019
Go to the official OpenVPN Website to download the latest Windows 64-bit MSI installer for the OpenVPN Community edition:
After the download is completed, go to the downloaded file and double-click on it. Click on the icon next to desired features to choose them. Check the ”EasyRSA 2 Certificate Management Scripts” and click on Next:
Once the installation is completed, you should generate the certificates and keys to access the VPN. To do this, open the terminal by typing cmd on the Start menu and right-click on the Command Prompt icon. Choose ”Run as Administrator”:
Go to the following path:
C:Program FilesOpenVPNeasy-rsa
Now you can start configuring OpenVPN:
init-config
In this step, you need to open the vars.bat file in the text editor:
notepad vars.bat
Edit the subsequent lines by switching The ”US”, ”CA” etc with your business’s data:
set KEY_COUNTRY=US set KEY_PROVINCE=CA set KEY_CITY=SanFrancisco set KEY_ORG=OpenVPN set [email protected]
–> KEY_CN and KEY_NAME: They will be unique for each build request and refer to the common name field and the name of the certificate.
–> KEY_OU: They refer to an ”Organizational Unit” and can be set to whatever if there isn’t a requirement for it.
–> PKCS11_values: They refer to settings used for Hardware Security Modules and Smart Cards if you use them.
Save the text editor file and exit it.
To apply the changes, enter the following command:
vars
clean all
Building Certificates and Keys
In order to create the Certificate Authority (CA) certificate and key, we need to run the following command:
build-ca
This will prompt you to enter your country, state, and city. These options will also have default values, which appear within brackets:
Certificate Authority "OpenVPN-CA": Country Name (2 letter code) [US]: State or Province Name (full name) [CA]: Locality Name (eg, city) [SanFrancisco]: Organization Name (eg, company) [OpenVPN]: Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []:OpenVPN-CA Email Address [[email protected]]:
Using the following command, we initiate the server’s certificate and key:
build-key-server server
When prompted to sign the certificate and commit, enter ”y” and enter the ”Common Name” as a server.
Server Certificates and Keys
C:Program FilesOpenVPNeasy-rsa>build-key-server.bat Generating a RSA private key ..............................................................................................................................................................................................................................................++++ ................................++++ writing new private key to 'keys.key' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [US]:US State or Province Name (full name) [MI]: Locality Name (eg, city) [Lansing]: Organization Name (eg, company) [OpenVPN]: Organizational Unit Name (eg, section) [changeme]: Common Name (eg, your name or your server's hostname) [changeme]:Server Name [changeme]: Email Address [[email protected]]: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:XXXXXXXXXXXXXXXX An optional company name []: Using configuration from openssl-1.0.0.cnf Can't open keys/index.txt.attr for reading, No such file or directory 1832:error:02001002:system library:fopen:No such file or directory:crypto/bio/bss_file.c:74:fopen('keys/index.txt.attr','r') 1832:error:2006D080:BIO routines:BIO_new_file:no such file:crypto/bio/bss_file.c:81: Check that the request matches the signature Signature ok The Subject's Distinguished Name is as follows countryName :PRINTABLE:'US' stateOrProvinceName :PRINTABLE:'MI' localityName :PRINTABLE:'Lansing' organizationName :PRINTABLE:'OpenVPN' organizationalUnitName:PRINTABLE:'changeme' commonName :PRINTABLE:'Server' name :PRINTABLE:'changeme' emailAddress :IA5STRING:'[email protected]' Certificate is to be certified until Dec 24 19:01:08 2029 GMT (3650 days) Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated C:Program FilesOpenVPNeasy-rsa>
Client Certificates and Keys
For each client that will be connecting to the server, you should choose a unique name to identify that user’s computer, such as ”Michael-PC” in the following example.
When prompted, enter the Common Name as the name you have chosen for the client’s cert/key. You will repeat this step for every client computer that is going to connect to the VPN.
C:Program FilesOpenVPNeasy-rsa>build-key Michael-PC Generating a RSA private key .............................................................................................................................................................................++++ ..............................................................................++++ writing new private key to 'keysMichael-PC.key' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [US]: State or Province Name (full name) [MI]: Locality Name (eg, city) [Lansing]: Organization Name (eg, company) [OpenVPN]: Organizational Unit Name (eg, section) [changeme]: Common Name (eg, your name or your server's hostname) [changeme]:Michael-PC Name [changeme]: Michael Jordan Email Address [[email protected]]: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:XXXXXXXXXXXXXXXX An optional company name []: Using configuration from openssl-1.0.0.cnf Check that the request matches the signature Signature ok The Subject's Distinguished Name is as follows countryName :PRINTABLE:'US' stateOrProvinceName :PRINTABLE:'MI' localityName :PRINTABLE:'Lansing' organizationName :PRINTABLE:'OpenVPN' organizationalUnitName:PRINTABLE:'changeme' commonName :PRINTABLE:'Michael-PC' name :PRINTABLE:'Michael Jordan' emailAddress :IA5STRING:'[email protected]' Certificate is to be certified until Dec 24 19:06:10 2029 GMT (3650 days) Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated C:Program FilesOpenVPNeasy-rsa>
In this part, you need to generate the ”Diffie Hellman” parameters using thebuild-dh command. This step is necessary in order to set up the encryption model.
C:Program FilesOpenVPNeasy-rsa>build-dh.bat Generating DH parameters, 2048 bit long safe prime, generator 2 This is going to take a long time .................................+......................................................................................................+.............................................................................................+..................................................................................+......................................................... .............................................................................+............................+..........+........+............................................+..............................................+....++*++*++*++* C:Program FilesOpenVPNeasy-rsa>
Generate a shared secret key (which is required when using tls-auth):
"C:Program FilesOpenVPNbinopenvpn.exe" --genkey --secret "C:Program FilesOpenVPNeasy-rsakeysta.key"
Configuration Files
OpenVPN provides sample configuration data which can easily be found using the start menu.
Open the Start menu, and click on All Programs. Then select OpenVPN Sample Configuration Files from the OpenVPN options.
Server Config File
Copy the sample ”server configuration” file over to the easy-rsa folder. This command and its output are as follows:
copy "C:Program FilesOpenVPNsample-configserver.ovpn" "C:Program FilesOpenVPNeasy-rsakeysserver.ovpn" C:Program FilesOpenVPNeasy-rsa>"C:Program FilesOpenVPNbinopenvpn.exe" --genkey --secret "C:Program FilesOpenVPNeasy-rsakeysta.key" C:Program FilesOpenVPNeasy-rsa>copy "C:Program FilesOpenVPNsample-configserver.ovpn" "C:Program FilesOpenVPNeasy-rsakeysserver.ovpn" 1 file(s) copied. C:Program FilesOpenVPNeasy-rsa>
Now edit the server.ovpn file:
notepad "C:Program FilesOpenVPNeasy-rsakeysserver.ovpn"
Locate the following lines within the file:
ca ca.crt cert server.crt key server.key dh dh2048.pem
Then edit them as follows:
ca "C:\Program Files\OpenVPN\config\ca.crt" cert "C:\Program Files\OpenVPN\config\server.crt" key "C:\Program Files\OpenVPN\config\server.key" dh "C:\Program Files\OpenVPN\config\dh2048.pem"
Finally, save and close the file.
Client Config Files
The client file modification is very similar to the server configuration changes.
Copy the sample server configuration file to the easy-rsa folder with the client’s Common Name as the file name.
Remember: Each client will need to have a unique filename.
copy "C:Program FilesOpenVPNsample-configclient.ovpn" "C:Program FilesOpenVPNeasy-rsakeysMichael-PC.ovpn" C:Program FilesOpenVPNeasy-rsa>copy "C:Program FilesOpenVPNsample-configclient.ovpn" "C:Program FilesOpenVPNeasy-rsakeysMichael-PC.ovpn" 1 file(s) copied. C:Program FilesOpenVPNeasy-rsa>
Edit the client’s config file.
notepad "C:Program FilesOpenVPNeasy-rsakeysMichael-PC.ovpn"
Locate the following settings in the file and edit them as follows:
ca ca.crt cert client.crt key client.key to ca "C:\Program Files\OpenVPN\config\ca.crt" cert "C:\Program Files\OpenVPN\config\Michael-PC.crt" key "C:\Program Files\OpenVPN\config\Michael-PC.key"
Next, we will edit the line “my-server-1“, replacing it with the server’s public IP Address or Domain Name.
remote my-server-1 1194 # The hostname/IP and port of the server. # You can have multiple remote entries # to load balance between the servers. remote my-server-1 69.16.236.167 ;remote my-server-2 1194
Save and close the file.
Copying the Client and Server Files to Their Pertinent Directories
Now you can copy these files from C:Program FilesOpenVPNeasy-rsakeys to C:Program FilesOpenVPNconfig on the server using the robocopy command:
- ca.crt
- ta.key
- dh2048.pem
- server.crt
- server.key
- server.ovpn
robocopy "C:Program FilesOpenVPNeasy-rsakeys " "C:Program FilesOpenVPNconfig " ca.crt ta.key dh2048.pem server.crt server.key server.ovpn
C:Program FilesOpenVPNeasy-rsa>robocopy "C:Program FilesOpenVPNeasy-rsakeys " "C:Program FilesOpenVPNconfig " ca.crt ta.key dh2048.pem server.crt server.key server.ovpn ------------------------------------------------------------------------------- ROBOCOPY :: Robust File Copy for Windows ------------------------------------------------------------------------------- Started : Friday, December 27, 2019 12:16:02 PM Source : C:Program FilesOpenVPNeasy-rsakeys Dest : C:Program FilesOpenVPNconfig Files : ca.crt ta.key dh2048.pem server.crt server.key server.ovpn Options : /DCOPY:DA /COPY:DAT /R:1000000 /W:30 ------------------------------------------------------------------------------ 4 C:Program FilesOpenVPNeasy-rsakeys 100% New File 2482 ca.crt 100% New File 432 dh2048.pem 100% New File 10901 server.ovpn 100% New File 657 ta.key ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 1 0 0 0 Files : 4 4 0 0 0 0 Bytes : 14.1 k 14.1 k 0 0 0 0 Times : 0:00:00 0:00:00 0:00:00 0:00:00 Speed : 452250 Bytes/sec. Speed : 25.877 MegaBytes/min. Ended : Thursday, July 16, 2020 12:16:02 PM C:Program FilesOpenVPNeasy-rsa>
You can copy the following files from C:Program FilesOpenVPNeasy-rsakeys on the server to C:Program FilesOpenVPNconfig for each client that will be using the VPN (e.g., Michael-PC, in this example)
- ca.crt
- ta.key
- Michael-PC.crt
- Michael-PC.key
- Michael-PC.ovpn
Firewall Settings
If you have any connection difficulties, ensure you set up a rule on the server’s firewall allowing incoming UDP traffic on port 1194. (Win+R “wf.msc”)
Conclusion
We hope you would enjoy this tutorial, you can ask questions about this training in the comments section, or to solve other problems in the field of Eldernode training, refer to the Ask page section and raise your problem in it as soon as possible. In this article, we taught you how to install OpenVPN on Windows Server 2019.
How to Setup OpenVPN on Windows server 2019
-
View Larger Image
Introduction
In this blog article we are going to discuss about How to setup OpenVPN on Windows Server 2019. 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.
- OpenVPN Community Edition, which is a free and open-source version
- 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.
- 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 Server 2019 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 Windows 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. 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 double click the installer exe file. 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 it. 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.
The install will get completed and we will get below screen. Click Close.
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, if we go to Server “Network and Internet ” settings >> Under Ethernet >> Change adaptor options >> We can see a new network adaptor named OpenVPN TAP device created.
We can restart the OpenVPN service from Windows Start Menu -> Control Panel -> Administrative Tools -> Services.
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 Server 2019 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”.
Now if you would like to add any OpenVPN features later you can use commands like below. Below example cmd command will install OpenVPN service feature on existing installed OpenVPN Server.
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:
- A separate certificate (also known as a public key) and private key for the server and each client, and
- 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.
SUPPOSE IF YOU WOULD LIKE TO USE YOUR OWN OPENSSL VERSION AND DON’T WISH TO USE EASY-RSA3 SCRIPTS, FOR GENERATING SSL/TLS CERTIFICATES THEN ONLY FOLLOW NEXT SECTIONS OTHERWISE MOVE TO SECTION 3
So lets see how we can generate SSL/TLS certificates using the openssl commands directly.
For that first make sure if the openssl toolkit installed in the server by issuing below version check command on windows cmd.
If it shows any error like openssl is not recognised as an internal or external command, we need to install the openssl toolkit first.
Section 2 a. Install and Setup openssl toolkit
Only follow this section if your server doesn’t have openssl toolkit available, otherwise skip this part and move on to next Section 2 b.
Open Windows Powershell and download the openssl package using below command.
Now perform the install by double-clicking on .exe file or from PowerShell issue below command.
A popup window will appear with message as Microsoft Visual C++ 2019 package is missing from the server. We need to install this package prior to proceed with the openssl package install .So click Yes for downloading the package.
Double click the downloaded Microsoft Visual C++ 2019 Redistributables msi installer. A another popup window will appear. Confirm the Licence Agreement and click Install.
We will get a success message after installation. Click close.
Now go back to the OpenSSL install wizard, Accept the Licence Agreement and Click Next.
Choose the Install directory and click Next, In our case, we are choosing the install directory as C:OpenSSL-Win64
Select Folder for OpenSSL Application shortcut. Leave the default one as it is and click Next.
Choose the copy OpenSSL DLL files as The windows system directory, which is the default one and Click Next.
Click “Install ” to proceed with the install of OpenSSL on Windows Server 2019.
Give few minutes to complete the install, A progress bar like below will show the status of install.
Click Finish to Complete the OpenSSL install.
Now add OpenSSL install binary folder C:OpenSSL-Win64bin
to the Windows environment PATH by issuing below two powershell commands.
Now export the OPENSSL_CONF as environment variable to server system variables section. Use below Powershell command.
The command output will look like below.
Now, we need to add the system variable OPENSSL_CONF permanently.
For that Press Windows + R keys together to open run window, Then type “sysdm.cpl” in the Run dialog box and hit Enter.
Go to “Advanced” tab and click on “Environment variables”. Click New under System Variables section.
Add values in the “variable name” as OPENSSL_CONF and “variable value” value box as C:OpenSSL-Win64binopenssl.cfg . Click OK Two times and Apply and OK from System Properties window.
.
Section 2 b . Configure OpenSSL.
In this section, we configure OpenSSL installed in the server to build SSL/TLS certificated as per OpenVPN recommendation. For that,
- First go the folder C:OpenSSL-Win64bin and create folder named “demoCA” . This is the folder where we kept generated certificates and other related files.
- Now under the “demoCA” folder create another folder named “certs” . This is the folder where the issued certs are kept.
- Now under the “demoCA” folder itself, create another folder named “newcerts”. This is the default folder for new certs.
- Under folder “demoCA” create a file named “serial”. Make sure there is no file extension like .txt. Enter a value as “01” in the file. It holds the current serial number
- Lastly under folder “demoCA” create a empty file named “index.txt”
Refer below screenshot for getting an idea about file structure.
Now open the OpenSSL config file C:OpenSSL-Win64binopenssl.cfg using any text editor.
Under [ CA_default ] section , set “dir” variable location as C:\OpenSSL-Win64\bin\demoCA
To avoid a possible Man-in-the-Middle attack where an authorised client tries to connect to another client by impersonating the server, make sure to enforce some kind of server certificate verification by clients. For accomplishing this we are following below method.
Build our server certificates with specific key usage and extended key usage as per RFC3280.
Now as part of creating CERT with the extended key attributes, first verify under which section we need define extended key attributes. For that look under [ req ] section in file C:OpenSSL-Win64binopenssl.cfg
Normally it should look like below. If its not, make the arrangement like below.
[ req ]
default_bits = 2048 |
---|
In the above section what we understood is all the x509 extension that are required should be specified in [ usr_cert ] section in C:OpenSSL-Win64binopenssl.cfg
So find out the [ usr_cert ] section and make sure below values are defined.
[ usr_cert ]
subjectKeyIdentifier = hash |
---|
After adding the extensions to usr_cert , Now find out [ v3_req ] section and insert same Extensions to add to a certificate request. As this section will have the extension that the certificate request should have.
Below is the extensions we normally needed.
extendedKeyUsage = serverAuth, clientAuth, codeSigning, emailProtection basicConstraints = critical, CA:true, pathlen:0 keyUsage = critical, digitalSignature, cRLSign, keyCertSign |
---|
Now also make sure below extension key values added under [ v3_ca ] section too. From this section our CA certificate extension will be added. Below is the necessary values need to added or enabled.
subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer basicConstraints = critical,CA:true |
---|
Finally save the OpenSSL config file C:OpenSSL-Win64binopenssl.cfg . Refer below screenshots so you will get an idea how the config file will look like.
This Completes the OpenSSL configuration according to OpenVPN recommendation. Now lets Proceed with the SSL/TLS Certificate creation.
Section 2 c. Generate SSL/TLS Certificates.
In this section we are creating CA, generate certificate & key for server and client. Sign those certificates using CA certificates. For all these tasks we use openssl commands.
Build a cert authority valid for ten years, starting now.
Open windows cmd , go to the directory C:OpenSSL-Win64bindemoCA. Issue below command.
We will ask to input information’s that will be incorporated in to the certificate request. Below are fields and Answered I have used. You can enter values as per your requirement.
In the common name field, 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.
Field | Value |
---|---|
Country Name | US |
State or Province Name | CA |
Locality Name | SanFrancisco |
Organisation Name | OpenVPN |
Organisation Unit Name | IT |
Common Name | OPENVPNSERVER |
Email Address | mail@openvpnserver.com |
Below is the captured screenshot of above issued command output.
After creating the CA certificate , we can check if the extensions are still properly added by issuing below command.
The captured output of above verify command will look like below. From the results we can see our added Extended Key usage parameters, validation details are with the generated SSL/TLS CA certificate.
Now Generate certificate & key for server
For that first issue below command for build a request for a server cert that will be valid for ten years.
Enter the needed information as we described earlier. Attached a screenshot for your reference. In the Common Name Field I have given the name as “Server” because the SSL/TLS certificate request are generating for the server.
Now we can confirm the generated server csr certificate has the Extended Key Usage values by using below command.
The output of above command will look like below. We will be able to see the Extended Key usage values from the result.
Now sign the server cert request with our ca, creating a cert/key pair.
For that issue below command.
We will be asked to confirm the signing of Certificate, type “Y” and also commit the changes by typing “Y”
Attached a screenshot for reference.
After signing the cert , we can check if the extensions are still properly added by issuing below command.
Also we can verify server certificate against the root CA certificate. An OK indicates that the chain of trust is intact.
The captured output of above verify command will look like below. From the results we can the Extended Key usage parameters are enabled with the generated SSL/TLS certificate.
Now Generate certificates & keys for 1 clients using below command.
Enter the Necessary information as we discussed earlier. Here the only change I made is changed the Common name to Client1 because I am generating this certificate for the VPN client named client1.
The command output will look like below.
Now sign the client cert request with our ca, creating a cert/key pair. Use below command.
We will be asked to confirm the Signing of Certificate and Commit the changes. Type “y” for both and Hit Enter.
Screenshot Attached for reference.
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 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.
The above command output will look like below.
Now Generate a shared-secret key that is used in addition to the standard RSA certificate/key. We named the file as ta.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.
Use below command.
Below is the captured output of above command.
Key Files
Now we will find our newly-generated keys and certificates in the “C:OpenSSL-Win64bindemoCA” folder and its subdirectory “certs” folder.
Take a look at the attached screenshot for reference.
Here is an 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 |
dh4096.pem | server only | Diffie Hellman parameters | NO |
server.crt | server only | Server Certificate | NO |
server.key | server only | Server Key | YES |
client1.crt | client1 only | Client1 Certificate | NO |
client1.key | client1 only | Client1 Key | YES |
ta.key | server + all clients | Used for tls-auth directive | No |
Now its the time to copy Certificate files ca.crt, client1.crt, client1.key and ta.key from OpenVPN server to the OpenVPN client PC. Make sure to copy secret files over a secure channel.
Section 3 . Enable NAT On OpenVPN Server.
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 NAT the OpenVPN TUN/TAP Network interface to the public internet through OpenVPN server Public Interface that already have internet access.
Lets Get Started. First Open Server Manager. Click Add Roles And Features.
Click Next on the Add Roles and Feature install wizard.
Choose “Role based or feature based installation” and click Next.
Select Our Server from the “select server from the server pool” section and click Next.
Choose “Remote Access” role and click Next.
leave Features section as it is and Click Next.
Click next On Remote Access section.
From Role Services section, choose “Routing ” and “Direct Access and VPN”
A popup window will appear. Click Add features and Click Next.
Click Next on Web Server Role Section.
Leave the default selection as it is under IIS Role Service section and Click on Next.
Click Install button on Confirmation Section.
Wait for few minutes, we will get the message as installation got succeeded. Click Close.
Now From the Server Manager itself, Choose “Remote Access from Left side” >> Right click our Server Name from Right side >> Choose Remote Access Management.
Under Direct Access and VPN >> Click on “Run the Remote Access Setup Wizard”
A Popup Window will appear. In that Click “Deploy VPN only”
The Routing and Remote Access Management” Panel will open. From there Right click on our VPN Server Name and Choose ” Configure and Enable Routing And Remote Access”
Click Next on Routing and Remote Access Server Setup Wizard.
Choose “Network Address Translation (NAT) ” and click Next.
Select Our Public Network Interface where we have internet Access and Click Next.
Select our OpenVPN TUN/TAP interface that we attach to the internet and Click Next.
Click Finish and Complete the NAT setup wizard.
Now from the Route and Remote Access Management panel itself >> Expand Our Server name >> Expand IPV4 >> Select NAT >> From right side Right click our Public Interface name and choose Properties.
From Services And Ports tab >> Choose Remote Access.
A popup windows will appear, in the Private Address filed give our Public IP address and Click OK, After that click Apply and Ok.
Suppose your Server RDP Port is different, you need create a new rule and allow that Port instead of default remote desktop port 3389.
Okay, This Completes the Enabling of NAT on OpenVPN server. Lets move to Next section.
Section 4 . 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.
Now open the config file using any Text editor and make changes to below values accordingly.
ca “C:\OpenSSL-Win64\bin\demoCA\certs\ca.crt”
cert “C:\OpenSSL-Win64\bin\demoCA\server.crt” key “C:\OpenSSL-Win64\bin\demoCA\certs\server.key” dh “C:\OpenSSL-Win64\bin\demoCA\certs\dh4096.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:\OpenSSL-Win64\bin\demoCA\certs\ta.key 0 data-ciphers AES-256-GCM |
---|
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-GCM” 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 powershell 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 start the OpenVPN service is from the Windows services section, which we described in section 1.
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 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.
After that rename the “client.ovpn” to “client1.ovpn” because we use this client config file for client1.
Move already downloaded ca.crt, client1.crt, client1.key and ta.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 client1.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\ta.key” 1 cipher AES-256-GCM |
---|
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-GCM” 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 server 2019 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
10 Comments
-
Dominique
November 18, 2021 at 9:11 am — ReplyThanks a lot for this page, Very helpfull to understand and configure an openvpn server and client ! And make IT WORKS !!
-
Иван Анатольевич
March 3, 2022 at 2:02 pm — ReplyOptions error: Unrecognized option or missing or extra parameter(s) in server.ovpn:192: push (2.5.3)
Use –help for more information.Help please
-
admin
March 13, 2022 at 4:47 am — ReplyCheck the mentioned line in openvpn config file. Could be some invalid character
-
-
Niltinho
April 3, 2022 at 6:16 pm — ReplyHi, thanks for the tutorial …. Do I need to create NAT for every type of traffic which by clients may be using? Is there a way to just assumes it will NAT by default?
-
admin
April 12, 2022 at 6:13 am — Replywe setup NAT for all type of traffic in this case
-
-
Nico
May 20, 2022 at 4:46 pm — ReplyTried to a VMWare émulator on Windows server 2019 and it doesn’t work for me :/
I had a lot of problem to install OpenSSL, I finally did it manualy not with Powershell or with the OpenVPN installator. And I think my problems comme from there.Anyways, may be it can’t work on a emulator ?
-
admin
May 28, 2022 at 10:00 am — Replyokay, I am not sure about VMware emulater network adaptor. Did you checked with VMware support team ?
-
Nico
May 29, 2022 at 7:22 pm — ReplyNo, but anyway it was just for test, its was not something important. I will ask them later.
Thanks for reply.
-
-
-
milad
August 7, 2022 at 8:42 am — ReplyI have 1 problem
you are install open ssl into “c:program filesopenssl” but config envoirment into “c:openssl” its true?
i cant execute openssl commands! -
milad
August 7, 2022 at 11:39 am — ReplyLast problemes is solved , but when i want exexute req
i have this error :
req: Can’t open “certsca.key” for writing, No such file or directory
Page load link
Go to Top
Введение
OpenVPN — свободная реализация технологии виртуальной частной сети (VPN) с открытым исходным кодом для создания зашифрованных каналов типа точка-точка или сервер-клиенты между компьютерами. Она позволяет устанавливать соединения между компьютерами, находящимися за NAT и сетевым экраном, без необходимости изменения их настроек.
Этап 1 — Установка сервера OpenVPN
Выполните загрузку OpenVPN с официального ресурса. Затем произведите установку. На этапе выбора компонентов проследите, чтобы все пункты из списка были отмечены.
Этап 2 — Развертывание ЦС (CA) и настройка инфраструктуры открытого ключа (PKI)
Запустите командную строку Windows Server 2019 от имени администратора и перейдите в каталог easyrsa:
В этом каталоге есть файл с именем vars.example. Переименуйте его в vars.bat и откройте его в текстовом редакторе.
Укажите значения следующих параметров (они будут использоваться по умолчанию при выпуске сертификатов):
Код: Выделить всё
set KEY_COUNTRY=US
set KEY_PROVINCE=CA
set KEY_CITY=SanFrancisco
set KEY_ORG=OpenVPN
set [email protected]
set KEY_CN=SERVER
set KEY_NAME=SERVER
set KEY_OU=changeme
set PKCS11_MODULE_PATH=changeme
set PKCS11_PIN=1234
Параметр set KEY_SIZE=4096 определяет размер генерируемых ключей. По умолчанию используется 4096 бит, чего во многих случаях достаточно. Ключи размерностью выше 4096 бит генерируются значительно дольше, поддерживаться не всеми клиентами и могут стать причиной замедления инициализации защищенных соединений.
Далее выполните запуск EasyRSA-start.bat для открытия оболочки EasyRSA 3 для Windows.
Выполните команду ./easyrsa с опцией init-pki, чтобы запустить настройку инфраструктуры открытых ключей:
Выполните команду ./easyrsa с опцией build-ca. В результате будет создан центр сертификации и два важных файла, ca.crt и ca.key, представляющие открытую и закрытую части сертификата SSL.
Если вы не хотите вводить пароль при каждом взаимодействии с ЦС, вы можете запустить команду build-ca с опцией nopass:
После выполнения команды build-ca вам будет предложено подтвердить обычное имя ЦС. Вы можете выбрать любое имя ЦС, но в данном случае проще всего нажать ENTER, чтобы принять имя по умолчанию.
Теперь ваш центр сертификации установлен и готов подписывать запросы сертификатов.
Этап 3 — Создание сертификата сервера, ключа и файлов шифрования
Создайте сертификат сервера и его ключ:
Создайте надежный ключ Диффи-Хеллмана, который будет использоваться при обмене ключами:
Cгенерируйте подпись HMAC для укрепления возможностей сервера по проверке целостности TLS:
Теперь все необходимые вашему серверу сертификаты и файлы ключей сгенерированы. Вы готовы создать соответствующие сертификаты и ключи, которые клиентский компьютер будет использовать для доступа к серверу OpenVPN.
Этап 4 — Создание сертификатов клиентов
Создайте сертификат клиента и его ключ:
Этап 5 — Настройка и запуск сервиса OpenVPN
Все сгенерированные сертификаты хранятся в C:Program FilesOpenVPNeasy-rsapki. Скопируйте указанные ниже сертификаты сервера в каталог C:Program FilesOpenVPNconfig:
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkica.crt" "C:Program FilesOpenVPNconfig"
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkiissuedserver.crt" "C:Program FilesOpenVPNconfig"
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkiprivateserver.key" "C:Program FilesOpenVPNconfig"
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkidh.pem" "C:Program FilesOpenVPNconfig"
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkita.key" "C:Program FilesOpenVPNconfig"
Скопируйте файл server.ovpn с образцом конфигурации OpenVPN из «C:Program FilesOpenVPNsample-config» в «C:Program FilesOpenVPNconfig»:
Код: Выделить всё
copy "C:Program FilesOpenVPNsample-configserver.ovpn" "C:Program FilesOpenVPNconfigserver.ovpn"
Отредактируйте файл конфигурации сервера OpenVPN:
Код: Выделить всё
notepad "C:Program FilesOpenVPNconfigserver.ovpn"
Код: Выделить всё
#################################################
# Sample OpenVPN 2.0 config file for #
# multi-client server. #
# #
# This file is for the server side #
# of a many-clients <-> one-server #
# OpenVPN configuration. #
# #
# OpenVPN also supports #
# single-machine <-> single-machine #
# configurations (See the Examples page #
# on the web site for more info). #
# #
# This config should work on Windows #
# or Linux/BSD systems. Remember on #
# Windows to quote pathnames and use #
# double backslashes, e.g.: #
# "C:\Program Files\OpenVPN\config\foo.key" #
# #
# Comments are preceded with '#' or ';' #
#################################################
# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d
# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one. You will need to
# open up this port on your firewall.
port 443
# TCP or UDP server?
;proto tcp
proto udp
# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one. On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap
# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key). Each client
# and the server must have their own cert and
# key file. The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys. Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca ca.crt
cert server.crt
key server.key # This file should be kept secret
# Diffie hellman parameters.
# Generate your own with:
# openssl dhparam -out dh2048.pem 2048
dh dh.pem
# Network topology
# Should be subnet (addressing via IP)
# unless Windows clients v2.0.9 and lower have to
# be supported (then net30, i.e. a /30 per client)
# Defaults to net30 (not recommended)
;topology subnet
# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.0.0.0 255.255.255.0
# Maintain a record of client <-> virtual IP address
# associations in this file. If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt
# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface. Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0. Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients. Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100
# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses. You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge
# Push routes to the client to allow it
# to reach other private subnets behind
# the server. Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
;push "route 192.168.10.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"
# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).
# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
# iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN. This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.
# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
# ifconfig-push 10.9.0.1 10.9.0.2
# Suppose that you want to enable different
# firewall access policies for different groups
# of clients. There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
# group, and firewall the TUN/TAP interface
# for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
# modify the firewall in response to access
# from different clients. See man
# page for more info on learn-address script.
;learn-address ./script
# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
;push "redirect-gateway def1 bypass-dhcp"
# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"
# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
;client-to-client
# 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
# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120
# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
# openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-auth ta.key 0 # This file is secret
# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
# Note that v2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
cipher AES-256-CBC
# Enable compression on the VPN link and push the
# option to the client (v2.4+ only, for earlier
# versions see below)
;compress lz4-v2
;push "compress lz4-v2"
# For compression compatible with older clients use comp-lzo
# If you enable it here, you must also
# enable it in the client config file.
;comp-lzo
# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100
# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nobody
# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun
# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log
# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "Program FilesOpenVPNlog" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it. Use one
# or the other (but not both).
;log openvpn.log
;log-append openvpn.log
# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3
# Silence repeating messages. At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20
# Notify the client that when the server restarts so it
# can automatically reconnect.
explicit-exit-notify 1
Вышеуказанные настройки создадут соединение VPN между двумя компьютерными системами, но не заставят никакие соединения использовать туннель. Если вы хотите использовать VPN для перенаправления всего вашего трафика, вам нужно будет передать настройки DNS на клиентские компьютеры.
В файле server.ovpn имеется несколько директив, которые нужно изменить для активации этой функции. Найдите раздел redirect-gateway и удалите точку с запятой «;» в начале строки redirect-gateway, чтобы убрать режим комментария. В разделах dhcp-option удалите символ «;» в начале каждой из строк, чтобы убрать режим комментария. Это поможет клиентам изменить настройки DNS, чтобы туннель VPN использовался как шлюз по умолчанию.
Для включения IP маршрутизации в Windows измените параметр IPEnableRouter на значение 1 в ветке реестра HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters:
Код: Выделить всё
reg add "HKLMSYSTEMCurrentControlSetServicesTcpipParameters" /v IPEnableRouter /t REG_DWORD /d 1 /f
По умолчанию сервер OpenVPN использует для подключения клиентов порт 1194 и протокол UDP. Если вам потребуется использовать другой порт из-за ограничений сети клиента, вы можете изменить номер порта. Если вы не храните веб-контент на сервере OpenVPN, вам подойдет порт 443, поскольку его обычно не запрещают правила внешнего брандмауэра.
Далее на сервере и клиенте нам нужно запустить OpenVPN в Меню Пуск -> Все программы -> OpenVPN -> OpenVPN GUI. Если у вас возникли какие-либо трудности с подключением, убедитесь, что вы настроили правило на брандмауэре сервера, разрешающее входящий трафик UDP через порт 443.
Теперь ваш сервер настроен для обработки трафика OpenVPN.
Этап 6 — Создание конфигураций клиентов
Все сгенерированные сертификаты хранятся в C:Program FilesOpenVPNeasy-rsapki. Скопируйте указанные ниже сертификаты клиентов в каталог C:Program FilesOpenVPNconfigclient:
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkica.crt" "C:Program FilesOpenVPNconfigclient"
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkiissuedclient.crt" "C:Program FilesOpenVPNconfigclient"
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkiprivateclient.key" "C:Program FilesOpenVPNconfigclient"
Код: Выделить всё
copy "C:Program FilesOpenVPNeasy-rsapkita.key" "C:Program FilesOpenVPNconfigclient"
Cкопируйте пример файла конфигурации сервера в папку config c именем клиента в качестве имени файла. (Помните, что каждый клиент должен иметь уникальное имя файла).
Код: Выделить всё
copy "C:Program FilesOpenVPNsample-configclient.ovpn" "C:Program FilesOpenVPNconfigclientclient.ovpn"
Отредактируйте файл базововой конфигурации клиента:
Код: Выделить всё
notepad "C:Program FilesOpenVPNconfigclientclient.ovpn"
Код: Выделить всё
##############################################
# Sample client-side OpenVPN 2.0 config file #
# for connecting to multi-client server. #
# #
# This configuration can be used by multiple #
# clients, however each client should have #
# its own cert and key files. #
# #
# On Windows, you might want to rename this #
# file so it has a .ovpn extension #
##############################################
# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client
# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel
# if you have more than one. On XP SP2,
# you may need to disable the firewall
# for the TAP adapter.
;dev-node MyTap
# Are we connecting to a TCP or
# UDP server? Use the same setting as
# on the server.
;proto tcp
proto udp
# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
remote SERVER_IP 443
;remote my-server-2 1194
# Choose a random host from the remote
# list for load-balancing. Otherwise
# try hosts in the order specified.
;remote-random
# Keep trying indefinitely to resolve the
# host name of the OpenVPN server. Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite
# Most clients don't need to bind to
# a specific local port number.
nobind
# Downgrade privileges after initialization (non-Windows only)
;user nobody
;group nobody
# Try to preserve some state across restarts.
persist-key
persist-tun
# If you are connecting through an
# HTTP proxy to reach the actual OpenVPN
# server, put the proxy server/IP and
# port number here. See the man page
# if your proxy server requires
# authentication.
;http-proxy-retry # retry on connection failures
;http-proxy [proxy server] [proxy port #]
# Wireless networks often produce a lot
# of duplicate packets. Set this flag
# to silence duplicate packet warnings.
;mute-replay-warnings
# SSL/TLS parms.
# See the server config file for more
# description. It's best to use
# a separate .crt/.key file pair
# for each client. A single ca
# file can be used for all clients.
ca ca.crt
cert client.crt
key client.key
# Verify server certificate by checking that the
# certicate has the correct key usage set.
# This is an important precaution to protect against
# a potential attack discussed here:
# http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the keyUsage set to
# digitalSignature, keyEncipherment
# and the extendedKeyUsage to
# serverAuth
# EasyRSA can do this for you.
remote-cert-tls server
# If a tls-auth key is used on the server
# then every client must also have the key.
tls-auth ta.key 1
# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
# Note that v2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
cipher AES-256-CBC
# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
#comp-lzo
# Set log file verbosity.
verb 3
# Silence repeating messages
;mute 20
Обязательно отредактируйте директиву remote. Она указывает клиенту адрес сервера OpenVPN, т. е. публичный IP-адрес вашего сервера OpenVPN. Найдите директивы, задающие ca, cert и key и укажите пути размещения.
Далее скопируйте конфиг клиента и сертификаты на клиентский ресурс. Запустите под администратором OpenVPN GUI. Нажмите правой кнопкой мыши на значок OpenVPN в системном трее и выберите «Подключение».
Introduction
A VPN (Virtual Private Network) is a virtual private network that allows you to securely connect to the Internet to remotely access your company’s IT network. Through a VPN it is therefore possible to access company services and resources, even from an untrusted network, as if you were physically present on site.
VPNs can be implemented through common operating systems, including Windows, and a service like OpenVPN. It is an open source software that allows you to create an encrypted virtual tunnel based on the TLS / SSL (Transport Layer Security / Secure Sockets Layer) protocols, using certificates to allow traffic to securely pass between the server and one or more clients.
In this tutorial you will learn how to implement a VPN on your Cloud Server by installing and configuring OpenVPN connect client software on Windows Server 2019.
Prerequisites
In order to connect to the same network, the two or more devices (client and server) connected to the VPN must have access to port 1194.
This can be done by allowing UDP traffic on that port by adding a rule to your firewall.
Installing OpenVPN
The first step is to download the OpenVPN installer for Windows Server 2019 directly from the official website .
Once the file is downloaded, open it and start the installation procedure. Make sure you put the check mark under «EasyRSA 2 Certificate Management Scripts» and then click on «Next».
Continue with the installation, by going on every time you are required to do so .
Generating Certificates and Keys for the Server
Once the preliminary installation phase of OpenVPN is completed, generate the certificates and keys for accessing the VPN .
First, open the terminal of your Windows Server. To do so, click on Start, type «cmd» and right-click on the Command Prompt icon, then, select «Run as administrator».
Go to the folder where OpenVPN was installed and start the «init-config» script.
cd "C:Program FilesOpenVPNeasy-rsa"
init-config
An output similar to that in the figure below should be shown.
At this point, apply the changes to the «vars.bat» file in the «C: Program Files OpenVPN easy-rsa» folder:
notepad vars.bat
Almost at the end of the document there will be a series of items beginning with «set» and used to set some information between the environment variables. Edit these fields with your information to generate the certificate.
This step is not essential as you will be required to enter this information later on as well. However, by setting the values in this file now, these values will be used as default parameters later.
Once this information has been entered, save the file and close the text editor. Then, type the following commands to apply these changes :
vars
clean-all
Then, start creating the Certificate. From the terminal (started as administrator and always in the «C: Program Files OpenVPN easy-rsa» folder) type:
build-ca
If the «vars» file was already edited with your information, this will already be present in the square brackets of each required field. In this case, just press «Enter» to select this value as the default parameter.
On the other hand, the item «Common name» has to be given an easy- to- remember name r: in this case «OpenVPN-CA» will be used.
To verify that the operation of certificate generation was successful, the two files «ca.crt» and «ca.key» will be created in the «easy-rsa keys» folder.
At this point, create the server keys. To start the procedure use the command:
build-key-server server_name
In this case, assign to the server the generic name by specifying it under «Common Name». As shown in the following image, the name «server» was here used.
Towards the end of the procedure you will be requested to confirm the saving of the data set twice. In both cases, type y and press «Enter».
Generating Key for the Client
Since in a VPN all connected devices must be recognizable, Clients also need a pair of keys for communicating. Still inside your Server, from the terminal and in the folder «C: Program Files OpenVPN easy-rsa») type:
build-key client_name
In this case, specify the generic name to assign to the Client (as in the image, in this case «client-desktop» was used) under the «Common Name» item .
Now it is necessary to start the Diffie-Hellman cryptographic protocol allowing the two interlocutors (Server and Client) to agree on which «common» key they will use as an authentication key to identify each other. Then, type:
build-dh
This operation may take long, depending on the hardware the server has, and requires no user interaction.
Finally, generate the «ta.key» key, to further increase the VPN security. More precisely, define a TLS authentication that verifies the integrity of the packets moving through the network. Then, type:
"C:Program FilesOpenVPNbinopenvpn.exe" --genkey --secret "C:Program FilesOpenVPNeasy-rsakeysta.key"
Server configuration file
OpenVPN already provides sample configuration files that can be used to generate the configuration needed for the correct functioning of the VPN.
Open Start -> All Programs -> OpenVPN -> OpenVPN Sample Configuration Files and copy the file «server.ovpn» to the folder «» C: Program Files OpenVPN easy-rsa keys «. Once copied, open it with the Notepad:
notepad "C:Program FilesOpenVPNeasy-rsakeysserver.ovpn"
Then identify the items:
- approx .crt
- cert server.crt
- key server.key
- dh dh2048.pem
and replace them with:
- ca «C: \ Program Files \ OpenVPN \ config \ ca.crt»
- cert «C: \ Program Files \ OpenVPN \ config \ server.crt»
- key «C: \ Program Files \ OpenVPN \ config \ server.key»
- dh «C: \ Program Files \ OpenVPN \ config \ dh2048.pem»
Apply these changes, save and close the file.
Client Configuration File
The changes to be made to the Client configuration file are very similar to those made for the Server.
Open Start -> All Programs -> OpenVPN -> OpenVPN Sample Configuration Files and copy the file «client.ovpn» to the folder «» C: Program Files OpenVPN easy-rsa keys «. Once copied, rename it giving it the same «Common Name» name used in the key generation phase (in this case «client-desktop») and open it with the Notepad.
notepad "C:Program FilesOpenVPNeasy-rsakeysclient-desktop.ovpn"
Then identify the items:
- approx .crt
- cert server.crt
- key server.key
and replace them with:
- ca «C: \ Program Files \ OpenVPN \ config \ ca.crt»
- cert «C: \ Program Files \ OpenVPN \ config \ client-desktop.crt»
- key «C: \ Program Files \ OpenVPN \ config \ client-desktop.key»
Also identify the remote entry my-server-1 1194 and replace “my-server-1” with the IP address of your Server. Apply these changes, save and close the file.
At this point, copy the following files:
- ca.crt
- ta.key
- dh2048.pem
- server.crt
- server.key
- server.ovpn
Inside the folder «C: Program Files OpenVPN config», an operation that can be performed directly with the robocopy tool .
robocopy "C:Program FilesOpenVPNeasy-rsakeys " "C:Program FilesOpenVPNconfig " ca.crt ta.key dh2048.pem server.crt server.key server.ovpn
Just copy the following files:
- ca.crt
- ta.key
- client-desktop.crt
- client-desktop.key
- client-desktop.ovpn
Within your Client in the folder «C: Program Files OpenVPN config «.
NB the OpenVPN GUI must have already been installed on the Client as well, as explained at the beginning of the tutorial for the Server.
At this point, click on Start -> All Programs -> OpenVPN -> OpenVPN GUI both on the Server and on the Client.
The graphical interface of OpenVPN will open in the tray system, at the bottom right. Right click on the respective OpenVPN icon, then click «Connect».
When the icon turns green, the connection to the virtual private network has been correctly established and, therefore, the two devices, client and server, will be communicating through the newly created VPN.