Openvpn для windows server 2012

Ниже мы детально разберем все, что касается серверных настроек на Win Server2008 и Server2012, а также покажем, как сделать подключения юзеров к созданной сети.

OpenVPN – это представление открытой (от англ. «open» — «открыть») частной виртуальной сети (от англ. «Virtual Private Network»). Данная технология помогает создавать виртуальные подключения групп клиентов к расположенных на расстоянии машинам посредством передачи данных по открытому каналу, то есть интернету.

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

Принципы работы

OpenVPN

Произведенная настройка позволит серверу взаимодействовать с внешним защищенным шифрованием SSL и создавать безопасное подключение к виртуальной сетевой машине (tun/tap). При этом не нужно будет волноваться об обработке трафика, поступающего от внешнего адаптера и аналогичных интерфейсов. Для серверных машин можно будет создать общий доступ к одному из указанных серверных адаптеров.

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

OpenVPN

Способы установки виртуальной сети

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

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

OpenVPN

Когда всплывает вопрос о сетевом адаптере TAP, следует разрешить его установку.

Стандартно OpenVPN загружается в папку с программными файлами, расположенную на диске C. Поэтому в ходе инструкции мы будем ссылаться к папке «C:Program FilesOpenVPN». Вы хотите изменить месторасположение файлов? Тогда учитывайте этот нюанс в дальнейшем.

Как сгенерировать ключи и выполнить их шифрование, алгоритм Diffie-Hellman

Для каждой пары ключей существуют свои собственные сертификаты, обеспечивающие безопасность передачи информации. Управлять ими можно специальным приложением Easy-rsa, которое запускается и работает в командной строке, аналогично консоли Линукс. Консоль открывается через нажатие клавиш Win + R и ввода в появившемся окне слова cmd.

Как работать с конфигурационным файлом

Загрузив соответствующий конфигурационный файл, нужно внести его вместо одноименного файла/скрипта, найти который можно в папке OpenVPNeasy-rsa. Директория располагается на диске C в Program Files. Или укажите тот путь, куда вы запланировали установку виртуальной частной сети.

В папке необходимо найти конфигурационный файл openssl-1.0.0.conf, его значения должны соответствовать вашим данным:

countryName_default
stateOrProvinceName_default
localityName_default
0.organizationName_default
emailAddress_default

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

Как генерировать ключи в Центре Сертификации

1. Для начала следует переименовать два файла при помощи командной строки:

cd cd "C:Program FilesOpenVPNeasy-rsa" ren index.txt.start index.txt ren serial.start serial

2. Затем, чтобы создать новый ключ/сертификат, понадобится запуск скрипта:

.build-ca.bat

В окне будут возникать различные предложения, большинство из них можно подтверждать кнопкой Enter. А для поля KEY_CN (Common Name) следует ввести оригинальное название и его же продублировать для поля name.

3. Так же генерируются сертификаты серверу. В этой строке вместе server нужно ввести оригинальное имя:

.build-key-server.bat server

4. Система начнет спрашивать, следует ли подписывать сертификаты для создаваемых ключей от имени Центра сертификации? Введите «да» — y (yes).

OpenVPN

Как генерировать клиентский ключ и сертификат

Всем юзерам виртуальной сети понадобится генерировать свои индивидуальные SSL-сертификаты.

Можно воспользоваться специальной опцией, которая позволяет присваивать 1 сертификат сразу нескольким пользователям. Она называется «dublicate-cn» и размещается в файле server.ovpn. Однако такой ход небезопасен.

Рассмотрим, как сгенерировать сертификат клиенту client2:

cd cd "C:Program FilesOpenVPNeasy-rsa" .build-key.bat client2

Внимание: под переменной client2 подразумевается вносимое название файла. Далее следует ввести client2 в запрос строчки Common Name.

Работа с алгоритмом Диффи-Хеллмана

В завершение всех действий понадобится запуск шифрования, чтобы сгенерировать группу параметров по Диффи-Хеллману:

.build-dh.bat

OpenVPN

Перенос сгенерированных ключей/сертификатов

Все созданные данные располагаются в подпапке easy-rsakeys. Следующие наименования файлов следует перенести в другую подпапку — config, которая располагается в том же месте:

• dh2048.pem/dh1048.pem

• server.key

• ca.crt

• server.crt

Настройка конфигурации на сервере

Запустите редактор реестра и отыщите в нем:

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters.

Справа вы увидите IPEnableRouter. Кликните по переменной два раза – откроется новое окошко для изменения параметров. В поле «Значение» поставьте единицу:

OpenVPN

Настраивать сервер мы будем через конфигурационный файл server.ovpn. Перед работой его следует переместить в папку config.

Открыв его, необходимо проверить правильность построение маршрутов к перенесенным сертификатам:

port 1194
proto udp
dev tun
server 10.8.0.0 255.255.255.0
ca "C:Program FilesOpenVPNconfigca.crt"
cert "C:Program FilesOpenVPNconfigserver.crt"
key "C:Program FilesOpenVPNconfigserver.key"
dh "C:Program FilesOpenVPNconfigdh2048.pem"
push "redirect-gateway def1"
push "dhcp-option DNS 8.8.8.8"
keepalive 10 120
comp-lzo
persist-key
persist-tun
verb 3

Если нужно, то меняем пути на правильные и пересохраняем.

Чтобы успешно пересылать трафик от одного адаптера к другому, нужно зайти в раздел сети и интернета, который находится в панели управления ПК. В нем найти центр сетевого управления и кликнуть по предложению изменить параметры интернет адаптера.

Из нескольких предложенных вариантов надо взять тот, что отвечает за внешние подключения, то есть не TAP-тип, так как он работает с VPN-соединениями.

OpenVPN

В свойствах зайдите на вкладку доступа и поставьте галочки на обоих пунктах:

Следующим шагом включается айпи-переадресация.

Зайдите в стандартный поиск ОС си введите следующее имя приложения:

Настройка автозапуска

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

Стандартные настройки окончены. Чтобы запустить сервер и его новые настройки, надо еще раз войти в файл server.ovpn и написать в него следующую строчку:

Start OpenVPN on this config

Настройки клиентской конфигурации

Виртуальная частная сеть имеет свое клиентское приложение, которое одинаково хорошо загружается для любой существующей операционной системы за исключением Mac – к нему разработан Tunnelblick. Версии приложений функционируют одинаково, затрагивают определенные конфигурационные файлы. В зависимости от версий, могут различаться отдельные опции. Более подробная информация расписана в документации OpenVPN.

Далее мы расскажем, как подключить клиентов на ОС Виндовс, применяя те же дистрибутивы, которые до этого инсталлировались на сервере. В случае с другими операционными системами методы и шаги будут примерно такими же.

1. Для начала на ПК клиента ставится актуальная версия (желательно последняя) OpenVPN.

2. Конфигурационные файлы клиента client.ovpn вместе с сертификатами *.crt и ключами *.key, которые перед этим мы сгеренировали, необходимо поместить в подпапку config, хранящуюся в разделе OpenVPN. При этом желательно файл клиента удалить с директории сервера, чтобы не запутаться при будущих настройках.

3. При открытии client.ovpn необходимо отыскать строчку remote my-server-1 1194. Задайте ей айпи и домен работающего сервера:

remote 1194

Например:

remote 111.222.88.99 1194

4. Ниже в файле обозначен путь к каждому сертификату, меняем их на путь к скопированным версиям:

# 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 "C:Program FilesOpenVPNconfigca.crt"
cert "C:Program FilesOpenVPNconfigclient2.crt"
key "C:Program FilesOpenVPNconfigclient2.key"
# This file should be kept secret

5. После сохранения базовые настройки будут окончены.

Как проверить правила брендмауэра

Чтобы функционирование виртуальной частной сети проходило корректно, на стороне сервера необходимо открыть соответствующий порт. Стандартно его имя UDP 1194.

Зайдите в установленный системный Firewall и посмотрите, разрешен ли доступ к порту антивирусным программным обеспечением и брендмауэром.

Как проверить OpenVPN-подключение

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

Start OpenVPN on this config file

Те же действия необходимо проделать для клиента. Только в этот раз открывается client.ovpn. Остальные действия аналогичны.

Следом должно показаться окно, где отобразится статус соединения. Окно самостоятельно свернется в трею, там же загорится ярлык компьютера с зеленым индикатором (это будет свидетельствовать об успешно проведенной настройке).

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

1. Запустим командную строку комбинацией клавиш Win + R и введением команды cmd.

2. Осуществим пинг к выбранному серверу (10.8.0.1). Для этого введем:

ping 10.8.0.1

3. Если настройка прошла отлично, в окне строки покажется передача пакетов ПК клиента к серверу:

4. Специальная утилита Tracert покажет маршрут, по которому происходит передача клиентских пакетов. Для этого в консоль вводится команда:

tracert ya.ru

Как показывает результат, клиентский пакет отправляется к виртуальному серверу, после чего перенаправляется к внешней сети:

OpenVPN

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

220140
Минск
ул. Домбровская, д. 9

+375 (173) 88-72-49

700
300

ООО «ИТГЛОБАЛКОМ БЕЛ»

220140
Минск
ул. Домбровская, д. 9

+375 (173) 88-72-49

700
300

ООО «ИТГЛОБАЛКОМ БЕЛ»

This weekend a friend of mine asked my advice on setting up a VPN for his  business to enable remote workers to connect and access the office’s file server and other internally hosted data.

The requirements really consisted of a using Windows Server (ease of management) with the ability for MacOSX laptops to connect over a VPN to it.

A couple of years ago, I had a similar setup that I used to connect to my home network using my own MacBook Pro but this time I thought I’d document it to help others.

So, for this setup we’ll use the following software to set-up this solution up:

Server (running Windows Server 2012 R2)

  • OpenVPN Server

Client (running MacOSX 10.11 El Capitan)

  • TunnelBlick (Free OpenVPN client software for MacOSX)

At the time of writing, the following latest stable versions and the versions that are installed as part of this guide are as follows:

  • OpenVPN Server 2.3.10 (openvpn-install-2.3.10-I601-x86_64.exe)
  • TunnelBlick 3.5.5 (Tunnelblick_3.5.5_build_4270.4461.dmg)

You can download both of these versions from my site if you wish!

Once installed, this will enable the client machine (the MacOSX laptop) to connect to the VPN using a split tunnel configuration; using a split tunnel will ensure that only traffic that is destined for the VPN network will be routed over the VPN, your internet connection and other traffic will be routed locally of which will increase speed and performance – Again, this was another requirement, before doing this yourself please understand the security implications of such a setup.

Installing the OpenVPN Server software

We will now log on to our Windows Server 2012 R2 desktop and then run the OpenVPN Server installer (openvpn-install-2.3.10-I601-x86_64.exe) installer, the following screen will appear, click Next to start the installation…

Screenshot 2016-01-31 22.10.01

Next you will be presented with the License Agreement, read and click the I Agree button to continue…

Screenshot 2016-01-31 22.10.16

You’ll then be asked to choose which components to install, you will need to ensure that you select ALL components, this is very important otherwise you will not get Easy-RSA and other utilities that we will need, when you are happen then click Next

Choose where you want to install the software and where the configuration will be stored, I simply accepted the defaults and then click Install

Screenshot 2016-01-31 22.10.49

During the installation you will be prompted to install the virtual TAP NIC adapter, this is a virtual network device that is required by OpenVPN server, you will need to click Install here…

Screenshot 2016-01-31 22.11.04

Once the installation is complete, you’ll then need to click Next

Screenshot 2016-01-31 22.11.22

Installation is now complete, now click Finish and we’ll move on to configuring the server.

Screenshot 2016-01-31 22.11.45

Configure easy-rsa

easy-rsa is a CLI utility to build and manage a PKI CA. In laymen’s terms, this means to create a root certificate authority, and request and sign certificates, including sub-CAs and certificate revokation lists (CRL).

If you are interested, the source code, further information on the utility and the issue tracker can be found on it’s GitHub project page.

Anyway, it’s get on and configure easy-rsa, open up Command Prompt and then type the following commands:

cd \
cd "C:\Program Files\OpenVPN\easy-rsa"
init-config.bat

Running init-config.bat script will generate a new vars.bat file in our easy-rsa directory, this file will contain our configuration. So now we need to open up the following directory using Windows Explorer:

C:\Program Files\OpenVPN\easy-rsa

Now, using Notepad (or another text editor) edit the batch file named vars.bat, we need to configure some variables…

Change the following settings (nearer the bottom of the file) to meet your requirements:

set KEY_COUNTRY=US
set KEY_PROVINCE=CA
set KEY_CITY=SanFrancisco
set KEY_ORG=OpenVPN
set KEY_EMAIL=mail@host.domain
set KEY_CN=changeme
set KEY_NAME=changeme
set KEY_OU=changeme
set PKCS11_MODULE_PATH=changeme
set PKCS11_PIN=1234

Mine now looks as follows – These values are only defaults that will be pre-populated when using the build scripts, and given that the KEY_CN and KEY_NAME will be unique for each build request, I’ve changed them just for reference notes really – this will be outputted so will act as a note to you (the admin) in future:

set KEY_COUNTRY=GB
set KEY_PROVINCE=Suffolk
set KEY_CITY=Ipswich
set KEY_ORG=ALLN
set KEY_EMAIL=ballen@bobbyallen.me
set KEY_CN=Unique/machine name
set KEY_NAME=Use same as the Common Name!
set KEY_OU=ICT
set PKCS11_MODULE_PATH=changeme
set PKCS11_PIN=1234

For the security paranoid amongst us, you may also look at increasing the value of the KEY_SIZE variable from 1024 to, for example 2048 but this will slow down TLS negotiation performance – your call really!

Next you should save the changes to the file and then using Command Prompt, run the following commands:

cd \
cd "C:\Program Files\OpenVPN\easy-rsa"
vars.bat
clean-all.bat

Generate the CA and Server certificates

Great, now we will build the CA (certificate authority) by running the following command:

build-ca.bat

When asked for input, you should be able to accept the defaults (as we set in the vars.bat file earlier but remember, we must specify a KEY_CN (Common Name) and when asked for the Name, it should match the Common Name.

Given that we are creating the Certificate Authority and the standard practice is to call this certificate file ‘ca’, when asked for the Common Name and the Name use ‘ca’ as shown in the screenshot below:

Screenshot 2016-02-01 09.43.43

We now need to build the servers’ certificate file and again, we’ll keep it as simple as possible so we will set the “Common Name” for the servers’ certificate file as ‘server‘ and again, the Name will match this (notice that the name is passed in as the first argument on the build-key-server.bat call):

build-key-server.bat server

In addition to the last created ‘ca’ certificate, this time you will be asked if you wish to sign and then commit the certificate (in both instances, as per the screenshot below choose yes (type ‘y’ and press enter for both!):

Screenshot 2016-02-01 09.49.47

Building client certificates

For each VPN client that connects to the VPN they will need to connect using an SSL certificate and therefore the following process must be ran for each client device that will connect to the VPN.

As a rule of thumb, you could generate and use an SSL certificate for each user that could be used on multiple machine but there should be a single SSL certificate generated for each device so that in the event that a laptop or other device is lost or stolen, the associated certificate can be revoked from the server to prevent unauthorised access to your network.

So for each new client device, run the following command and then input the requested information:

cd \
cd "C:\Program Files\OpenVPN\easy-rsa"
vars.bat
build-key.bat {machine_name}

As before, when prompted for the “Common Name” and the “Name” use the name of the machine, therefore in this instance “bobby-macbookpro” as demonstrated in the example screenshot below:

Screenshot 2016-02-01 10.13.50

Generate Diffie Hellman parameters

To complete the set-up of encryption we must now generate the Diffie Hellman parameters, we do this by typing the following command:

build-dh.bat

The output of running the above command should look as follows:-

Screenshot 2016-02-01 10.20.52

To learn more about the Diffie Hellman protocol, check the Wikipedia article.

Copy the generated certificates to the “config” directory

When using easy-rsa to generate the certificates they are generated and stored under: C:\Program Files\OpenVPN\easy-rsa\keys, the following files in this directory need to be copied to the C:\Program Files\OpenVPN\config directory:

  • ca.crt
  • dh1024.pem
  • server.crt
  • server.key

Once complete, we should start the OpenVPN service in the Services Manager as shown here:

Screenshot 2016-02-01 11.15.00

Be aware: By default the OpenVPN service is set to start manually, therefore if your server reboots you will need to manually start this service before VPN clients can re-connect. If you want to set this to ‘Automatic’, right-click the service name, choose properties and then configure the startup as ‘Automatic’.

Configuring OpenVPN server

Now that we have the certificate and CA creation out of the way, we will now configure the OpenVPN server.

Lets copy the sample configuration files to the ‘config’ directory to give us a base to start our configuration on:

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

We can now edit the “cloned” sample configuration files and of which, once fully configured to meet our preference we will then be used in our production environment.

So, using a text editor (for example, NotePad) edit the server.ovpn file:

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

We need to set the location of the certificates that we generated earlier, therefore locate the following block:

# 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 dh2048.pem

and replace the paths so they match as shown here:

# 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 "C:\\Program Files\\OpenVPN\\config\\ca.crt"
cert "C:\\Program Files\\OpenVPN\\config\\server.crt"
key "C:\\Program Files\\OpenVPN\\config\\server.key" # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
# openssl dhparam -out dh2048.pem 2048
dh "C:\\Program Files\\OpenVPN\\config\\dh1024.pem"

Save the file – Lets move on to configuring the Client configuration!

Configure the Client OpenVPN config file

Similar to the server configuration, we just need to edit the client configuration file and set the remote IP/hostname of our OpenVPN server.

The Client OpenVPN configuration file is then used on the client machines to configure the OpenVPN client to connect to the remote VPN server.

Be aware: If you edit this using NotePad on Windows the line endings will be formatted CLRF of which, will cause issues when trying to load it on the Mac, therefore it is recommended that you use a LF aware editor to edit it or convert the file using dos2unix when using it for the first time on your MacOSX/Linux machine.

Lets edit the file and set the remote server address:

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

Locate the following line:

remote my-server-1 1194

and replace it with your public IP address or hostname that your clients will use to connect to your OpenVPN server, for example:

remote vpn.mydomain.com 1194

Save the file and we’re nearly ready to start testing!!

Configuring port forwarding and firewall rule exceptions

We’re nearly ready to start testing but before we do, assuming you have a router/firewall between your server and the internet you will need to first of all open up port 1194/UDP (don’t forget to enable it on the Windows Server 2012 R2 software firewall too if you haven’t already!) and ensure that the traffic is forwarding to your server without this the VPN clients will not be able to connect and use the newly configured VPN service.

From a “best practice” point of view it is advisable to change the default UDP port in your server and client configurations and ensure that the firewall/router is also updated too this makes it harder for hackers to identify which services are running on your server.

Configuring the OpenVPN client (TunnelBlick) on MacOSX

Now that we have the server and network configured we now need to install TunnelBlick on the MacOSX client device.

The installation of TunnelBlick is so simple that I won’t cover it here but once you have it installed lets continue…

First of all we need to create a directory in our home directory to store the client and CA certificates that we will copy from our server shortly.

I would recommend that you create a directory in the root of your home directory called ‘OpenVPN Client Config’, you can do this in the terminal like so:

mkdir ~/OpenVPN\ Client\ Config

Now copy the following file from your Server:

  • C:\Program Files\OpenVPN\config\client.ovpn
  • C:\Program Files\OpenVPN\easy-rsa\keys\ca.cert
  • C:\Program Files\OpenVPN\easy-rsa\keys\bobby-macbookpro.crt
  • C:\Program Files\OpenVPN\easy-rsa\keys\bobby-macbookpro.key

Into the new OpenVPN Client Config directory in your home directory like so:

Screenshot 2016-02-01 11.53.31

Now we have to make some minor adjustments to he certificate paths in the client.ovpn file so, using a text editor, open the file on your Mac and update the certificate paths to match your environment like so:

# 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 "/Users/ballen/OpenVPN Client Config/OpenVPN Config/ca.crt"
cert "/Users/ballen/OpenVPN Client Config/bobby-macbookpro.crt"
key "/Users/ballen/OpenVPN Client Config/bobby-macbookpro.key"

Save the file and close the text editor, we then need to install our new configuration by double-clicking the client.ovpn icon as shown in the above screenshot.

Double-clicking the icon will prompt as follows, click “Only Me”:

Screenshot 2016-02-01 11.56.11

Once the configuration has been added, you’ll get notification of success as shown here:

Screenshot 2016-02-01 11.57.32

Connecting to the VPN for the first time

Now that the configuration has been added to TunnelBlick, using the TunnelBlick icon in the top-right hand corner you should now be able to connect to it:

Screenshot 2016-02-01 11.58.18

TunnelBlick should now happily connect to the VPN…

Screenshot 2016-02-01 11.58.28

Now that you are connected to your VPN, test out by “pinging” the server IP address:

ping 10.8.0.1

To disconnect from it, simply click the TunnelBlick icon and choose ‘Disconnect client’…

Screenshot 2016-02-01 11.58.41

In my next post (otherwise this post will be huge) I will cover the advanced configuration of the server to enable your VPN clients to “see” your internal network and your internal network to “see” your VPN clients this will bidirectional transfer of data eg. accessing network shares on the network and other services provided on the office network.

В этой статье мы приводим подробную инструкцию по настройке частных серверов на ОС Windows Server, а также по присоединению клиентов к созданной программе OpenVPN.

Для начала расшифруем понятие. Программа предназначена для открытой работы виртуальной частной сети между двумя разными отдаленными узлами, помимо интернета, через который осуществляется передача данных. Применяется в тех случаях, когда требуется безопасное соединение путем шифрования программой OpenSSL. При этом доступ остается закрытым. Аренда виртуальных серверов от oblako.kz.

Содержание:

  • Механизм работы
  • Инсталляция
  • Создание пар ключей, генерация параметров
  • Настройки сервера
  • Совокупность параметров клиента
  • Проверка правил и соединения

Механизм работы

OpenVPN

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

Общий доступ для клиентов можно настроить таким образом, что соединение будет происходить с определенным сетевым адаптером, расположенным на сервере. Также чуть ниже мы разберем соответствующие логическое построение трафика пользователей. При такой инкапсуляции протоколов хост, который проводит обработку входящих соединений, играет дополнительную роль прокси-сервера. Хост стандартизирует правила интернет-активности клиентов и определяет путь следования их трафика от своего имени.

OpenVPN

Инсталляция

Первый шаг — это необходимость загрузить и установить последнюю версию программы, подходящей к требованиям вашей операционной системы. Скачать актуальное приложение можно здесь. После скачивания OpenVPN запустите инсталляцию программы. На третьем этапе установке необходимо удостовериться в том, что выбраны все компоненты программы для инсталляции, как это изображено ниже.

OpenVPN Setup

Важно! Прежде чем приступать к дальнейшим действиям, нужно учесть, что в данных примерах все действия проводятся с учетом того, что приложение устанавливается в директорию, расположенную по адресу C:\Program Files\OpenVPN. Если вы выбираете другую, сообразуйте свои действия с данными другой директории.

Итак, далее система запросит добавление TAP. Следующий шаг – разрешение установки виртуального сетевого адаптера, после чего необходимо дождаться окончания инсталляции.

Создание пар ключей, генерация параметров

Чтобы создавать и менять пары «ключ-сертификат», необходимо использование вспомогательной программы. Утилита работает через консоль Windows. Чтобы запустить утилиту easy-rsa, войдите в консоль (одновременное нажатие кнопок Win+R), после введите команду cmd и щелкните на Enter.

Файлы настроек

С этой страницы вы можете загрузить конфигурационные и программные файлы, после чего переместить их туда, где расположена программа easy-rsa. Убедитесь в совпадении путей, при необходимости внесите изменения во все документы.

В файл настроек openssl-1.0.0.conf необходимо внести коррективы согласно вашим данным. Обратите внимание, если в значении переменной есть проблем, то необходимо заключить данные в кавычки.

countryName_default
stateOrProvinceName_default
localityName_default
0.organizationName_default
emailAddress_default

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

  1. Необходимо внести изменения в названия документов index.txt.start и serial.start следующим образом: Запустите следующий скрипт: cd \
    cd "C:\Program Files\OpenVPN\easy-rsa"
    ren index.txt.start index.txt
    ren serial.start serial
  2. Начнется создание необходимого ключа: .\build-ca.bat
  3. Система будет задавать вопросы, на которые можно реагировать нажатием клавиши Enter. Кроме одного случая, в строку KEY_CN внесите данные уникального имени, а затем скопируйте его в строку name.
  4. Создаем сертификат. В строки name и Common Name нужно внести данные имени будущего файла. .\build-key-server.bat server

    После изменения для всех ключей, которые будут создаваться, будет всплывать запрос подписи генерируемого сертификата. Необходимо отвечать «Да» (y).

    Консоль

Создание пар для клиента

Уникальный сертификат шифрования нужно создавать для всех клиентов по отдельности. В настройках утилиты есть специальный параметр, который позволяет использовать всего один SSL-сертификат для разных клиентов, однако это не самый лучший выбор, так как опция не гарантирует полного соблюдения безопасности. Создавать сертификаты возможно в течение работы для каждого нового клиента согласно их присоединению, поэтому рассмотрим создание единственного SSL-сертификата для client1 (в дальнейшем название следует менять на имя вашего файла).

Введите такие команды, чтобы сгенерировать ключи клиента:

cd \
cd "C:\Program Files\OpenVPN\easy-rsa"
.\build-key.bat client1

В строке Common Name введите данные имени будущего клиента (сейчас указываем client1).

Обмен ключей по Диффи-Хеллману

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

.\build-dh.bat

Созданные параметры будут отображаться следующим образом:

OpenVPN

Перемещение ключей и сертификатов

Готовые данные расположены по такому пути C:\Program Files\OpenVPN\easy-rsa\keys. Выберите документы:

  • ca.crt;
  • dh2048.pem/dh1048.pem;
  • server.crt;
  • server.key.

Перенесите их по пути C:\Program Files\OpenVPN\config.

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

Войдите в редактор реестра, откройте HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters. С правой стороны экрана будет отображено содержание папки, где необходимо выбрать файл IPEnableRouter. Двойным нажатием левой клавиши мыши откройте окно редактирования переменной, измените значение параметра на «1», как показано ниже. Эти действия позволят разрешить переадресацию на VPS.

Редактор реестра

  1. Перейдем к настройке. Выберите документ настройки с названием server.ovpn (загрузить его можно у нас, ссылка была приведена выше) и перенесите его сюда — C:\Program Files\OpenVPN\config.

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

    port 1194
    proto udp
    dev tun
    server 10.8.0.0 255.255.255.0
    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"
    push "redirect-gateway def1"
    push "dhcp-option DNS 8.8.8.8"
    keepalive 10 120
    comp-lzo
    persist-key
    persist-tun
    verb 3

  2. Войдите в инструмент управления системой, выберите пункт «Сеть и интернет», затем перейдите к управлению подключениями и щелкните на «Изменение параметров адаптера». Для разрешения передачи данных между адаптерами, необходимо выбрать тот, который отвечает за внешнее соединение.

    Ethernet

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

  3. В строке поиска операционной системы найдите приложение REGEDIT.exe, которое поможет настроить адресацию по IP-адресу.

Автоматический запуск службы

Если вы хотите, чтобы OpenVPN включался автоматически при начале работы системы, необходимо произвести приведенные ниже настройки.

Войдите в меню «Службы» операционной системы. В списке найдите OpenVPN, далее выберите «ПКМ», затем «Свойства», в строке запуск поставьте значение «Автоматически».

Таким образом базовая настройка завершена. Перейдите по пути C:\Program Files\OpenVPN\config\server.ovpn. Нажмите на файл, во всплывающем меню щелкните на команду, которая помогает запустить сервер.

Совокупность параметров клиента

Существуют программы для всех распространенных систем (для MacOS применяется специальная утилита Tunnelblick). Все программы OpenVPN функционируют на основании одинаковых конфигурационных данных с небольшими различиями в некоторых параметрах. Чтобы выяснить разницу в опциях, необходимо ознакомиться с документацией определенного клиента. Ниже мы разберем подключение клиента операционной системы Windows, используя тот же установочный пакет, который применялся при установке сервера. Соответственно, при установке приложения на прочие операционные системы, пошаговое руководство аналогично (с учетом внесения изменений).

  1. Установите последнюю версию приложения.
  2. Скопируйте файлы сгенерированных ранее сертификатов в директорию C:\Program Files\OpenVPN\config. Файл с названием client.ovpn необходимо удалить с сервера, когда вы его перенесете.
  3. Откройте этот документ, найдите приведенную ниже строку и введите данные доменного имени сервера или его ip-адрес. Пример: remote 1194
    remote 111.222.88.99 1194
  4. Согласно приведенному ниже примеру укажите пути до сертификатов, которые были скопированы во втором шаге. # 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 "C:\\Program Files\\OpenVPN\\config\\ca.crt"
    cert "C:\\Program Files\\OpenVPN\\config\\client1.crt"
    key "C:\\Program Files\\OpenVPN\\config\\client1.key"
    # This file should be kept secret
  5. Сохраните изменения и закройте файл – настройка окончена успешно.

Проверка правил и соединения

Важно! Для правильной работы приложения, необходимо открыть нужные порты. Чтобы сделать это, необходимо войти в файерволл вашей ОС (по умолчанию брандмауэр или иная установленная программа-антивирус) и проверить настройки — открыть порт UDP 1194.

Для проверки соединения клиента нужно включить OpenVPN сервер. Затем откройте установочный файл сервера, расположенный по пути C:\Program Files\OpenVPN\config.

Откроется окно, демонстрирующее параметр подключения, которое автоматически свернется и перейдет на панель задач. Если ярлык программы горит зеленым светом, значит, процедура подключения прошла успешно.

Затем необходимо убедиться в открытости сервера по отношению к устройству клиента с использованием внутреннего адреса сети.

  1. Откройте командную консоль;
  2. Введите данные ping; ping 10.8.0.1
  3. Если все работает правильно, то запустится процесс обмена пакетами с сервером;

    Вывод

  4. В командную строку введите приведенную ниже команду для запуска программы, проверяющей маршрут: tracert ya.ru
  5. Ниже можно увидеть, что пакеты данных идут во внешнюю сеть только через виртуальный сервер.

    Трассировка маршрута

На этом настройка OpenVPN сервера на Windows Server 2008/2012 окончена. В нашей базе знаний вы найдёте ещё множество статей посвящённых различным аспектам работы в Windows, а если вы ищете надежный виртуальный сервер под управлением Windows, обратите внимания на нашу услугу — Аренда виртуального сервера Windows.

This is a step-by-step guide on how to configure an Open VPN server on Windows Server 2008/2012 operating systems and connect clients to the created virtual private network.

Open VPN is an open implementation of VPN technology — the Virtual Private Network, which is designed to create virtual private networks between groups of geographically distant nodes on top of an open data transmission channel (Internet). Open VPN is suitable for tasks such as secure remote network connection to a server without opening Internet access to it, as if you are connecting to a host on your local network. Connection security is achieved by Open SSL encryption.

How it works?

When the Open VPN configuration is completed, the server will be able to accept external SSL-protected network connections to the virtual network adapter created at the start of the VPN service (tun / tap) without affecting the traffic processing rules of other interfaces (external Internet adapter, etc.). You can configure client sharing Open VPN to a specific network adapter from those present on the server. In the second part of the instruction, this tunneling of users’ Internet traffic is considered. With this method of forwarding, the host that handles VPN connections will also perform the function of a proxy server (Proxy) — to unify the rules of network activity of users and to route client Internet traffic on its own behalf.

Installing Open VPN on the server

Download and install version of Open VPN that matches your operating system. Run the installer; make sure that all features are selected for installation in the third step of the installation wizard.

open VPN -- install open VPN-choose all_1

Please note that in this instruction further commands are based on the fact that Open VPN is installed in the default directory «C: \ Program Files \ OpenVPN».

We allow adding a virtual network adapter TAP in response to the corresponding request and wait until the installation is complete (it may take several minutes).

Key generation (PKI) of the certification center, server, client; Diffie-Hellman algorithm

To manage the key / certificate pairs of all nodes of the private network being created, use the easy-rsa utility, which works via the command line, by analogy with the Linux console. To work with it, open, run the command line (Keyboard shortcut Win + R, then type cmd and press Enter)

Configuration files.

Running init-config.bat script will generate a new vars.bat file in our easy-rsa directory, this file will contain our configuration:

cd "C:\Program Files\OpenVPN\easy-rsa"
init-config.bat

So now we need to open up the following directory using Windows Explorer: C:\Program Files\OpenVPN\easy-rsa

Now, using Notepad (or another text editor) edit the batch file named vars.bat, we need to configure some variables…

Change the following settings (nearer the bottom of the file) to meet your requirements:

set KEY_COUNTRY=US
set KEY_PROVINCE=CA
set KEY_CITY=SanFrancisco
set KEY_ORG=OpenVPN
set KEY_EMAIL=mail@host.domain
set KEY_CN=changeme
set KEY_NAME=changeme

Note: if the value of the variable contains a space, enclose it in quotes.

Next you should save the changes to the file and then using Command Prompt, run the following commands:

cd "C:\Program Files\OpenVPN\easy-rsa"
vars.bat
clean-all.bat

Certification Center and Server Key Generation

Let’s proceed to the creation of the key / certificate of the certification authority. Run the script:

build-ca.bat

In response to the prompts that appear, you can simply press Enter. The only exception is the KEY_CN (Common Name) field — be sure to specify a unique name and insert the same name in the Name field:

open VPN -- install open VPN-ca generation

Similarly, we generate a server certificate. Here the value of the Common Name and Name fields is SERVER:

.\build-key-server.bat server

Note: the server argument is the name of the future file.

All generated keys will now be asked whether to sign the generated certificate (Sign the certificate) on behalf of the certification authority. Answer y (yes).

open VPN -- install open VPN-server key generation

Generating client keys and certificates

For each VPN client, you need to generate a separate SSL certificate.

There is an option in the Open VPN configuration, by enabling which you can use one certificate for several clients (see the server.ovpn file -> «dublicate-cn» file), but this is not recommended from a security point of view. Certificates can be generated in the future, as new customers connect. Therefore, now we will create only one for client1:

Run the following commands to generate client keys:

cd \
cd "C:\Program Files\OpenVPN\easy-rsa"
.\build-key.bat client1

Note: client1 argument is the name of the future file.

In the Common Name field, specify the name of the client (in our case client1).

open VPN -- install open VPN-client key generation

Diffie Hellman Parameters

To complete the encryption setting, you need to run the Diffie-Hellman parameter generation script:

.\build-dh.bat

Displaying information about creating parameters looks like this:

open VPN -- install open VPN-dh generation

Transferring generated keys / certificates

The generated certificates are located in the C: \ Program Files \ OpenVPN \ easy-rsa \ keys directory. Copy the files listed below to the directory C:\Program Files\OpenVPN\config:

  • ca.crt
  • dh2048.pem/dh1048.pem
  • server.crt
  • server.key

Open VPN server configuration

Let’s proceed to the configuration of the VPN server directly, use our configuration file with the name server.ovpn and place it in the C: \ Program Files \ OpenVPN \ config directory.

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

    Open the file; find the path to the keys (see below). Check the paths to the previously copied certificates ca.crt, dh1024.pem / dh2048.pem, server.key, server.crt and, if necessary, change:

    port 1194
    proto udp
    dev tun
    server 10.8.0.0 255.255.255.0
    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"
    push "redirect-gateway def1"
    push "dhcp-option DNS 8.8.8.8"
    keepalive 10 120
    comp-lzo
    persist-key
    persist-tun
    verb 3

    Save the file.

    Now you need to allow traffic forwarding between adapters. Follow these steps: Control Panel -> Network and Internet -> Network and Sharing Center -> Change adapter settings. Choose an adapter that looks to the external Internet (TAP-adapter is responsible for the VPN connection). In our example, this is Ethernet 2.

    Double-click the adapter Properties and go to the Access tab, tick all the checkboxes. Save the changes.

    Next you need to enable IP addressing.

    Using Windows Search, locate the REGEDIT.exe application.

    In the tree, find the directory HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ Tcpip \ Parameters. In the right part of the window, find the IPEnableRouter variable, double-click into the value editing window and change it to 1, thereby allowing addressing on the VPS.

    open VPN -- enable ip addressing regedit

      Autorun Open VPN

      Immediately configure the Open VPN service to autorun at system startup.

      Open the Windows Services. Find in the list Open VPN -> right-click -> Properties -> Start: Automatic

      open VPN -- enable service.png

      This completes the basic configuration of the virtual private network server. Find the file C: \ Program Files \ OpenVPN \ config \ server.ovpn -> right-click -> «Start OpenVPN on this config» to start the virtual private network server and the configuration file we prepared.

      Open VPN Client Configuration

      Open VPN client applications are available for all popular operating systems: Windows / Linux / iOS / Android. For MacOS, the Tunnelblick client is used. All of these applications work with the same configuration files. Only some differences of several options are possible. You can learn about them by examining the documentation for your Open VPN client. In this guide, we will look at connecting a Windows client using the same distribution package of the program that we installed on the server. When using applications for other operating systems, the setup logic is similar.

      1. Install the current version of Open VPN on the client computer.
      2. Copy to the directory C: \ Program Files \ OpenVPN \ config the client certificate files created earlier on the server (2 certificates with the .crt extension and the key with the .key extension) and use our client.ovpn client configuration file. After copying to the user’s device, the last file is deleted from the server or transferred from the config folder to avoid confusion in the future.
      3. Open the client.ovpn file. Find the line remote my-server-1 1194 and specify the ip-address or domain name of the vpn-server in it:

        remote <ip-address> 1194</ip-address>

        For example:

        remote 83.166.241.155 1194
      4. Find ways to certificates. Specify in it the paths to the ca.crt, client1.key, client1.crt certificates copied earlier as in the example below:

        # 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 "C:\\Program Files\\OpenVPN\\config\\ca.crt"
        cert "C:\\Program Files\\OpenVPN\\config\\client1.crt"
        key "C:\\Program Files\\OpenVPN\\config\\client1.key"
        # This file should be kept secret
      5. Save the file. Client setup complete.

      Verify Windows Firewall Rules

      Attention! For the correct operation of the OpenVPN service, it is required that the corresponding ports be opened on the server (by default UDP 1194). Check the relevant rule in your Firewall: Windows Firewall or third-party anti-virus software.

      Check OpenVPN connections

      Start the Open VPN server, to do this, go to the directory C: \ Program Files \ OpenVPN \ config and select the server configuration file (we have server.ovpn -> right-click -> «Start OpenVPN on this config file»).

      Start the client, to do this, go to the directory C: \ Program Files \ OpenVPN \ config and select the client configuration file (we have client.ovpn -> right-click -> «Start Open VPN on this config file»).

      The screen displays the connection status window. In a few seconds it will be minimized to tray. The green indicator of the Open VPN shortcut in the notification area indicates a successful connection.

      Check the accessibility from the client device of the OpenVPN server using its internal private network address:

      1. Press the Win + R keys and type cmd in the window that appears to open the command line.
      2.  Execute the ping command to the address of our server in a virtual private network (10.8.0.1):

        ping 10.8.0.1

        If the VPN is configured correctly, the packet exchange with the server will start.

        openVPN -- ping.png

      3. With the help of the tracert utility, we will check on which route the packets from the client go. In the console, enter the following command:

      From the result of the utility, we see that the packets are first sent to the VPN server, and only then to the external network.

      Now you have a ready-to-work virtual private network that allows you to make secure network connections between its clients and the server using open and geographically distant points of connection to the Internet.

      Create an Utho account to try this guide with a $100 credit.
      Sign Up

      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!

      Create an Utho account to try this guide with a $100 credit.
      Sign Up

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

      0 комментариев
      Старые
      Новые Популярные
      Межтекстовые Отзывы
      Посмотреть все комментарии
    1. Ежедневник с напоминаниями для windows
    2. Запись экрана windows 10 через xbox
    3. Вардрайвинг wifi на windows
    4. Для этой операции требуется съемный носитель например usb устройство флэш памяти windows 10
    5. Какие папки нельзя создать в windows