Перед выполнением описанных ниже команд убедитесь, что вы используете последнюю версию WireGuard и обладаете правами администратора на вашем устройстве.
Установка
1) Скачайте текущую версию для Windows: https://www.wireguard.com/install/ и установите.
2) Запустите C:\Program Files\WireGuard\wireguard.exe и добавьте пустой туннель (мы будем настраивать серверную часть):
Добавить туннель → Добавить пустой туннель …
Регистрируем настройки:
Имя — имя сетевого подключения
Открытый ключ — открытый ключ сервера WireGuard (необходим для настройки клиентской части)
[Interface] PrivateKey = # private key of WireGuard server ListenPort = # port that WireGuard will listen to Address = # desired IP address of WireGuard server
Включить параметры, позволяющие серверу WG использовать основной сетевой интерфейс
3) Добавляем еще один пустой туннель (будем настраивать клиентскую часть): Add tunnel → Add empty tunnel
Регистрируем настройки:
Имя — имя сетевого подключения
Открытый ключ — открытый ключ клиента WireGuard (необходим для настройки серверной части)
[Interface] PrivateKey = # WireGuard client private key Address = # desired IP address of WireGuard client [Peer] PublicKey = # public key of the WireGuard server (from step 2) AllowedIPs = # specify the IP addresses for which you want to use the created WG tunnel (specifying the subnet 0.0.0.0/0 will allow you to route all traffic to the WG tunnel) Endpoint = # Server IP address (real, not WireGuard) and port that WireGuard server listens on (configured in step 2)
4) Теперь нам нужно добавить нашего клиента в серверную часть WireGuard, для этого вернитесь к шагу 2 и добавьте его конфиг:
... [Peer] PublicKey = #WireGuard client public key (from step 3) AllowedIPs = #IP user address
5) Настроим брандмауэр Windows для работы с WireGuard. Для этого:
- Создадим новое правило для входящего трафика:
-
Откройте «Windows Defender Firewall with Advanced Security» (Брандмауэр Windows с повышенной безопасностью).
-
В левой панели выберите «Inbound Rules» (Входящие правила).
-
Нажмите «New Rule…» (Создать правило).
-
- Укажем протокол (UDP) и порты (например, 51820):
-
В появившемся окне «New Inbound Rule Wizard» выберите «Port» (Порт) и нажмите «Next» (Далее).
- В разделе «Protocol and Ports» (Протокол и порты) выберите тип протокола:
-
Выберите «UDP».
-
- Укажите конкретные локальные порты (Specific local ports):
-
Например, порт WireGuard по умолчанию — 51820.
-
Если используется несколько портов, перечислите их через запятую (например: 51820, 51821).
-
-
Нажмите «Next» (Далее).
-
- Разрешим подключения:
-
В разделе «Action» (Действие) выберите «Allow the connection» (Разрешить подключение).
-
Нажмите «Next» (Далее).
-
- Сохраним правило:
- Определите профили, для которых будет применяться правило:
-
Domain (Доменный);
-
Private (Частный);
-
Public (Общий).
-
-
Нажмите «Next» (Далее).
-
Укажите понятное имя для нового правила, например: «WireGuard UDP 51820».
-
Нажмите «Finish» (Готово).
- Определите профили, для которых будет применяться правило:
Ваш брандмауэр настроен на пропуск трафика через указанные порты WireGuard
6) Теперь достаточно экспортировать файлы конфигурации Экспортировать все туннели в zip→Указатьместо для экспорта→Сохранить
Далее откройте сохраненный архив, там будут конфигурации всех наших туннелей.
Отдайте клиенту его конфигурационный файл.
7) На сервере выберите конфигурацию сервера и запустите программу

Выберите конфигурацию клиента и запустите программу
На этом настройка первого клиента завершена, аналогичным образом настраиваются остальные клиенты путем добавления их данных в конфигурацию сервера (шаг 4).
Автоматический запуск WireGuard после перезапуска сервера.
1) Добавьте файл запуска в автозапуск планировщика Windows: Пуск→taskschd.msc
Нажмите «Создать простую задачу» → Введите имя задачи (например, wireguard) → Далее
Выберите «При запуске компьютера» → Далее
Выберите «Запустить программу»→ Далее
В поле «Программа или сценарий» выберите файл для запуска WireGuard (по умолчанию это «C:\Program Files\WireGuard\wireguard.exe»).
Добавьте аргументы:
/installtunnelservice "C:\Program Files\WireGuard\wg_server.conf"
где:
C:\Program Files\WireGuard\wg_server.conf — расположение конфигурационного файла *.conf
Установите флажок «Открыть окно свойств для этой задачи после нажатия кнопки «Готово»» → Готово
В открывшемся окне отметьте пункт «Запускать с наивысшими правами»→ОК
Готово. Выполните перезагрузку, проверьте
Wg Server for Windows
WS4W is a desktop application that allows running and managing a WireGuard server endpoint on Windows.
Inspired by Henry Chang’s post, How to Setup Wireguard VPN Server On Windows, my goal was to create an application that automated and simplified many of the complex steps. While still not quite a plug-and-play solution, the idea is to be able to perform each of the prerequisite steps, one-by-one, without running any scripts, modifying the Registry, or entering the Control Panel.
Getting Started
The latest release is available here. Download the installer and run.
Note: The application will request to run as Administrator. Due to all the finagling of the registry, Windows services, wg.exe calls, etc., it is easier to run the whole application elevated.
Upgrade from 1.5.2
Before introducing an installer, WS4W was distributed as a portable application. The portable versions (1.5.2 and earlier) have no automatic upgrade path to the installer version. To upgrade, simply delete the downloaded portable version and download the installer. No configuration settings will be lost.
What Does It Do?
Below are the tasks that can be performed automatically using this application.
Before
WireGuard.exe
This step downloads and runs the latest version of WireGuard for Windows from https://download.wireguard.com/windows-client/wireguard-installer.exe. Once installed, it can be uninstalled directly from WS4W, too.
Server Configuration
Here you can configure the server endpoint. See the WireGuard documentation for the meaning of each of these fields. The Private Key and Public Key are generated by calling wg genkey and wg pubkey [private key] respectively. (You can optionally supply your own Private Key.)
Note: It is important that the server’s network range not conflict with the host system’s IP address or LAN network range.
In addition to creating/udpating the configuration file for the server endpoint, editing the server configuration will also update the ScopeAddress registry value (under HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters). This is the IP address that is used for the WireGuard adapter when using the Internet Sharing feature (explained here). Thus, the Address property of the server configuration serves to determine the allowable addresses for clients, as well as the IP that Windows will assign to the WireGuard adapter when performing Internet Sharing. Note the IP address is grabbed from the ScopeAddress at the time when Internet Sharing is first performed. That means that if the server’s IP address is changed in the configuration (and thus the ScopeAddress registry value is updated), the WireGuard interface will no longer accurately reflect the desired server IP. Therefore, WS4W will prompt to re-share internet. If canceled, Internet Sharing will be disabled and will have to be re-enabled manually.
Important: You must configure port forwarding on your router. Forward all UDP traffic that is destined for your server endpoint port (default
51820) to the LAN IP of your server. Every router is different, so it is difficult to give specific guidance here. As an example, here is what the port forwarding rule would look like on a Verizon Quantum Gateway router.![]()
You should set the Endpoint property to your public IPv4, IPv6, or domain address, followed by whatever port you have forwarded. The Detect Public IP Address button will attempt to detect your public address automatically using the ipify.org API. However, if possible, it is recommended that you use a domain name with DDNS. That way, if your public IP address changes, your clients will be able to find your server endpoint without reconfiguration.
Client Configuration
Here you can configure the client(s). The Address can be entered manually or calculated based on the server’s network range. For example, if the server’s network is 10.253.0.0/24, the client config can determine that 10.253.0.2 is a valid address. Note that the first address in the range (in this example, 10.253.0.1) is reserved for the server. DNS is optional, but recommended. You may add DNS Search Domains (also known as DNS Suffixes, read more). Lastly, the Private Key, Public Key, and Preshared Key are generated using wg genkey, wg pubkey [private key], and wg genpsk. (You may specify your own Private Key. Preshared Keys are optional, generated uniquely per-client, and shared with the server’s configuration. See #34 for more info.)
Due to a bit of a quirk in WireGuard, if you were to remove a client Preshared Key and sync the server configuration, WireGuard would still expect the client to connect with a PSK. Therefore, WS4W does not allow you to clear the Preshared Key field from clients. Instead, delete and recreate a client to remove the PSK.
Once configured, it’s easy to import the configuration into your client app of choice via QR code or by exporting the .conf file.
For security, you may not want to keep the clients’ private keys on the server. In that case, you may clear the private key field before saving a client configuration. However, there are two things to keep in mind.
- You should export the client config (via QR code or file) before removing the private key and saving.
- If you ever need to import the config to your client again, you will have to re-generate both the private and public keys.
Tunnnel Service
Once the server and client(s) are configured, you may install the tunnel service, which creates a new network interface for WireGuard using the wireguard /installtunnelservice command. After installation, the tunnel may be also removed directly within WS4W. This uses the wireguard /uninstalltunnelservice command.
After completing this step, WireGuard clients should be able to get as far as performing a successful handshake with the server.
Note: If the server configuration is edited after the tunnel service is installed, the tunnel service will automatically be updated via the
wg syncconfcommand (if the newly saved server configuration is valid). This is also true of the client configurations, updates to which often cause the server configuration to be updated (e.g., if a new client is added, the server configuration must be aware of this new peer).
Private Network
Even after the tunnel service is installed, some protocols may be blocked. It is recommended to change the network profile to Private, which eases Windows restrictions on the network.
This step also creates a Windows Task to make the network Private automatically on boot. You may disable the Task via the dropdown.
Note: On a system where the shared internet connection originates from a domain network, this step is not necessary, as the WireGuard interfaces picks up the profile of the shared domain network.
Routing
The last step is to allow requests made over the WireGuard interface to be routed to your private network or the Internet. To do so, the connection of the «real» network adapter on the Windows machine must be shared with the virtual WireGuard adapter. This can be done in one of two ways.
- NAT Routing
- Internet Sharing + Persistent Internet Sharing
The first option is only available on some systems (see more below). The second options may be used as necessary, but have some caveats (such as, if the Internet Connection is shared with the WireGuard adapter, it cannot be shared with any other adapter; see #18). There have also been multiple issues reported with Internet Sharing, so NAT Routing should be used if available.
These options are mutually exclusive.
NAT Routing
Here you can create a NAT routing rule on the WireGuard interface to allow it to interact with your private/public network. Specifically, the following commands are invoked.
New-NetIPAddressis called on the WireGuard adapter to assign a static IP in the range of the Server Configuration’s Address property.New-NetNatis called to create a new NAT rule on the WireGuard adapter.- A Windows Task is created to call
New-NetIPAddresson boot.- If you do not wish to have the Windows Task automatically configure the WireGuard interface on boot, you can press the dropdown and choose «Disable Automatic NAT Routing».
NAT Routing requires at least Windows 10, and the option to enable it will not even appear in the application on older versions of Windows. However, even with Windows 10, NAT Routing does not always work. Sometimes it requires Hyper-V to be enabled, which the application will prompt for, but that also requires a Pro or higher (i.e., not Home) version of Windows. Ultimately, if the application is unable to enable NAT Routing, it will recommend using Internet Connection Sharing instead (below). See #30 for a full discussion about NAT Routing support.
Internet Sharing
If NAT Routing is not available, you can use internet sharing to provide network connection to the WireGuard interface. When configuring this option, you may select any of your network adapters to share. Note that it will likely only work for adapters whose status is Connected, and it will only be useful for adapters which provide internet or LAN access. When choosing the adapter to share, hover over the menu item to get more details, including the adapter’s assigned IP address, to determine if it’s the one you want to share.
Note: When performing internet sharing, the WireGuard adapter is assigned an IP from the
ScopeAddressregistry value (underHKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters). This value is automatically set when updating the Address property of the server configuration. See more here.
Persistent Internet Sharing
There are issues in Windows that cause Internet Sharing to become disabled after a reboot. If the WireGuard server is intended to be left unattended, it is recommended to enable Persistent Internet Sharing so that no interaction is required after rebooting.
When enabling this feature, two actions are performed in Windows:
- The
Internet Connection Sharingservice startup mode is changed fromManualtoAutomatic. - The value of the
EnableRebootPersistConnectionregstry value inHKLM\Software\Microsoft\Windows\CurrentVersion\SharedAccessis set to1(it is created if not found).
Even with these workarounds, Internet Sharing can become disabled after a reboot. Therefore, one more action is performed. A Scheduled Task is created that disables and re-enables Internet Sharing using the WS4W CLI upon system boot. This should be sufficient to guarantee that sharing remains enabled.
View Server Status
Once the tunnel is installed, the status of the WireGuard interface may be viewed. This is accomplished via the wg show command. It will be continually updated as long as Update Live is checked.
Settings
-
Set Boot Task Delay
This setting allows configuring a delay for boot tasks. This can be useful for tasks that depend on adapters which are slow to load. Note that tasks must be disabled and re-enabled after changing this value.
After
CLI
There is also a CLI bundled in the portable download called ws4w.exe which can be invoked from a terminal or called from a script. In addition to messages written to standard out, the CLI will also set the exit code based on the success of executing the given command. In PowerShell, for example, the exit code can be printed with echo $lastexitcode.
Note: The CLI must also be run as an Administrator for the same reasons as above.
Usage
The CLI uses verbs, or top-level commands, each of which has its own set of options. You can run ws4w.exe --help for a list of all verbs or ws4w.exe verb --help to see the list of options for a particular verb.
List of Supported Verbs
ws4w.exe restartinternetsharing [--network <NETWORK_TO_SHARE>]- This will tell WS4W to attempt to restart the Internet Sharing feature.
- The
--networkoption may be passed to specify which network WS4W should share. - If Internet Sharing is already enabled, WS4W will attempt to reshare the same network (unless
--networkis passed). - If multiple networks are already shared, it is not possible to tell which one is shared with the WireGuard network, so the
--networkoption must be passed to specify. - If Internet Sharing is not already enabled, the
--networkoption must be passed, otherwise there is no way to know which network to share. - The exit code will be 0 if the requested or previously shared network was successfully reshared.
This command is used by the Scheduled Task that is created when Persistent Internet Sharing is enabled.
ws4w.exe setpath- This will tell WS4W to add the current executing directory to the system’s
PATHenvironment variable. - This verb has no options.
This command is used by the installer when the «Add CLI to PATH» option is selected.
- This will tell WS4W to add the current executing directory to the system’s
ws4w.exe setnetipaddress --serverdatapath <PATH_TO_SERVER_CONFIG>- This will tell WS4W to call
Set-NetIPAddresson the WireGuard interface, using the network Address as defined in the given WireGuard server configuration file.
This command is used by the Scheduled Task that is created when NAT Routing is enabled.
- This will tell WS4W to call
ws4w.exe privatenetwork- This will set the category of the WireGuard network interface to Private.
- This verb has no options.
This command is used by the Windows Task that is created when Private Network is enabled.
Known Issues
Inability to Enable Internet Sharing
First, it is recommended to use NAT Routing if available.
However, if you experience the following error message when enabling Internet Sharing, please perform the following manual steps.
- Open Network Connections in the Control Panel.
- Right-click > Properties on the network interface that you want to share.
- Go to the Sharing tab and check «Allow other network users to connect through this computer’s Internet connection».
- From the «Home networking connection» dropdown, choose
wg_server. - Press OK.
- Close and reopen WS4W. It should now show Internet Sharing enabled, and subsequent attempts to disable/re-enable should be sucessful going forward.
Note: This issue is often triggered after creating a new virtual switch for a VM. The manual workaround should only be needed once after that and does not affect the virtual switch.
Compatibility
WS4W has been tested and is known to work on Windows Server (2012 R2 and newer) and Windows Desktop (10 and newer).
Attribution
WireGuard is a registered trademark of Jason A. Donenfeld.
Icon made by Freepik from www.flaticon.com.
Время на прочтение6 мин
Количество просмотров61K
Подозреваю, что я не один такой, кто держит дома в режиме 24/7 маленький и тихий системный блок с Windows в качестве сервера, на который можно зайти по RDP (с того же смартфона) и несколько переживает в связи с количеством «неслучайных» попыток к нему подключиться. Задача не новая и вполне себе решаемая, например можно рассмотреть следующие варианты:
-
Настроить OpenSSH сервер, начиная с Windows 10 1809 он официально часть дистрибутива, включить авторизацию по ключам и заходить на RDP через SSH тоннель. На маршрутизаторе соответственно настроить перенаправление только для SSH порта. Из плюсов — достаточно безопасно, из минусов:
-
Не очень понятно, можно ли зайти со смартфона (для iPhone вероятно понадобится какой-то гибридный RDP клиент).
-
Поддерживается только TCP, а RDP уже довольно давно умеет использовать преимущества UDP.
-
Обновления Windows имеют необъяснимое свойство отключать OpenSSH, не знаю с чем это связано, но несколько за год раз такое было.
-
-
Настроить VPN непосредственно на маршрутизаторе. В целом, решение рабочее и минусы тут довольно субъективные:
-
Не хочется вешать на маршрутизатор дополнительную «необязательную» нагрузку.
-
Открывается дополнительный вектор атаки непосредственно на маршрутизатор.
-
Требует определенных технических навыков.
-
-
Дополнительно установить Raspberry Pi и на нем настроить VPN (можно ещё много чего на ней запустить). До сих пор пользуюсь, отличный вариант, если есть необходимые навыки и немного денег на «малинку».
-
Скорее для полноты картины, чем для реального домашнего использования, можно установить Hyper-V на нашу машинку с Windows, создать виртуальную машину с Linux и на нем настроить VPN. Как и в предыдущем случае:
-
Требует определенных технических навыков.
-
Увеличивается нагрузка на наш не особенно могучий домашний сервер (у меня это обычно Intel NUC) .
-
Могут возникнуть проблемы при отключении питания (виртуальная машина окажется в состоянии Saved и VPN будет недоступен).
-
-
Ну и наконец, можно установить сервер VPN непосредственно на Windows. Выбор конкретного VPN дело глубоко личное, но мне последние пару лет посчастливилось изрядно поработать с WireGuard и даже реализовать специализированного клиента для Wandera, в связи с этим выбор был очевиден.
Предварительные изыскания
Я думаю, это ни для кого не новость, что WireGuard уже больше года как включен в основную ветку ядра Linux. С Windows не все так радужно, однако в силу специфики протокола официальный WireGuard для Windows вполне себе выполняет функцию сервера, ему не хватает только NAT. Благодаря Henry Chang и его вдохновленному им micahmo примерно известно как сделать это стандартными средствами Windows. Честно говоря, процесс выглядит немного сложновато, хотя надо отдать должное micahmo, который его частично автоматизировал. Помимо этого, меня заинтересовал следующий комментарий под оригинальным постом:
Good day, excellent article!
I have a Win10 machine that I plan to use as a wireguard server. This machine has a main internet network adapter + OpenVPN client connection that is used for selected routes.
If I understand correctly described above wireguard VPN setup will only allow my wireguard clients to access main internet interface but not the OpenVPN connection, please correct me I’m wrong.
Is there a way for a wireguard client to use all available connections and honor existing routes configuration on wireguard server?Thank you!
Думаю, что полный перевод не требуется, суть состоит в том, чтобы WireGuard использовал для выхода не какой-то один определенный интерфейс (это единственный вариант с Windows Internet Connection Sharing), а тот из них который определен согласно действующей таблице маршрутизации.
Итак, сформулируем задачу
-
Максимально упростить процесс установки и настройки WireGuard. Давление на компании предоставляющие услуги VPN нарастает и, согласитесь, было бы неплохо, если бы любой пользователь Windows мог бы:
-
Настроить WireGuard на сервере расположенном облаке, не погружаясь в особенности реализации. Я не призываю к обходу блокировок уважаемого Роскомнадзора, но это так же может быть необходимо, чтобы обойти географические ограничения на какие-то продукты или услуги. Например, до недавнего времени, Ghidra нельзя было скачать с российского IP адреса. Сайт и сейчас вас не пустит, но сам дизассемблер можно скачать с Github. Или цена (валюта расчетов) на авиабилеты может варьироваться в зависимости от страны, с IP которой Вы зашли на сайт авиакомпании. Или можем вспомнить недавнюю историю с «неофициально» ввезенными телевизорами Samsung, у которых «неожиданно» отключилась функция Smart TV. Вернуть телевизор к нормальной жизни можно было только подключив его через европейский VPN. И это только то, что я сходу смог вспомнить…
-
Установить WireGuard на домашнем Windows сервере и получить постоянный защищенный доступ в собственную сеть и пользоваться ВСЕМИ сервисами доступными ему дома независимо от того в какой точке мира он находится. Например, понравилась мне Яндекс Станция (это не реклама, я действительно их довольно много приобрел для себя, для семьи, в подарки друзьям), да так, что я даже одну привез на Тенерифе. И тут выяснилась удивительная подробность, Яндекс-музыка работает за границей, а вот КиноПоиск ссылается на географические ограничения и отказывается работать. Было бы обидно, но настроил WireGuard клиента на роутере Keenetic и подключил Яндекс станцию через домашний VPN в России. А еще не так уж давно я проделывал что-то подобное для Amazon Fire Stick, чтобы нормально пользоваться подпиской Prime. Могу ошибаться, но кажется где-то читал, что и сам WireGuard был изначально придуман, чтобы смотреть американский Netflix из Австралии.
-
-
Использовать некую альтернативу Internet Connection Sharing со всем уважением к имеющейся сетевой конфигурации.
Примерно месяц назад у меня появилось 3-4 относительно свободных дня на неделе и я приступил к ее постепенной реализации. Как раз на днях закончил «боевую» сборку, которая в настоящее время успешно крутится на паре домашних машинок с Windows 10 Pro и на VPS в Microsoft Azure (Windows Server 2019 Core, 1vCPU + 1Gb) и которую нестыдно показать. Сразу должен отметить, что по производительности реализация в ядре безусловно выигрывает и если вам не составляет особенного труда сконфигурировать WireGuard на VPS с Linux, то это более оптимальный выбор. Моя целевая аудитория — это обычные пользователи Windows далекие от IT. Насколько могу судить, в текущей реализации самое сложное это настроить перенаправление UDP порта (на роутере или в панели управления виртуальной машиной в облаке).
WireSock Gateway
И с WireGuard созвучно и по смыслу подходит, к тому же, как удачно, домен wiresock.net оказался свободен. Инсталляторы и краткая инструкция по установке есть на сайте. В двух словах, кроме того, чтобы скачать и установить приложение, необходимо запустить ‘cmd’ с правами Администратора и выполнить ‘wg-quick-config -add -start’. wg-quick-config постарается определить внешний IP адрес и свободный локальный UDP порт, которые будут предложены по умолчанию. Если на маршрутизаторе настроен динамический DNS, то можно поменять IP на доменное имя. Если ISP/VPS провайдер выдает вам ‘белый» IPv4 адрес, то после этого достаточно настроить форвард на роутере для выбранного UDP порта. Виртуальная сеть для WinTun адаптера по умолчанию 10.9.0.0/24, но так же по желанию может быть изменена.
wg-quick-config создаст файлы конфигурации для сервера (wiresock.conf) и клиента (wsclient_1.conf), создаст и запустит WIreGuard туннель, а так же отобразит конфигурацию клиента в виде QR кода, который можно отсканировать смартфоном. Дополнительных клиентов можно добавлять, вызывая ‘wg-quick-config -add -restart’.
Основная работа выполняется сервисом Wiresock Service, который поддерживает два режима работы: NAT и Proxy.
Первый это классический NAT, сервис включает маршрутизацию (для некоторых типов соединений начиная с Windows 7 встроенная маршрутизация не работает, и они маршрутизируются «вручную»), определяет внешний интерфейс «по умолчанию» на котором и занимается подменой адресов во входящих/исходящих пакетах. Получает почти то же самое, что дает встроенный Internet Connection Sharing, но без ограничений на адреса клиентской сети.
Второй несколько интереснее и именно этот режим включается инсталлятором по умолчанию. Все TCP/UDP соединения (для UDP условно), кроме DNS и NTP, прозрачно перенаправляются на локальные TCP/UDP прокси, которые уже от своего имени устанавливают соединения к сетевым ресурсам. При этом если у локальной системы присутствуют системные настройки HTTP/SOCKSv5 прокси, то Wiresock Service со всем уважением будет их использовать. Что касается NTP и DNS, то они обрабатываются отдельно. Wiresock Service сам отвечает за NTP сервер, а для DNS запросы перенаправляются на локально сконфигурированные IPv4 DNS сервера, а если таковых по каким-то причинам не окажется, то используются 8.8.8.8 и 1.1.1.1. Единственный недостаток данного подхода — не будет работать ping на внешние адреса.
Таким образом, основные задачи вроде бы выполнены. И если к проекту будет интерес, то ему есть куда развиваться, например:
-
На данный момент (v.1.0.2.4) отсутствует поддержка IPv6.
-
«Белые» IPv4 постепенно становятся редкостью, поэтому хотелось бы организовать работу WireGuard сервера за NAT (или даже multi-NAT) Интернет-провайдера. Здесь правда без внешнего сервиса (с «белым» IP) обойтись не удастся.
Буду рад любым отзывам и замечаниям…
Сетевая безопасность и защита данных становятся все более важными аспектами работы любого предприятия. В связи с этим, многие компании и организации сегодня используют VPN-связь для защищенного доступа к сети. Wireguard — это одна из самых новых и инновационных технологий VPN, которая обеспечивает высокий уровень безопасности и производительности.
В данной статье мы рассмотрим, как настроить Wireguard на Windows Server 2008. Эта операционная система всё ещё широко используется во многих организациях, и многие администраторы сталкиваются с необходимостью настройки безопасной VPN-связи на этой платформе. В нашем руководстве представлено простое и понятное решение, которое позволяет быстро и легко настроить VPN-сервер на Windows Server 2008.
Wireguard является современным и эффективным протоколом VPN, который был разработан для обеспечения максимальной безопасности и производительности. Он использует современные алгоритмы шифрования и аутентификации данных, обеспечивая высокий уровень безопасности передачи информации. Кроме того, Wireguard является очень легким и быстрым, что делает его идеальным выбором для VPN-связи на Windows Server 2008.
Настройка Wireguard на Windows Server 2008 — это одна из самых эффективных и безопасных решений для настройки VPN-связи. Следуя нашему руководству, вы сможете создать защищенное и надежное соединение для передачи данных, что сделает вашу работу более эффективной и безопасной.
Установка и настройка Wireguard на Windows Server 2008
Шаг 1: Установка Wireguard на сервере
Сначала необходимо скачать и установить Wireguard на сервере Windows Server 2008. Для этого:
- Скачайте последнюю версию Wireguard для Windows Server 2008 с официального сайта.
- Запустите установочный файл и следуйте инструкциям мастера установки.
Шаг 2: Генерация ключей на сервере
После успешной установки необходимо сгенерировать ключи для сервера и клиентов. Для этого:
- Откройте командную строку или PowerShell на сервере.
- Перейдите в каталог установки Wireguard.
- Введите команду
wg genkey | tee privatekey | wg pubkey > publickeyдля генерации приватного и публичного ключей.
Шаг 3: Настройка конфигурации Wireguard
После генерации ключей необходимо настроить конфигурацию Wireguard на сервере. Для этого:
- Создайте новый файл с расширением .conf (например, wg0.conf) в каталоге конфигурации Wireguard.
- Откройте файл в текстовом редакторе и вставьте следующий шаблон конфигурации:
[Interface]PrivateKey = [приватный ключ сервера]Address = [IP-адрес и подсеть сервера][Peer]PublicKey = [публичный ключ клиента]AllowedIPs = [IP-адрес и подсеть клиента]
Вместо [приватного ключа сервера], [IP-адреса и подсети сервера], [публичного ключа клиента] и [IP-адреса и подсети клиента] нужно указать соответствующие значения.
Шаг 4: Запуск Wireguard
После настройки конфигурации Wireguard можно запустить его на сервере. Для этого:
- Сохраните файл конфигурации Wireguard.
- Откройте командную строку или PowerShell на сервере.
- Перейдите в каталог установки Wireguard.
- Введите команду
wg-quick up [имя файла конфигурации]для запуска Wireguard с указанным файлом конфигурации.
После выполнения всех этих шагов Wireguard должен успешно установиться и настроиться на Windows Server 2008. Теперь вы можете использовать безопасное VPN-соединение для связи между клиентами и сервером.
Мощное решение для создания безопасной VPN-связи
Wireguard на Windows Server 2008 предоставляет простое и эффективное решение для создания безопасной VPN-связи между различными устройствами и сетями. С его помощью вы сможете подключиться к вашей сети из любого места, обеспечивая максимальную безопасность и конфиденциальность передаваемых данных.
Одной из основных преимуществ Wireguard является его простота в использовании. С его установкой и настройкой справится даже пользователь, не имеющий большого опыта в работе с VPN-серверами. Вам не придется тратить много времени на прочтение длинных инструкций и изучение сложной документации.
Wireguard также обладает высокой производительностью и эффективностью. Он использует современные протоколы шифрования, обеспечивая высокую степень защиты передаваемых данных. Благодаря своей минималистичной архитектуре Wireguard имеет низкую нагрузку на ресурсы системы, что позволяет использовать его даже на слабых или старых серверах.
Другим важным преимуществом Wireguard является его кроссплатформенность. Он поддерживается на различных операционных системах, включая Windows, Linux, macOS, Android и iOS. Это позволяет подключаться к вашей VPN-сети с любого устройства, будь то компьютер, ноутбук, смартфон или планшет.
В заключение, Wireguard на Windows Server 2008 — это мощное решение для создания безопасной VPN-связи. Он обладает высоким уровнем безопасности, простотой использования и хорошей производительностью. Благодаря его кроссплатформенности, вы сможете подключаться к вашей VPN-сети с любого устройства. Не стоит откладывать на потом — начните использовать Wireguard уже сейчас и убедитесь в его эффективности!
Подготовка и установка необходимых компонентов
Для успешной настройки Wireguard на Windows Server 2008 необходимо выполнить следующие шаги:
- Установить ОС Windows Server 2008 на сервер.
- Проверить наличие обновлений и установить все доступные патчи и исправления.
- Установить необходимые компоненты для работы Wireguard:
| Компонент | Версия | Ссылка для скачивания |
|---|---|---|
| OpenSSL | 1.1.1 | https://www.openssl.org/source/ |
| Wireguard | 0.4.1 | https://www.wireguard.com/install/ |
После установки всех необходимых компонентов вы готовы приступить к настройке Wireguard на Windows Server 2008.
Шаги по установке Wireguard на Windows Server 2008
Для установки Wireguard на Windows Server 2008 вам понадобятся следующие шаги:
- Скачайте и установите последнюю версию Wireguard для Windows Server 2008 с официального сайта.
- Запустите установочный файл и следуйте инструкциям мастера установки.
- После установки откройте командную строку с правами администратора.
- Создайте директорию для хранения конфигурационных файлов Wireguard.
- Создайте конфигурационный файл Wireguard с необходимыми настройками, такими как IP-адрес сервера, порт и ключи.
- Скопируйте созданный конфигурационный файл в директорию Wireguard.
- Запустите Wireguard с помощью команды в командной строке:
wireguard.exe /installtunnelservice /configdir C:\путь\к\директории\wireguard - Проверьте, что Wireguard успешно запущен и работает на вашем сервере.
- Настройте клиентские устройства для подключения к Wireguard серверу с использованием сконфигурированных ключей и IP-адреса сервера.
После завершения этих шагов Wireguard будет успешно установлен и готов к использованию на Windows Server 2008.
Создание конфигурационного файла
Чтобы настроить и использовать Wireguard на Windows Server 2008, необходимо создать конфигурационный файл с необходимыми настройками.
1. Откройте текстовый редактор, такой как Notepad или Notepad++, чтобы создать новый файл.
2. Введите следующий текст в новый файл:
[Interface]PrivateKey = ваш_закрытый_ключAddress = ваш_виртуальный_IP/24DNS = 8.8.8.8[Peer]PublicKey = публичный_ключ_сервераAllowedIPs = 0.0.0.0/0Endpoint = IP_сервера:порт_сервераPersistentKeepalive = 25
3. Замените «ваш_закрытый_ключ» на ваш секретный ключ, который вы сгенерировали для клиента.
4. Замените «ваш_виртуальный_IP» на виртуальный IP-адрес, который вы хотите назначить клиенту.
5. Замените «публичный_ключ_сервера» на публичный ключ сервера, который вы получили при настройке сервера.
6. Замените «IP_сервера» на публичный IP-адрес вашего сервера.
7. Замените «порт_сервера» на порт, который вы настроили для Wireguard сервера.
8. Сохраните файл с расширением .conf, например, myconfig.conf.
В конфигурационном файле вы указываете приватный ключ и адрес для каждого клиента, а также публичный ключ, разрешенные IP-адреса и настройки сервера.
Теперь у вас есть конфигурационный файл Wireguard для использования на Windows Server 2008.
Простые инструкции по созданию и настройке конфигурационного файла
Для настройки Wireguard на Windows Server 2008 вам понадобится создать и настроить конфигурационный файл. В этом разделе мы расскажем, как это сделать.
Шаг 1: Откройте текстовый редактор, такой как Notepad, и создайте новый файл с расширением «.conf».
Шаг 2: Введите следующую информацию в ваш файл:
- Секция [Interface]:
-
- PrivateKey: Укажите ваш приватный ключ.
- Address: Укажите IP-адрес и префикс вашей Wireguard-сети (например, 10.0.0.1/24).
- ListenPort: Укажите порт, который будет слушать ваш сервер (например, 51820).
- Секция [Peer]:
-
- PublicKey: Укажите публичный ключ удаленного сервера.
- AllowedIPs: Укажите диапазон IP-адресов, которые маршрутизируются через VPN (например, 0.0.0.0/0).
- Endpoint: Укажите IP-адрес и порт удаленного сервера (например, example.com:51820).
Шаг 3: Сохраните файл и закройте его.
Теперь у вас есть готовый конфигурационный файл для вашего Wireguard-сервера на Windows Server 2008. Вы можете использовать этот файл для подключения удаленных клиентов к вашей защищенной VPN-сети.
Генерация ключей безопасности
Прежде чем настраивать Wireguard на Windows Server 2008, необходимо сгенерировать ключи безопасности для VPN-связи. Для этого выполните следующие шаги:
- Установите программу генерации ключей. Для генерации ключей without Wireguard на Windows Server 2008, вы можете использовать программа PuTTY Key Generator.
- Откройте программу PuTTY Key Generator. После установки запустите программу и вам откроется окно с настройками генерации ключей.
- Сгенерируйте приватный и публичный ключ. Нажмите кнопку «Generate», чтобы начать процесс генерации ключей. Программа будет использовать случайность вашего движения мышью для создания уникальных ключей.
- Сохраните ключи на вашем компьютере. После генерации ключей, вы должны сохранить приватный и публичный ключи в безопасном месте на вашем компьютере. Приватный ключ используется для авторизации на сервере, а публичный ключ будет использоваться на клиентской стороне для проверки подлинности сервера.
Теперь у вас есть сгенерированные ключи безопасности, которые вы можете использовать при настройке Wireguard на Windows Server 2008.
Как сгенерировать и использовать ключи безопасности в Wireguard
Для настройки безопасной VPN-связи с использованием протокола Wireguard необходимо сгенерировать и использовать ключи безопасности.
Для генерации ключей в Wireguard можно воспользоваться командой wg genkey. Эта команда сгенерирует приватный ключ, который необходимо сохранить себе.
После генерации приватного ключа необходимо сгенерировать соответствующий публичный ключ с помощью команды wg pubkey. Публичный ключ будет использоваться для обмена данными с другими устройствами в VPN-туннеле.
Полученные ключи можно использовать для настройки Wireguard на Windows Server 2008. Для этого необходимо указать приватный ключ в конфигурационном файле Wireguard на сервере, а публичный ключ указать на клиентском устройстве.
При использовании ключей в Wireguard следует учитывать следующие советы:
| 1. | Не передавайте приватный ключ третьим лицам. |
| 2. | Храните приватный ключ в надежном и безопасном месте. |
| 3. | Периодически меняйте ключи безопасности для повышения уровня безопасности. |
Следуя указанным рекомендациям, вы сможете генерировать и использовать ключи безопасности в Wireguard для безопасной VPN-связи на Windows Server 2008.
Организация VPN-соединения с другими устройствами
После настройки Wireguard на Windows Server 2008, можно организовать VPN-соединение с другими устройствами. Для этого необходимо выполнить следующие шаги:
1. Создание конфигурационного файла:
На Windows Server 2008 запустите Wireguard и создайте новую конфигурацию, указав имя и адрес сервера.
2. Добавление клиентских устройств:
На сервере Wireguard создайте клиентские конфигурационные файлы с использованием команды «wg genkey | tee privatekey | wg pubkey > publickey». Передайте клиенту файл с приватным ключом (privatekey) и сохраните приватный ключ клиента на сервере.
3. Установка Wireguard на клиентских устройствах:
На клиентских устройствах, например, на компьютерах и мобильных устройствах, установите Wireguard и создайте новую конфигурацию, указав IP-адрес и публичный ключ сервера.
4. Установка IP-адресов и добавление правил маршрутизации:
Настройте IP-адреса для сервера и клиентских устройств, добавив правила маршрутизации для перенаправления трафика через VPN-туннель.
5. Установка защиты соединения:
Настройте параметры шифрования и аутентификации для обеспечения безопасности VPN-соединения. Используйте алгоритмы шифрования и аутентификации, рекомендуемые Wireguard.
После выполнения всех этих шагов, VPN-соединение будет успешно организовано между Windows Server 2008 и другими устройствами.
This tutorial goes through the process of setting up a Wireguard server on Windows. Most Wireguard tutorials on the internet only give you the choice of hosting a server in a Linux environment. However, it is very possible to setup a windows server.
After searching for a tutorial to no avail, I spent a couple days to figure out the best way to do it and how to automate the process. Ideally you would still want to run it in an Linux environment, but if you have a use case for a windows server like me, you would appreciate just how flexible Wireguard is!
Prerequisite
- Latest Wireguard Windows Client installed (Download here from official site)
- Setup firewall rules (just as you would for a Linux server setup: open and forward ports 51820, configure ddns etc)
Disclaimer: Using Wireguard on Windows as server is not officially supported. Use at your own risk.
Step 1: Prepare Wireguard Server and Client Config File
This step is the same as other Linux tutorials. I’ve provided my own server side and client side configs below, adjust to your own use case.
#Server Config
[Interface]
PrivateKey = #Replace with server private key#
ListenPort = 51820
Address = 192.168.200.1/24
[Peer]
#Client 1
PublicKey = #Replace with client public key#
PresharedKey = #Replace with pre-shared key#
AllowedIPs = 192.168.200.2/32
#Client Config
[Interface]
PrivateKey = #Replace with client private key#
Address = 192.168.200.2/24
DNS = 1.1.1.1, 8.8.8.8
[Peer]
PublicKey = #Replace with server public key#
PresharedKey = #Replace with pre-shared key#
AllowedIPs = 0.0.0.0/0
Endpoint = #Replace with server domain name or ip address#:51820
After you prepared the server config files, place it in a folder somewhere permanent. For this tutorial I will assume the server config file is placed at C:\wireguard\wg_server.conf
Step 2: Start up the server
Instead of using the GUI to start the server, we will start it using command options. At the time of this tutorial the official GUI only allows one connection at a time. If we use it to run the server, the GUI will be occupied and we won’t be able to make a new connection without dropping the server interface. Running the server using command line options allows us the keep the GUI free for daily use. If you don’t mind the GUI being occupied, you can just start the server on the GUI and skip to Step 3.
Use the following code to start / stop the server. Without saying, adjust the file paths if they are different on your system.
You need to run these with administrative privilege!
#Start server
C:\Program Files\WireGuard\wireguard.exe /installtunnelservice "C:\wireguard\wg_server.conf"
#Stop server
C:\Program Files\WireGuard\wireguard.exe /uninstalltunnelservice wg_server
You will only need to run the command once, wireguard’s background service will remember the run state over reboots. Once you start the server, wireguard will create a new network adapter as the same name as your server config file. Thus for our tutorial, the network adapter name would be “wg_server” Check if the network adapter is successfully created.
Step 2.1: (Optional) Setting adapter profile
Now we have the wireguard adapter setup, it is recommended to change it to “Private” profile”, by defaults the adapter is added as “Public”. Private profile will allow greater compatibility for the clients (say you want to use some remote desktop etc.). Public profile may block these ports and services.
To Do this we run three simple PowerShell commands with admin privilege manually:
#Open powershell with admin privilege and run the following:
$NetworkProfile = Get-NetConnectionProfile -InterfaceAlias "wg_server"
$NetworkProfile.NetworkCategory = "Private"
Set-NetConnectionProfile -InputObject $NetworkProfile
Step 3: Enable server routing
Now that server is running, the client should be able to handshake (given that you have the correct ports open and forwarded correctly). However, you will notice the client won’t be able to access either the internet or the LAN network. This is because by default windows do not bridge or NAT the wireguard interface with your actual physical internet interface. In Linux this is done by some PostUp/PostDown firewall commands, which we do not use here. Instead, we use a PowerShell script to enable the NAT (or in Windows term “internet sharing”) function:
Function Set-NetConnectionSharing
{
Param
(
[Parameter(Mandatory=$true)]
[string]
$LocalConnection,
[Parameter(Mandatory=$true)]
[bool]
$Enabled
)
Begin
{
$netShare = $null
try
{
# Create a NetSharingManager object
$netShare = New-Object -ComObject HNetCfg.HNetShare
}
catch
{
# Register the HNetCfg library (once)
regsvr32 /s hnetcfg.dll
# Create a NetSharingManager object
$netShare = New-Object -ComObject HNetCfg.HNetShare
}
}
Process
{
#Clear Existing Share
$oldConnections = $netShare.EnumEveryConnection |? { $netShare.INetSharingConfigurationForINetConnection.Invoke($_).SharingEnabled -eq $true}
foreach($oldShared in $oldConnections)
{
$oldConfig = $netShare.INetSharingConfigurationForINetConnection.Invoke($oldShared)
$oldConfig.DisableSharing()
}
# Find connections
$InternetConnection = Get-NetRoute | ? DestinationPrefix -eq '0.0.0.0/0' | Get-NetIPInterface | Where ConnectionState -eq 'Connected'
$publicConnection = $netShare.EnumEveryConnection |? { $netShare.NetConnectionProps.Invoke($_).Name -eq $InternetConnection.InterfaceAlias }
$privateConnection = $netShare.EnumEveryConnection |? { $netShare.NetConnectionProps.Invoke($_).Name -eq $LocalConnection }
# Get sharing configuration
$publicConfig = $netShare.INetSharingConfigurationForINetConnection.Invoke($publicConnection)
$privateConfig = $netShare.INetSharingConfigurationForINetConnection.Invoke($privateConnection)
if ($Enabled)
{
$publicConfig.EnableSharing(0)
$privateConfig.EnableSharing(1)
}
else
{
$publicConfig.DisableSharing()
$privateConfig.DisableSharing()
}
}
}
Note: The shell script is originally created by igoravl, I made some modification to simplify the process and get rid of some errors for our wireguard server application.
This shell script is written as a custom function “Set-NetConnectionSharing” and needs to be loaded in PowerShell.
Save the script in the following location:
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\wireguard\wireguard.psm1
wireguard.psm1 needs to be in a folder named wireguard for the function to be loaded by powershell
Now you can open a PowerShell window with administrative privilege and run the following commands to enable / disable NAT for our wireguard server interface.
#"wg_server" is the wireguard adapter name, replace it if you have something different.
#Enable NAT
Set-NetConnectionSharing "wg_server" $true
#Disable NAT
Set-NetConnectionSharing "wg_server" $false
If everything goes well, when you open the properties panel of your main internet network adaptor (Ethernet 3 in my case) the following options should be ticked:
Notice also the “Home networking connection” field should be populated with your wireguard interface name (picture shows Wireguar_Server but should be wg_server if you are following the tutorial).
Technically you can do this through the windows gui using the properties menu manually, but having this script will allow you to automate the server start/stop process as you will see later on in the tutorial.
Now everything should be working correctly, the client should be able to reach the internet and LAN network you allow it to.
Step 3.1: Change default Internet Connection Sharing IP
By default, when internet sharing (NAT) is enabled, Windows will change the IP address of the adapter to something else (to avoid conflicts). However, we already know what IP address we want to adapter to be (set in the [interface] block in our wireguard config), which is 192.168.200.1 in our case.
To modify the default IP Windows will switch to, we can simply change the setting in registry. Open Registry Editor and go to the following path:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\SharedAccess\Parameters
Then simply change ScopeAddress and ScopeAddressBackup to the IP address we desire (192.168.200.1 in our case).
Disable and re-enable Internet connection sharing (NAT) using the powershell command in Step 3 to make sure this change takes place (you might need to restart computer).
Step 4: Enable persistent Internet Sharing on restart (updated 2/12/2020)
Since there is a windows bug that internet connection sharing will not auto start on reboot, we need to change a few settings to make sure internet sharing is started. The earlier tutorial used a scheduled task to accomplish this, but I’ve found a better way after reading the windows bug fix here.
Open the Service window and find “Internet Connection Sharing”:
Chang the startup type to “Automatic”:
After that’s done, finally we add a registry:
Path: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\SharedAccess
Type: DWORD (32bit)
Setting: EnableRebootPersistConnection
Value: 1
Step 4.1 (optional) Bat files to easily start / stop server manually
For convenience I also made two bat files to run these commands so I don’t have to open command prompt or PowerShell every time to start and stop the server.
Server start batch script: (save as “start.bat” and run with admin privilege)
@echo off
"C:\Program Files\WireGuard\wireguard.exe" /installtunnelservice "C:\Henry-Scripts\Wireguard_Server.conf"
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" Set-NetConnectionSharing "Wireguard_Server" $true
Server stop batch script: (save as “stop.bat” and run with admin privilege)
@echo off
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" Set-NetConnectionSharing "Wireguard_Server" $false
"C:\Program Files\WireGuard\wireguard.exe" /uninstalltunnelservice Wireguard_Server
Final Remarks:
Compared to Linux, setting up a windows wireguard server can be tricky. However, I have done most of the ground work for you (the PowerShell script to enable NAT). Running the PowerShell script on startup with 3 minutes delay is not elegant, but it works. There should be a way to run the task after the wireguard service is started and running, but I wasn’t able to get it to work. If you know how to get it to work, please share it with me.
