Установка openvpn на windows server 2019

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

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

Установка OpenVPN Server

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

Community Downloads

vpn

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

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

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

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

Finish.

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

cd "C:\Program Files\TAP-Windows\bin"
"C:\Program Files\TAP-Windows\bin\tapinstall.exe" install "C:\Program Files\TAP-Windows\driver\OemVista.inf" tap0901

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

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

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

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

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

vpn

Выполняем:

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

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

notepad vars.bat

vpn

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

vpn

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

vpn

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

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

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

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

set KEY_KONFIG=openssl-1.0.0.cnf

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

vpn

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

vpn

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

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

vars.bat

vpn

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

clean-all.bat

vpn

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

vpn

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

build-ca.bat

vpn

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

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

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

vpn

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

build-dh.bat

vpn

В папке C:\Program Files\OpenVPN\easy-rsa\keys появляется файл:

  • dh2048.pem

vpn

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

build-key-server.bat server

vpn

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

После завершения работы скрипта в папке C:\Program Files\OpenVPN\easy-rsa\keys появляется четыре файла:

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

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

vpn

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

build-key.bat client

vpn

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

После завершения работы скрипта в папке C:\Program Files\OpenVPN\easy-rsa\keys появляется четыре файла:

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

vpn

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

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

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

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

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

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

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

vpn

В папке C:\Program Files\OpenVPN\easy-rsa\keys появляется файл:

  • ta.key

vpn

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

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

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

mkdir "C:\Program Files\OpenVPN\ssl"
copy "C:\Program Files\OpenVPN\easy-rsa\keys" "C:\Program Files\OpenVPN\ssl"

vpn

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

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

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

notepad "C:\Program Files\OpenVPN\config\server.ovpn"

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

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

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

proto tcp

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

services.msc

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

netstat -tan | find "1194"

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

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

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

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

vpn

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

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

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

vpn

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

vpn

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

vpn

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

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

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

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

vpn

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

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

cd "C:\Program Files\OpenVPN\easy-rsa"
vars.bat
revoke-full client

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

В папке C:\Program Files\OpenVPN\keys появляется файл:

  • crl.pem

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

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

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

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

net stop OpenVPNService
net start OpenVPNService

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

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

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

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

connect-retry-max 25

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

Ссылки

OpenVPN 2.5.1 сервер на Windows

Skip to content

Cloud Orchestration Logo

How to Setup 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.

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

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

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

OpenVPN for Windows

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

OpenVPN Connect client

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

Setting Up OpenVPN Server.

In this article will show you how to Setup up a OpenVPN Server ( Community Edition) On Windows 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 Files\OpenVPN\config-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 Files\OpenVPN\config”.

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:

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

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

The easy-rsa3 scripts folder location should be “C:\Program Files\OpenVPN\easy-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 Files\OpenVPN\easy-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 Files\OpenVPN\easy-rsa Defines the folder location of easy-rsa scripts
set_var EASYRSA_OPENSSL C:\Program Files\OpenVPN\bin\openssl.exe Defines the OpenSSL binary path
set_var EASYRSA_PKI C:\Program Files\OpenVPN\easy-rsa\pki 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 Files\OpenVPN\easy-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 Files\OpenVPN\easy-rsa\pki”

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 Files\OpenVPN\easy-rsa\pki” 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 Files\OpenVPN\easy-rsa\pki\issued” 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 Files\OpenVPN\easy-rsa\pki\issued” 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 Files\OpenVPN\easy-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 Files\OpenVPN\easy-rsa\pki\easytls”.  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 Files\OpenVPN\easy-rsa\pki” 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 Files\OpenVPN\easy-rsa\pki CA file, DH file and other OpenSSL related files like config file
C:\Program Files\OpenVPN\easy-rsa\pki\private Include the private key files of CA, Server and Client certificates
C:\Program Files\OpenVPN\easy-rsa\pki\easytls Contains the tls-auth key
C:\Program Files\OpenVPN\easy-rsa\pki\issued 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-Win64\bin 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-Win64\bin\openssl.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,

  1. First go the folder C:\OpenSSL-Win64\bin and create folder named “demoCA” . This is the folder where we kept generated certificates and other related files.
  2.  Now under the “demoCA” folder create another folder named “certs” . This is the folder where the issued certs are kept.
  3. Now under the “demoCA” folder itself, create another folder named “newcerts”. This is the default folder for new certs.
  4. 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
  5. 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-Win64\bin\openssl.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-Win64\bin\openssl.cfg

Normally it should look like below.  If its not, make the arrangement like below.

[ req ]

default_bits = 2048
default_md = sha1
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
req_extensions = v3_req
x509_extensions = usr_cert

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-Win64\bin\openssl.cfg

So find out the [ usr_cert ]  section and make sure below values are defined.

[ usr_cert ]

subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign
extendedKeyUsage = serverAuth, clientAuth, codeSigning, emailProtection

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-Win64\bin\openssl.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-Win64\bin\demoCA.  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-Win64\bin\demoCA” 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 Files\OpenVPN\sample-config and copy file named  “server.ovpn” to C:\Program Files\OpenVPN\config.

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 Files\OpenVPN\sample-config and copy file named “client.ovpn” to C:\Program Files\OpenVPN\config.

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 Files\OpenVPN\config.

Refer below screenshot for better understanding on file structure.

Section 5 b . Configure Client Config File.

Go to the folder “C:\Program Files\OpenVPN\config” 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!

By admin|2021-12-17T14:52:17+00:00October 5th, 2021|Windows|

Related Posts

14 Comments

  1. Dominique
    November 18, 2021 at 9:11 am — Reply

    Thanks a lot for this page, Very helpfull to understand and configure an openvpn server and client ! And make IT WORKS !!

  2. Иван Анатольевич
    March 3, 2022 at 2:02 pm — Reply

    Options 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 — Reply

      Check the mentioned line in openvpn config file. Could be some invalid character

  3. Niltinho
    April 3, 2022 at 6:16 pm — Reply

    Hi, 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 — Reply

      we setup NAT for all type of traffic in this case

  4. Nico
    May 20, 2022 at 4:46 pm — Reply

    Tried 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 — Reply

      okay, I am not sure about VMware emulater network adaptor. Did you checked with VMware support team ?

      • Nico
        May 29, 2022 at 7:22 pm — Reply

        No, but anyway it was just for test, its was not something important. I will ask them later.
        Thanks for reply.

  5. milad
    August 7, 2022 at 8:42 am — Reply

    I have 1 problem
    you are install open ssl into “c:\program files\openssl” but config envoirment into “c:\openssl” its true?
    i cant execute openssl commands!

  6. milad
    August 7, 2022 at 11:39 am — Reply

    Last problemes is solved , but when i want exexute req
    i have this error :
    req: Can’t open “certs\ca.key” for writing, No such file or directory

  7. kimbo slice
    November 3, 2022 at 3:35 pm — Reply

    This milad guy really ought to pay attention to file paths, lol

  8. Cupio
    January 13, 2023 at 3:54 pm — Reply

    Hi my issue is :
    I made this folder : C:\Program Files\OpenSSL-Win64\bin\demoCA\newcerts
    and when I run this command :

    openssl ca -days 3650 -extensions usr_cert -cert certs\ca.crt -keyfile certs\ca.key -out client1.crt -infiles certs\client1.csr

    My Error is :
    Using configuration from C:\Program Files\OpenSSL-Win64\bin\openssl.cfg
    ca: ./demoCA/newcerts is not a directory
    ./demoCA/newcerts: No error

    but I have that directory !

  9. Antonio
    January 16, 2023 at 2:49 pm — Reply

  10. BobH
    February 3, 2023 at 6:32 am — Reply

    Unable to start OpenVPN server – get “Options error: Unrecognized option or missing or extra parameter(s) in ..\config\server.ovpn:78: ca (2.6.0). Use –help for more information.
    1) Unable to determine what :78 is – guessing line number, but there’s nothing but a blank line there. Tried guessing that it was counting non-blank lines (the sample config has every other line blank) and the nearest actual config line was dh “C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\dh.pem”. Verified that dh.pem exists at that path and I did run ./easyrsa gen-dh from the easy-ras shell (date/time stamp on dh.pem confirms).

    2) Verified other edited config value that they point to correct locations, such as:
    ca “C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\ca.crt”
    cert “C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\issued\\ServerVPN.crt”
    key “C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\private\\ServerVPN.key” # This file should be kept secret
    tls-auth “C:\\Program Files\\OpenVPN\\easy-rsa\\pki\\private\\ta.key” 0 # This file is secret

Page load link

Go to Top

Tutorial Install OpenVPN on Windows Server 2019

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.

Table of Contents

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:

Download-OpenVPN-from-website

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:

Installation-OpenVPN-features

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”:

Command-prompt-OpenVPN

Go to the following path:

C:\Program Files\OpenVPN\easy-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 Files\OpenVPN\easy-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 Files\OpenVPN\easy-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 Files\OpenVPN\easy-rsa>build-key Michael-PC Generating a RSA private key .............................................................................................................................................................................++++ ..............................................................................++++ writing new private key to 'keys\Michael-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 Files\OpenVPN\easy-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 Files\OpenVPN\easy-rsa>build-dh.bat Generating DH parameters, 2048 bit long safe prime, generator 2 This is going to take a long time .................................+......................................................................................................+.............................................................................................+..................................................................................+......................................................... .............................................................................+............................+..........+........+............................................+..............................................+....++*++*++*++* C:\Program Files\OpenVPN\easy-rsa>

Generate a shared secret key (which is required when using tls-auth):

"C:\Program Files\OpenVPN\bin\openvpn.exe" --genkey --secret   "C:\Program Files\OpenVPN\easy-rsa\keys\ta.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 Files\OpenVPN\sample-config\server.ovpn" "C:\Program Files\OpenVPN\easy-rsa\keys\server.ovpn" C:\Program Files\OpenVPN\easy-rsa>"C:\Program Files\OpenVPN\bin\openvpn.exe" --genkey --secret "C:\Program Files\OpenVPN\easy-rsa\keys\ta.key" C:\Program Files\OpenVPN\easy-rsa>copy "C:\Program Files\OpenVPN\sample-config\server.ovpn" "C:\Program Files\OpenVPN\easy-rsa\keys\server.ovpn" 1 file(s) copied. C:\Program Files\OpenVPN\easy-rsa>

Now edit the server.ovpn file:

notepad "C:\Program Files\OpenVPN\easy-rsa\keys\server.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 Files\OpenVPN\sample-config\client.ovpn" "C:\Program Files\OpenVPN\easy-rsa\keys\Michael-PC.ovpn"    C:\Program Files\OpenVPN\easy-rsa>copy "C:\Program Files\OpenVPN\sample-config\client.ovpn" "C:\Program Files\OpenVPN\easy-rsa\keys\Michael-PC.ovpn"  1 file(s) copied.  C:\Program Files\OpenVPN\easy-rsa>  

Edit the client’s config file.

notepad "C:\Program Files\OpenVPN\easy-rsa\keys\Michael-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 Files\OpenVPN\easy-rsa\keys\ to C:\Program Files\OpenVPN\config\ on the server using the robocopy command:

  • ca.crt
  • ta.key
  • dh2048.pem
  • server.crt
  • server.key
  • server.ovpn
robocopy "C:\Program Files\OpenVPN\easy-rsa\keys\ " "C:\Program Files\OpenVPN\config\ " ca.crt ta.key dh2048.pem server.crt server.key server.ovpn  
C:\Program Files\OpenVPN\easy-rsa>robocopy "C:\Program Files\OpenVPN\easy-rsa\keys\ " "C:\Program Files\OpenVPN\config\ " 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 Files\OpenVPN\easy-rsa\keys\  Dest : C:\Program Files\OpenVPN\config\  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 Files\OpenVPN\easy-rsa\keys\  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 Files\OpenVPN\easy-rsa>  

You can copy the following files from C:\Program Files\OpenVPN\easy-rsa\keys\ on the server to C:\Program Files\OpenVPN\config\ 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.

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

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

Содержание:

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

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

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

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

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

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

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

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

WinTun драйвер openvpn

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

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

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

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

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

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

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

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

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

copy vars.example vars

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

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

set_var EASYRSA_TEMP_DIR "$EASYRSA_PKI/temp"

EASYRSA_TEMP_DIR

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

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

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

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

#set_var EASYRSA_CA_EXPIRE 3650
#set_var EASYRSA_CERT_EXPIRE 825

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

EasyRSA-Start.bat

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

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

./easyrsa init-pki

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

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

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

./easyrsa build-ca

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

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

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

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

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

./easyrsa gen-req server nopass

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

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

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

./easyrsa sign-req server server

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

push "redirect-gateway def1"

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

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

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

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

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

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

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

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

импорт конфигурации клиента ovpn в openvpn клиент

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

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

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

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

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

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

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

Table of Content

INTRODUCTION

In this tutorial, we will learn how to instal and setup OpenVPN Connect in Windows Server 2012R2, 2016, 2019.

Step 1. Login to your Windows Server

Setup OpenVPN Connect in Windows

Setup OpenVPN Connect in Windows

Step 2. Download OpenVPN Connect Setup OpenVPN Connect in Windows

Download OpenVPN for Windows

Setup OpenVPN Connect in Windows

Step 3. Open the installer package Setup OpenVPN Connect in Windows

Step 4. Follow the installation window

OpenVPN Connect installed.

Setup OpenVPN Connect in Windows

Step 5. Import your OpenVPN profile and you are good to go. Setup OpenVPN Connect in Windows

Setup OpenVPN Connect in Windows

Thank You!

  • Установка sp2 на windows 7 обновление kb3125574
  • Установка ubuntu рядом с windows 10 без флешки
  • Установка rsat windows 10 22h2
  • Установка sp flash tool на windows 10
  • Установка rras windows server 2016