Change profile windows firewall

Windows Firewall Profiles

When authoring your firewall rules it is best to only plumb your firewall rules to profiles that are appropriate for your scenarios and to modify your rules according to each specific profile.

Windows Firewall offers three firewall profiles: domain, private and public. The domain profile applies to networks where the host system can authenticate to a domain controller. The private profile is a user-assigned profile and is used to designate private or home networks. Lastly, the default profile is the public profile, which is used to designate public networks such as Wi-Fi hotspots at coffee shops, airports, and other locations.

Windows Firewall provides public APIs which can be used to acquire the current profile and to enable firewall rule groups on specific profiles. These APIs should be utilized by all installers to provide the best user experience and seamless integration.

Best practices are to create your rules in all three profiles, but only enable the firewall rule group on the profiles that suit your scenarios. For example, if you are installing a home media sharing application that is only used on a private network then it would be best to create firewall rules in all three profiles, but only enable the firewall rule group containing your rules on the private profile.

If the current profile is not one of the profiles which apply to your scenarios, then inform the user that your firewall rules are not enabled in the current profile. You should also inform the user that the application will not function as expected unless the user moves to a network which has one of the profiles that applies to your scenario or re-categorizes the current network.

Enabling rules that have been created in the public profile by default is not recommended.

Windows Firewall Profiles — Restrictions per Profile

You may also wish to modify the restrictions on your firewall rules depending on which profile the rules are applied to. For applications and services that are designed to only be accessed by devices or other computers within a home or small business network, it is best to modify the remote address restriction to specify «Local Subnet» only. The same application or service would not have this restriction when used in an enterprise environment. This can be done by adding the remote address restriction to rules that are added to the private and public profiles, while leaving them unrestricted in the domain profile. This remote address restriction should not apply to applications or services that require global Internet connectivity.

How to Change a Network Location from Public to Private on Windows 10/Windows Server 2016?

In this article, we will consider the concept of a network profile in Windows, consider what types of network profiles are, what they are used for and how to change the assigned network profile from Public to Private or vice versa in Windows 10 and Windows Server 2019/2016. This is necessary if the network location is mistakenly detected as Public Network, when it should be Private.

Windows network profiles are a part of the Windows Defender Firewall with Advanced Security and allow you to apply different firewall rules depending on the type of network the computer is connected to. Depending on the profile used for your network connection, other computers may or may not see your computer on the network (network discovery settings), use shared network folders and printers.

Читайте также:  Не запускается служба dhcp windows

What is a Network Location (Profile) in Windows?

Network profiles firstly appeared in Vista/Windows Server 2008. In Windows 10 (Windows Server 2016), you can assign one of the following network security profiles (locations) for your NIC (network interface card), whether Ethernet or Wi-Fi:

  • Private or Home network – a profile for a trusted network (home or office networks). In such a network, the computer will be available for discovery by other devices; you can share your files and printers.
  • Public network – a profile for an untrusted network (public Wi-Fi network in the subway, cafe, airport). You don’t trust other devices on such a network, your computer will be hidden to other network devices, no one will be able to access shared network folders and printers on your computer;
  • Domain network – a profile for computers that are members of an Active Directory domain. Applies automatically after joining Windows to the AD domain. You can apply domain firewall policies for this profile.

The Network Location Awareness (NLA) service is used by Windows to determine if a network connection is on a Public, Private, or Domain network.

As mentioned earlier, different Windows Firewall rules apply to your network connection based on the network profile of your NIC.

In Windows 10, you can check the current network profile (location) assigned to the network connection in the Settings -> Network & Internet. In my screenshot, you can see that the Open (Public) profile is assigned to the Ethernet0 NIC.

In the classic Control Panel, the network type for active network connections is displayed here: Control Panel -> All Control Panel Items -> Network and Sharing Center. But you cannot change the assigned network location from the classic Control Panel. For example, in Windows Server 2012 R2 / Windows 8.1, you can only change the network profile through the PowerShell, registry, or local security policy (described below).

How to Set a Network Profile in Windows 10?

The network profile in Windows 10 is selected by the user when the device connected to the new network for the first time. A prompt appears:

If you select “Yes”, the Private profile will be assigned to the network, or the Public profile if you select “No”. The next time you connect to the same LAN or WiFi network, the previously selected profile is automatically assigned.

You can hide “Network Location Wizard” when connecting to a new network through the registry. Just create an empty registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Network\NewNetworkWindowOff. After that, all networks are considered Public.

You can reset all settings and profiles for saved networks in Windows 10 by selecting Settings -> Network & Internet -> Status -> Network Reset and reboot the computer.

Now when you connected to the network, a network discovery request appears again.

How to Change Windows 10 Network Location from Public to Private?

You can change the network profile from the Windows 10 GUI. If you are using the new Settings panel, go to “Network & Internet” -> “Status” -> “Change connection properties”.

Here you can switch the network location profile from Public to Private and vice versa.

You cannot change the network profile from the classic Control Panel in Windows 10.

Also, you cannot change the network profile on the domain-joined computer. The Domain profile will always be used for a domain network connection.

Change Network Types Using PowerShell in Windows 10

On Windows 10/Windows Server 2016/2019, you can manage network connection location from the PowerShell. Run the elevated PowerShell console.

Now use the Get-NetConnectionProfile cmdlet to get a list of network adapters on your computer and their associated network profiles.

In my example, there is only one physical network adapter on a computer with a Public network location type (in the NetworkCategory value, you can see the following types of network profiles: Public, Private or DomainAuthenticated).

Читайте также:  Веб агент для windows

Let’s try to change the assigned network profile for the NIC. We need to get the index assigned to this network card. In this example, InterfaceIndex is 8.

After you get the network adapter index, you can change the network type to Private:

Set-NetConnectionProfile -InterfaceIndex 8 -NetworkCategory Private

Check that the network profile has changed:

Get-NetConnectionProfile -InterfaceIndex 19

The new firewall rules will be applied to the interface according to the assigned network profile without rebooting.

You can also change the network profile for all network adapters of the computer at once:

Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private

Setting Network Type Using Windows Registry

The network type can also be changed from the Registry Editor. To do this, run regedit.exe and go to the following key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles. This registry key contains profiles of all network connections.

You can find the necessary network profile by its name listed (from the Network and Sharing Center) in the ProfileName registry parameter.

The network type is specified in the Category parameter. The following values are available:

  • 0 — Public Network
  • 1 — Private Network
  • 2 — Domain Network

Change the key value to the one you need and restart your computer.

Настройка правил брандмауэра Windows групповыми политиками

Брандмауэр Windows позволяет ограничить исходящий / входящий сетевой трафик для определенного приложения или TCP/IP порта, и является популярным средством ограничения сетевого доступа к (от) рабочим станциям пользователей или серверам. Правила Windows Firewall можно настроить индивидуально на каждом компьютере, или, если компьютер пользователя включен в домен Windows, администратор может управлять настройками и правилами брандмауэра Windows с помощью групповых политик.

В крупных организация правила фильтрации портов обычно выносятся на уровень маршрутизатором, L3 коммутаторов или выделенных межсетевых экранах. Однако ничего не мешает вам распространить ваши правила ограничения сетевого доступа Windows Firewall к рабочим станциям или серверам Windows.

Групповые политики, использующиеся для управления настройками Брандмауэра Защитника Windows

С помощью редактора доменной групповой политики (group Policy Management Console – gpmc.msc) создайте новую политику с именем Firewall-Policy и перейдите в режим редактирования (Edit).

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

  • Computer Configuration -> Administrative Templates -> Network -> Network Connections -> Windows Firewall – эта секция GPO использовалась для настройки правил брандмауэра для ОС Vista / Windows Server 2008 и ниже. Если у вас в домене нет компьютеров со старыми ОС, для настройки файервола используется следующая секция.
    Network -> Network Connections -> Windows Firewall » width=»609″ height=»276″ srcset=»https://winitpro.ru/wp-content/uploads/2018/12/administrative-templates-greater-network-greater-network-con.png 968w, https://winitpro.ru/wp-content/uploads/2018/12/administrative-templates-greater-network-greater-network-con-300×136.png 300w, https://winitpro.ru/wp-content/uploads/2018/12/administrative-templates-greater-network-greater-network-con-768×348.png 768w» sizes=»(max-width: 609px) 100vw, 609px»/>
  • Computer Configuration -> Windows Settings -> Security Settings -> Windows Firewall with Advanced Security – это актуальный раздел для настройки Брандмауэра Windows в современных версиях ОС и по интерфейсу он напоминает интерфейс локальной консоли управления Брандмауэра.

Включаем Windows Firewall с помощью GPO

Чтобы пользователи (даже с правами локального админа) не могли выключить службу брандмауэра, желательно настроить автоматический запуск службы Windows Firewall через GPO. Для этого перейдите в раздел Computer Configuration- > Windows Settings -> Security Settings -> System Services. Найдите в списке служб Windows Firewall и измените тип запуск службы на автоматический (Define this policy setting -> Service startup mode Automatic). Убедитесь, что у пользователей нет прав на остановку службы.

Перейдите в раздел консоли GPO Computer Configuration -> Windows Settings -> Security Settings. Щелкните ПКМ по Windows Firewall with Advanced Security и откройте свойства.

На всех трех вкладках Domain Profile, Private Profile и Public Profile (что такое профиль сети) измените состояние Firewall state на On (recommended). В зависимости от политик безопасности в вашей организации вы можете указать, что все входящие подключения по умолчанию запрещены(Inbound connections -> Block), а исходящие разрешены (Outbound connections -> Allow) и сохраните изменения.

Создаем правило файервола с помощью групповой политики

Теперь попробуем создать разрешающее входящее правило файервола для всех. Например, мы хотим разрешить подключение к компьютерам по RDP (порт TCP 3389). Щелкните ПКМ по разделу Inbound Rules и выберите пункт меню New Rule.

Читайте также:  Стиль разделов guid установка windows 10

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

Выберите тип правила. Можно разрешить доступ для:

  • Программы (Program) – можно выбрать исполняемый exe программы;
  • Порта (Port) – выбрать TCP/UDP порт или диапазон портов;
  • Преднастроенное правило (Predefined) – выбрать одно из стандартных правил Windows, в которых уже имеются правила доступа (описаны как исполняемые файлы, так и порты) к типовым службам (например, AD, Http, DFS, BranchCache, удаленная перезагрузка, SNMP, KMS и т.д.);
  • Собственное правило (Custom) – здесь можно указать программу, протокол (другие протоколы помимо TCP и UDP, например, ICMP, GRE, L2TP, IGMP и т.д.), IP адреса клиентов или целые IP подсети.

В нашем случае мы выберем правило Port. В качестве протокола укажем TCP, в качестве порта – порт 3389 (RDP порт по-умолчанию, можно изменить).

Далее нужно выбрать что нужно сделать с таким сетевым соединением: разрешить (Allow the connection), разрешить если оно безопасное или заблокировать (Block the connection).

Осталось выбрать профили файервола, которым нужно применить правило. Можно оставить все профили (Domain, Private и Public).

На последнем шаге нужно указать имя правило и его описание. Нажмите кнопку Finish и оно появится в списке правил брандмауэра.

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

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

Теперь осталось назначить политику Firewall-Policy на OU с компьютерами пользователей

Проверка политик брандмаэера Windows на клиентах

Обновите политики на клиентах (gpupdate /force). Проверьте, что указанные вами порты доступны на компьютерах пользователей (можно использовать командлет Test-NetConnection или утилиту Portqry).

На ПК пользователя откройте Панель управления\Система и безопасность\Брандмауэр Защитника Windows и убедитесь, что появилась надпись: Для обеспечения безопасности, некоторые параметры управляются групповой политикой (For your security, some settings are controlled by Group Policy), и используются заданные вами настройки брандмаэера.

Пользователь теперь не может изменить настройки брандмауэра, а в списке Inbound Rules должны быть указаны все созданные вами правила.

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

netsh firewall show state

Импорт / экспорт правил Брандмауэра Windows в GPO

Конечно, процесс создания правил для брандмауэра Windows – очень кропотливое и долгое занятие (но результате того стоит). Для упрощения свое задачи можно воспользоваться возможностью импорт и экспорта настроек брандмауэра Windows. Для этого вам достаточно нужным образом настроить локальные правила брандмауэра на обычном рабочей станции. Затем встаньте на корень оснастки брандмауэра (Монитор Брандмауэра Защитника Windows в режиме повышенной безопасности) и выберите пункт Действие -> Экспорт политики.

Политика выгружается в WFW файл, который можно импортировать в редакторе Group Policy Management Editor, выбрав пункт Import Policy и указав путь к файлу wfw (текущие настройки будут перезаписаны).

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

В зависимости от того, хотите ли вы, чтобы локальные администраторы могли создавать на своих компьютерах собственные правила брандмауэра и эти должны быть объединены с правилами, полученными с помощью групповой политики. в групповой политике вы можете выбрать режим объединения правил. Откройте свойства политики и обратите внимание на настройки в разделе Rule merging. По умолчанию режим объединения правил включен. Вы можете принудительно указать, что локальный администратор может создавать собственные правила брандмауэра: в параметре Apply local firewall rules выберите Yes (default).

Несколько советов об управлении брандмауэром Windows через GPO

Конечно, для серверов и рабочих станций нужно создавать отдельные политики управления правилами брандмауэра (для каждой группы одинаковых серверов возможно придется создать собственные политики в зависимости от их роли). Т.е. правила файервола для контроллера домена, почтового Exchange сервера и сервера SQL будут отличаться.

Какие порты нужно открыть для той или иной службы нужно искать в документации на сайте разработчика. Процесс довольно кропотливый и на первый взгляд сложный. Но постепенно вполне реальной придти к работоспособной конфигурации Windows файервола, который разрешает только одобренные подключения и блокирует все остальное. По опыту хочу отметить, что на ПО Microsoft можно довольно быстро найти список используемых TCP/UDP портов.

Оцените статью