Управление брандмауэром windows 10 через powershell

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

Содержание:

  • Как включить и отключить Windows Defender Firewall через PowerShell?
  • Создать новое правило Windows Firewall
  • Изменить правило Windows Firewall с помощью PowerShell
  • Включить/отключить правило Windows Defender Firewall
  • PowerShell: вывести список активных правил Windows Firewall

Для управления настройками Windows Firewall обычно используется отдельная графическая MMC оснастка
wf.msc
(Control Panel -> System and Security -> Windows Defender Firewall -> Advanced settings). Большинство операций по настройке и управлению параметрами Windows Firewall можно выполнять из командной строки PowerShell. Для этого, начиная с версии Windows PowerShell 5.1, можно использовать встроенный модуль NetSecurity

Полный список командетов в модуле NetSecurity можно вывести с помощью команды:

Get-Command -Module NetSecurity

модуль NetSecurity для управления Windows Defender Firewall из PowerShell

Раньше для управления правилами и настройками Брандмауэра Windows использовалась команда
netsh advfirewall firewall
.

Как включить и отключить Windows Defender Firewall через PowerShell?

По умолчанию Defender Firewall в Windows включен.

Get-NetFirewallProfile | Format-Table Name, Enabled

отключить windows firewall с помощью powershell

Как вы видите, в Windows Firewall есть три типа сетевых профилей:

  • Domain (Доменный) – применяется к компьютерам, включенным в домен Active Directory;
  • Private (Частный) – домашние или рабочие сети;
  • Public (Общий) – общедоступные сети.

В настройках профилей по-умолчанию разрешены все исходящие подключения и блокируется входящие (кроме разрешенных).

windows defender firewall включен в windows

Информация о типах сетей хранится службой Network Location Awareness (NLA) в базе данных. Вы можете изменить профиль сети в Windows, если он определился некорректно.

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

Чтобы полностью отключить Firewall в Windows, выполните команду:

Set-NetFirewallProfile -All -Enabled False

Либо укажите конкретный профиль вместо All:

Set-NetFirewallProfile -Profile Public -Enabled False

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

Set-NetFirewallProfile -All -Enabled True

Вывести тип профиля, который применяется к сетевому подключению:

Get-NetConnectionProfile

В этом примере к сетевому подключению Ethernet0 применяется доменный профиль (DomainAuthenticated).

Вы можете управлять правилами Windows Firewall на удаленных компьютерах, если на них настроен PowerShell Remoting (WinRM). В этом примере с помощью командлета Invoke-Command мы отключим файервол на удаленных компьютерах из списка:

$computers = @('PC01', 'PC02', 'PC03')
Invoke-Command -ComputerName $computers {Set-NetFirewallProfile -All -Enabled False}

Можно изменить действие по-умолчнию для профиля Public и заблокировать все входящие подключения.

Set-NetFirewallProfile –Name Public –DefaultInboundAction Block

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

Get-NetFirewallProfile -Name Public

настройки по умолчанию для public профиля Windows Firewall

Если вы управляете настройками Windows Firewall через GPO, вы можете вывести текущие результирующие настройки профилей так:

Get-NetFirewallProfile -policystore activestore

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

Get-NetFirewallProfile -Name Public | fl DisabledInterfaceAliases

Если все интерфейсы защищены, команда должна вернуть:

DisabledInterfaceAliases : {NotConfigured}

Get-NetFirewallProfile

Можно отключить определенный профиль для интерфейса (вывести список имен интерфейсов можно с помощью командлета Get-NetIPInterface).

Set-NetFirewallProfile -Name Public -DisabledInterfaceAliases "Ethernet0"

Как вы видите, теперь профиль Public не применяется к интерфейсу Ethernet0:

DisabledInterfaceAliases : {Ethernet0}

Set-NetFirewallProfile - изсенить настройки профиля Firewall

С помощью командлета
Set-NetFirewallProfile
вы можете изменить параметры профиля (действие по-умолчанию, журналирование, путь и размер лог файла, настройки оповещений и т.д.).

Вы можете настроить параметры логирования сетевых подключений на уровне каждого профиля. По умолчанию журналы Windows Firewall хранятся в каталоге
%systemroot%\system32\LogFiles\Firewall
, размер файла – 4 Мб. Вы можете изменить включить журналирование подключений и увеличить максимальный размер файла:

Set-NetFireWallProfile -Profile Domain -LogBlocked True -LogMaxSize 20000 -LogFileName ‘%systemroot%\system32\LogFiles\Firewall\pfirewall.log’

Создать новое правило Windows Firewall

Для управления правилами брандмауэра используются 9 командлетов:

  • New-NetFirewallRule
  • Copy-NetFirewallRule
  • Disable-NetFirewallRule
  • Enable-NetFirewallRule
  • Get-NetFirewallRule
  • Remove-NetFirewallRule
  • Rename-NetFirewallRule
  • Set-NetFirewallRule
  • Show-NetFirewallRule

Рассмотрим несколько простых примеров открытия портов в Windows Firewall.

Например, вы хотите разрешить входящие TCP подключения на порты 80 и 443 для профилей Domain и Private. Воспользуйтесь такой командой:

New-NetFirewallRule -DisplayName 'WEB-Inbound' -Profile @('Domain', 'Private') -Direction Inbound -Action Allow -Protocol TCP -LocalPort @('80', '443')

New-NetFirewallRule - создать новое правило Windows Firewall с помощью PowerShell

Вы можете разрешить или заблокировать трафик для конкретной программы. Например, вы хотите заблокировать исходящие соединения для FireFox:

New-NetFirewallRule -Program “C:\Program Files (x86)\Mozilla Firefox\firefox.exe” -Action Block -Profile Domain, Private -DisplayName “Block Firefox” -Description “Block Firefox” -Direction Outbound

Разрешим входящее RDP подключение по стандартному порту TCP\3389 только с одного IP адреса:

New-NetFirewallRule -DisplayName "AllowRDP" –RemoteAddress 192.168.1.55 -Direction Inbound -Protocol TCP –LocalPort 3389 -Action Allow

Чтобы разрешить ICMP ping для адресов из указанных диапазонов IP адресов и подсети, используйте команды:

$ips = @("192.168.1.50-192.168.1.60", "192.165.2.22-192.168.2.200", ”10.10.0.0/16”)

New-NetFirewallRule -DisplayName "Allow inbound ICMPv4" -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -RemoteAddress $ips -Action Allow

New-NetFirewallRule -DisplayName "Allow inbound ICMPv6" -Direction Inbound -Protocol ICMPv6 -IcmpType 8 -RemoteAddress $ips -Action Allow

Добавить в правило файервола список IP адресов из текстового файла (по одному IP в строке):

$ips=Get-Content C:\temp\ip.txt
Get-NetFirewallrule -DisplayName 'AllowRDP'|Set-NetFirewallRule -RemoteAddress $ips

В предыдущей статье мы показывали как с помощью PowerShell можно заблокировать доступ к сайтам не только по IP адресу, но и по DNS имени домена/сайта.

Разрешить все входящие подключения с указанного IP адреса (добавить адрес в белый список):

$IP = '192.168.1.20'
New-NetFirewallRule -DisplayName "Allow $IP" -Direction Inbound -Action Allow -RemoteAddress $IP

Изменить правило Windows Firewall с помощью PowerShell

Чтобы отредактировать правило брандмауэра, используется командлет Set-NetFirewallRule. Например, вы хотите разрешить входящие подключения с указанного IP адреса для ранее созданного правила:

Get-NetFirewallrule -DisplayName 'WEB-Inbound' | Get-NetFirewallAddressFilter | Set-NetFirewallAddressFilter -RemoteAddress 192.168.1.20

Если нужно добавить в правило файервола несколько IP адресов, используйте такой скрипт:

$ips = @("192.168.1.50", "192.165.2.22",”192.168.1.21”)
$current_ips = (Get-NetFirewallRule -DisplayName 'WEB-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$current_ips += $ips
Get-NetFirewallrule -DisplayName 'WEB-Inbound'|Set-NetFirewallRule -RemoteAddress $current_ips

Вывести все IP адреса, которые содержатся в правиле брандмауэра:

(Get-NetFirewallrule -DisplayName 'Web-Inbound'|Get-NetFirewallAddressFilter).remoteaddress

Удалить один IP адрес из правила:

$removeip = "192.168.1.21"
$current_ips = (Get-NetFirewallRule -DisplayName 'WEB-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$filterIP = $current_ips | Where-Object{ $_ -notin $removeip }
Get-NetFirewallrule -DisplayName 'WEB-Inbound'|Set-NetFirewallRule -RemoteAddress $filterIP

powershell: добавить ip адрес в правило firewall

Включить/отключить правило Windows Defender Firewall

Вы можете включать/отключать правила файервола с помощью командлетов Disable-NetFirewallRule и Enable-NetFirewallRule.

Disable-NetFirewallRule –DisplayName 'WEB-Inbound'

Чтобы разрешить ICMP (ping), выполните команду:

Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In

Чтобы удалить правило брандмауэре используется командлет Remove-NetFirewallRule.

Remove-NetFirewallRule -DisplayName 'WEB-Inbound'

Чтобы сбросить все правила Microsoft Defender Firewall и восстановить настройки по умолчанию, выполните команду:

netsh advfirewall reset

или

(New-Object -ComObject HNetCfg.FwPolicy2).RestoreLocalFirewallDefaults()

Это очистит все пользовательские настройки и правила Microsoft Defender Firewall. В списке правил останутся только стандартные правила сетевого доступа Windows.

Перед сбросом можно экспортировать текущие настройки в файл.

netsh advfirewall export "C:\Backup\firewall-config.wfw"

В дальнейшем вы можете вернуть старые настройки файервола, импортировав файл с правилами:

netsh advfirewall import "C:\Backup\firewall-config.wfw"

PowerShell: вывести список активных правил Windows Firewall

Список активных правил для входящего трафика можно вывести так:

Get-NetFirewallRule | where {($_.enabled -eq $True) -and ($_.Direction -eq "Inbound")} |ft

Если, например, нам нужно вывести список блокирующих исходящих правил:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound

Если нужно отобразить имя программы в правиле:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound | %{$_.Name; $_ | Get-NetFirewallApplicationFilter}

Get-NetFirewallRule вывод правил Windows Firewall

Как вы видите командлет Get-NetFirewallRule не выводит порты сетевые порты и IP адреса для правил брандмауэра. Чтобы вывести всю информацию о разрешенных входящих (исходящих) подключениях в более удобном виде с отображением номеров портов, используйте такой скрипт:

Get-NetFirewallRule -Action Allow -Enabled True -Direction Inbound |
Format-Table -Property Name,
@{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},
@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}},
@{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},
@{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},
Enabled,Profile,Direction,Action

Get-NetFirewallRule вывести IP адрес и имя порта

PowerShell предоставляет широкие возможности по управлению правилами Windows Firewall из командной строки. Вы можете автоматически запускать скрипты PowerShell для открытия/закрытия портов при возникновении определенных событий. В следующей статье мы рассмотрим простую систему на базе PowerShell и Windows Firewall для автоматической блокировки IP адресов, с которых выполняется удаленный перебор паролей по RDP на Windows VDS сервере.

Windows включает в себя надежный (в целом 🙄), но простой в использовании, брандмауэр с расширенными возможностями. А с помощью PowerShell 7 можно легко настроить его из командной строки. В этой статье описываются общие команды, используемые в межсетевом экране Windows, а также возможные способы их использования.

Модуль NetSecurity хорошо задокументирован. Учтите, что эта статья относится только к операционной системе Windows. Для других операционных систем существуют другие инструменты командной строки, которые могут использоваться для выполнения тех же задач, такие как UFW или IPTables в Linux.


Вызов модуля NetSecurity

Предустановленный в системе модуль NetSecurity обладает всем необходимым функционалом для управления правилами межсетевого экрана Windows. Чтобы задействовать данный модуль, достаточно импортировать его показанным ниже способом (конечно же команду запускаем в PowerShell):

Import-Module -Name 'NetSecurity'

Вывод списка правил

Командлет Get-NetFirewallRule выводит список настроенных правил. В системе большое количество предварительно настроенных правил, но для примера мы выбрали первые 10:

Get-NetFirewallRule | Select-Object DisplayName, Enabled, Direction, Action -First 10

Get-NetFirewallRule

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

Get-NetFirewallRule | Select-Object * -First 1

Get-NetFirewallRule | Select-Object * -First 1


Создание нового правила

Создать новое правило позволяет команда New-NetFirewallRule. Основные параметры, которые нужно передать команде следующие:

  • DisplayName — название правила;
  • Direction — Направление трафика, которое нужно блокировать. Может быть либо входящим (Inbound), либо Исходящим (Outbound);
  • Action — Действие правила. Правило может быть либо Разрешающим (Allow), либо Запрещающим (Block).
$Params = @{ "DisplayName" = 'Block WINS' "Direction" = 'Inbound' "Action" = 'Block' "RemoteAddress" = 'WINS' }
New-NetFirewallRule @Params

Если не указан параметр Name, система сгенерирует случайный GUID. DisplayName может быть читабельным, но сам Name будет сгенерирован случайным образом.


Изменение существующего правила

Что если нужно изменить какой-то параметр правила, не удаляя и пересоздавая его? Для этого нужно задействовать командлет Set-NetFirewallRule.

$Params = @{
"DisplayName" = 'Block WINS'
"Action" = 'Allow'
}

Set-NetFirewallRule @Params

Данная команда также позволяет вносить изменения в несколько правил сразу. Это можно сделать, передав команде одно из трех параметров правила:

  • Name — Параметр по умолчанию. Если команде переданы несколько параметров Name в виде строки или же через пайплайн (|), изменения коснутся каждого из правил;
  • DisplayName — так же, как и в случае с параметром Name, команде можно передать нескольких правил, чтобы изменить их;
  • DisplayGroup или Group — Если несколько правил сгруппированы, то команде можно передать название этой группы и внести изменения во все члены указанной группы.

Удаление правила

И, наконец, мы хотим удалить правило, которое больше не нужно. Для этого запускаем командлет Remove-NetFirewallRule. Также при удалении часто рекомендуется использовать параметр WhatIf, который позволяет убедиться в том, что будет удалено нужное правило.

Remove-NetFirewallRule -DisplayName "Block WINS"

Следует отметить, что данный командлет позволяет удалять несколько правил сразу. На примере ниже мы удаляем все отключенные правила, которые содержит групповая политика firewall_gpo в домене ad.local.test.

Remove-NetFirewallRule -Enabled 'False' -PolicyStore 'ad.local.test\firewall_gpo'

Запущенный сам по себе командлет Remove-NetFirewallRule достаточно полезный, но в то же время опасный, так как удаляет все локально созданные правила. Если есть доменная групповая политика, определяющая правила межсетевого экрана, данная команда удалит все локальные правила, конфликтующие с правилами групповой политики.


Дополнительные возможности

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

  • Copy-NetFirewallRule — данная команда копирует существующее правило и все связанные с ними фильтры в то же или другое хранилище политик;
  • Disable-NetFirewallRule — отключает ранее созданное правило. Отключенное правило не удаляется из базы, но уже никак не влияет на трафик. Если запустить эту команду без параметров, то она отключит все активные правила на целевой машине. Поэтому если не указано конкретное правило или группа правил, рекомендуется всегда запускать данную команду с параметром WhatIf;
  • Enable-NetFirewallRule — в противовес предыдущей команде, данный командлет включает все отключенные правила. Если не указано конкретное правило, то данную команду также рекомендуется запускать с параметром WhatIf;
  • Get-NetFirewallProfile — эта команда отображает параметры, настроенные для указанного профиля, например, профилей Domain, Private или Public;
  • Get-NetFirewallSettings — глобальные параметры брандмауэра можно получить с помощью команды Get-NetFirewallSettings. Это такие параметры, как параметры сертификатов, организация очередей пакетов или списки авторизации;
  • Rename-NetFirewallRule — данная команда позволяет переименовать существующее правило. Это полезно, если правило было создано без указания имени, таким образом получив случайный GUID в качестве название, и предпочтительно назначить читабельное название;
  • Set-NetFirewallProfile — для установки определенных параметров отдельных профилей можно использовать команду Set-NetFirewallProfile. Это позволяет каждому профилю иметь различные настройки;
  • Set-NetFirewallSettings — позволяет настроить поведение межсетевого экрана независимо от используемого профиля сети;
  • Show-NetFirewallRule — эта вспомогательная команда отображает правила брандмауэра и связанные с ними объекты в виде отформатированного списка.

Данный модуль также включает расширенные возможности для управления IPSec. Указанные выше команды управляют стандартными настройками межсетевого экрана Windows.


Заключение

Существует множество команд для управления межсетевым экраном Windows. В этой статье рассматриваются только некоторые из них, наиболее важные команды для быстрого вывода списка, создания, изменения и удаления правил брандмауэра. Но с помощью модуля NetSecurity можно сделать настройки и посложнее.

This article covers the basics of managing the settings and rules of the built-in Windows Defender Firewall with Advanced Security from the PowerShell command line. We’ll look at how to enable/disable the firewall for different network profiles, create or remove firewall rules, and import/export Windows Firewall rules with PowerShell.

Contents:

  • How to Turn Windows Defender Firewall On or Off with PowerShell
  • Create Windows Firewall Rules Using PowerShell
  • Modifying an Existing Windows Firewall Rule Using PowerShell
  • How to Enable/Disable/Remove Windows Firewall Rule with PowerShell
  • PowerShell: List Active Rules in Windows Firewall

Windows Firewall settings are typically managed using a separate graphical MMC snap wf.msc (Control Panel -> System and Security -> Windows Defender Firewall -> Advanced settings). You can perform most Windows Firewall configuration and settings management operations from the PowerShell command line. You can use the built-in NetSecurity module to do this (which is available in the version of Windows PowerShell 5.1 or newer).

You can list the available cmdlets in the NetSecurity module by using the command:

Get-Command -Module NetSecurity

powershell NetSecurity on windows 10 to manage windows defender advanced firewall

Previously, the netsh advfirewall firewall command was used to manage Windows Firewall rules and settings.

How to Turn Windows Defender Firewall On or Off with PowerShell

The Windows Defender firewall is enabled by default.

Get-NetFirewallProfile | Format-Table Name, Enabled

There are three types of network profiles in Windows Firewall:

  • Domain – is applied to the computers that are joined to an Active Directory domain;
  • Private – home, SOHO, or workgroup networks;
  • Public – public networks.

By default, the Windows Firewall allows all outbound connections and blocks all inbound connections (except those that are allowed) for each network profile.

The Network Location Awareness (NLA) service stores information about network types in a database. You can manually change the network profile (location) in Windows if it is not detected correctly.

Each network profile (location) may have different firewall rules in use. By default, all of the computer’s network interfaces are protected by a firewall and all three types of profiles are applied to them.

To completely disable the Windows firewall, run the following command

Set-NetFirewallProfile -All -Enabled False

Or specify a specific profile name instead of All:

Set-NetFirewallProfile -Profile Public -Enabled False

In order to enable the Windows Firewall for all three network profiles, use the following command

Set-NetFirewallProfile -All -Enabled True

Displays the type of profile that applies to the network connection:

Get-NetConnectionProfile

The DomainAuthenticated profile is applied to the Ethernet0 network connection in this example.

If PowerShell Remoting (WinRM) is configured on remote computers, you can manage Windows Firewall rules on those computers. In this example, we will use the Invoke-Command cmdlet to connect to remote computers in the list and disable the firewall on them.

$computers = @('WKS01', 'WKS02', 'WKS03')
Invoke-Command -ComputerName $computers {Set-NetFirewallProfile -All -Enabled False}

You can change the default action for the Public profile to block all inbound connections.

Set-NetFirewallProfile –Name Public –DefaultInboundAction Block

The current profile settings can be displayed as follows:

Get-NetFirewallProfile -Name Public

Set-NetFirewallProfile

If you manage Windows Firewall settings using a GPO, you can view the current resulting profile settings as follows:

Get-NetFirewallProfile -policystore activestore

Make sure that all firewall settings are applied to all network interfaces on the computer:

Get-NetFirewallProfile -Name Public | fl DisabledInterfaceAliases

If all interfaces are protected, the command should return:

DisabledInterfaceAliases : {NotConfigured}

Get-NetFirewallProfile

You can disable a particular profile for a network interface ( you can list network adapters in Windows using the Get-NetIPInterface cmdlet):

Set-NetFirewallProfile -Name Public -DisabledInterfaceAliases "Ethernet0"

As you can see, the Public profile is no longer applied to the Ethernet0 interface::

DisabledInterfaceAliases : {Ethernet0}

disable public location for ehernet0 interface

You can use the Set-NetFirewallProfile cmdlet to change the profile settings (default action, logging settings, log file path and size, notification settings, etc.). You can configure network connection logging settings for each network location profile. By default, Windows Firewall logs are stored in %systemroot%\system32\LogFiles\Firewall, and the file size is 4MB. You can enable connection logging and increase the maximum file size:

Set-NetFireWallProfile -Profile Domain -LogBlocked True -LogMaxSize 20000 -LogFileName ‘%systemroot%\system32\LogFiles\Firewall\pfirewall.log’

Create Windows Firewall Rules Using PowerShell

There are 9 PowerShell cmdlets to manage firewall rules on Windows:

  • New-NetFirewallRule
  • Copy-NetFirewallRule
  • Disable-NetFirewallRule
  • Enable-NetFirewallRule
  • Get-NetFirewallRule
  • Remove-NetFirewallRule
  • Rename-NetFirewallRule
  • Set-NetFirewallRule
  • Show-NetFirewallRule

Let’s take a look at a few simple examples of how to open ports in the Windows Firewall.

For example, if you want to allow incoming TCP connections on TCP ports 80 and 443 for both the Domain and Private profiles, run the following command:

New-NetFirewallRule -DisplayName 'HTTP-Inbound' -Profile @('Domain', 'Private') -Direction Inbound -Action Allow -Protocol TCP -LocalPort @('80', '443')

New-NetFirewallRule create new firewall rule with powershell

You can allow or block network access for a specific application (executable). For example, you may want to block outbound connections for the Firefox browser:

New-NetFirewallRule -Program “C:\Program Files (x86)\Mozilla Firefox\firefox.exe” -Action Block -Profile Domain, Private -DisplayName “Block Firefox browser” -Description “Block Firefox browser” -Direction Outbound

Let’s allow an incoming RDP connection on the default TCP\3389 port from only one IP address:

New-NetFirewallRule -DisplayName "AllowRDP" –RemoteAddress 192.168.2.200 -Direction Inbound -Protocol TCP –LocalPort 3389 -Action Allow

To allow ICMP pings for IP addresses from the specified ranges of IP addresses and subnets, create the following rule:

$ips = @("192.168.2.15-192.168.2.40", "192.168.100.15-192.168.100.200", ”10.1.0.0/16”)
New-NetFirewallRule -DisplayName "Allow inbound ICMPv4" -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -RemoteAddress $ips -Action Allow
New-NetFirewallRule -DisplayName "Allow inbound ICMPv6" -Direction Inbound -Protocol ICMPv6 -IcmpType 8 -RemoteAddress $ips -Action Allow

Add a list of IP addresses from a plain text file to the firewall rule (one IP address per line):

$ips=Get-Content C:\temp\ip.txt
Get-NetFirewallrule -DisplayName 'AllowRDP'|Set-NetFirewallRule -RemoteAddress $ips

Allow all incoming connections from the specified IP address. This will add the IP address to the firewall whitelist:

$IP = '192.168.1.20'
New-NetFirewallRule -DisplayName "Allow $IP" -Direction Inbound -Action Allow -RemoteAddress $IP

Modifying an Existing Windows Firewall Rule Using PowerShell

If you want to edit a firewall rule, use the Set-NetFirewallRule cmdlet. For example, you may want to allow inbound connections from a specific IP address for a rule that you have previously created:

Get-NetFirewallrule -DisplayName 'HTTP-Inbound' | Get-NetFirewallAddressFilter | Set-NetFirewallAddressFilter -RemoteAddress 192.168.1.10

To add multiple IP addresses to a firewall rule, use the following PowerShell script:

$ips = @("192.168.2.15", "192.168.2.17",”192.168.100.15”)
$current_ips = (Get-NetFirewallRule -DisplayName 'HTTP-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$current_ips += $ips
Get-NetFirewallrule -DisplayName 'HTTP-Inbound'|Set-NetFirewallRule -RemoteAddress $current_ips

List of all IP addresses in a firewall rule:

Get-NetFirewallrule -DisplayName 'Http_inbound'|Get-NetFirewallAddressFilter

Remove one IP address from a firewall rule:

$removeip = "192.168.100.5"
$current_ips = (Get-NetFirewallRule -DisplayName 'HTTP-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$filterIP = $current_ips | Where-Object{ $_ -notin $removeip }
Get-NetFirewallrule -DisplayName 'HTTP-Inbound'|Set-NetFirewallRule -RemoteAddress $filterIP

add ip address to existing firewall rule

How to Enable/Disable/Remove Windows Firewall Rule with PowerShell

You can use the Disable-NetFirewallRule and Enable-NetFirewallRule cmdlets to enable and disable firewall rules.

Disable-NetFirewallRule –DisplayName 'HTTP-Inbound'

To allow ICMP (ping), run this command:

Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In

To remove a firewall rule, use the Remove-NetFirewallRule cmdlet.

Remove-NetFirewallRule -DisplayName 'HTTP-Inbound'

To reset all Microsoft Firewall rules and restore the default settings, run the following command

netsh advfirewall reset

or:

(New-Object -ComObject HNetCfg.FwPolicy2).RestoreLocalFirewallDefaults()

This will delete all of the user-defined settings as well as the Microsoft Defender firewall rules. Only the network access rules that are built into Windows will remain.

Before resetting the firewall rules, you can export the current settings to a file.

netsh advfirewall export "C:\Backup\firewall-config.wfw"

Later, you can restore the old firewall settings by importing the rules file:

netsh advfirewall import "C:\Backup\firewall-config.wfw"

PowerShell: List Active Rules in Windows Firewall

The list of enabled firewall rules for incoming traffic can be displayed as follows

Get-NetFirewallRule | where {($_.enabled -eq $True) -and ($_.Direction -eq "Inbound")} |ft

You can only list outbound blocking rules:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound

If you want to display the program (executable) name in the rule:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound | %{$_.Name; $_ | Get-NetFirewallApplicationFilter}

Get-NetFirewallrule - view firewall rule properties

As you can see, the Get-NetFirewallRule cmdlet doesn’t show network ports and IP addresses for firewall rules. To display the detailed information about allowed inbound (outbound) connections in a more convenient way with  the port numbers, use the following PowerShell script:

Get-NetFirewallRule -Action Allow -Enabled True -Direction Inbound |
Format-Table -Property Name,
@{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},
@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}},
@{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},
@{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},
Enabled,Profile,Direction,Action

Use PowerShell to List Firewall Rules with port nubbers

PowerShell provides a wide range of options for managing Windows Firewall rules from the command prompt. You can automatically run PowerShell scripts to open/close ports if certain events happen. In the following article, we’ll look at simple PowerShell- and Windows Firewall-based solutions to automatically block RDP brute-force attacks on your Windows VDS host by adding the attacker’s IP address to the firewall rule.

In Powershell, you can easily enable or disable Windows Firewall using the Set-NetFirewallProfile command. This cmdlet is used to configure the Firewall’s advanced security settings for a particular, or all, network profile.

While you can also disable Firewall using GUI options like Control Panel/Windows Settings, doing it via CLI options like PowerShell/CMD is more efficient.

Note: Firewall is a key line of defense for your network against unauthorized access and malicious programs. While you can temporarily disable it for testing or other purposes, we advise enabling it afterward.

How to Enable Firewall via Powershell

  1. Press Windows + X to open the quick link menu.
  2. Press and accept the prompt to launch Windows PowerShell (Admin).
  3. Use the following commands as required. Type them and press Enter after each.
  4. Enable Firewall entirely:
    Set-NetFirewallProfile -Enabled True
  5. Enable Firewall for a specific profile(s):
    Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
    Check the Network Profiles section for more on this.
  6. Check if Firewall is enabled:
    netsh advfirewall show all
    netsh-advfirewall-show-all

How to Disable Firewall via Powershell

  1. Press Windows + X to open the quick link menu.
  2. Press and accept the prompt to launch Windows PowerShell (Admin).
  3. Use the following commands as required. Type them and press Enter after each.
  4. Disable Firewall entirely:
    Set-NetFirewallProfile -Enabled False
  5. Disable Firewall for a specific profile(s):
    Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
    Check the Network Profiles section for more on this.
    Powershell-disable-firewall-domain-public-private

  6. Check if Firewall is disabled:
    netsh advfirewall show all

Remotely Enable/Disable Firewall with Powershell

Note: WinRM needs to be set up beforehand on the target computer for remote disabling to work. Check out How to enable Windows Remote Shell for more on that.

Disable Firewall on One Remote Computer

Replace acer22 with the remote computer’s name and use the following commands:

Enter-PsSession -ComputerName acer22
Set-NetFirewallProfile -All -Enabled False

Powershell-remote-disable-firewall

Disable Firewall On Multiple Remote Computers

Replace acer22 nitro15 dell and so on with the remote computers’ names and add or subtract more names as appropriate. Then use the following commands:

$computers = @(‘acer22', ‘nitro15’, ‘dell’)
$computers | ForEach-Object {
Invoke-Command-ComputerName $_ {
Set-NetFirewallProfile-All -Enabled False
}
}

Remote-disable-firewall-multple-computers

How to Enable/Disable Firewall Using Command Prompt?

In CMD, we’ll use the netsh advfirewall command to enable/disable the firewall. This command also allows for precise control of firewall rules for each of the profiles (Domain, Public, Private).

Enable Firewall via CMD

  1. Press Windows + R to launch Run.
  2. Type cmd and press CTRL + Shift + Enter to launch elevated Command Prompt.
  3. Use the following commands as required. Type them and press Enter after each.
  4. Enable Firewall entirely:
    netsh advfirewall set allprofiles state on
    cmd-netsh-advfirewall-set-allprofiles-state-on

  5. Enable Firewall for the current profile:
    netsh advfirewall set currentprofile state on
  6. Enable Firewall for a specific profile(s):
    netsh advfirewall set publicprofile state on
    Replace public with domain or private as appropriate. Check the Network Profiles section for more on this.
  7. Check if Firewall is enabled:
    netsh advfirewall show all

Disable Firewall via CMD

  1. Press Windows + R to launch Run.
  2. Type cmd and press CTRL + Shift + Enter to launch elevated Command Prompt.
  3. Use the following commands as required. Type them and press Enter after each.
  4. Enable Firewall entirely:
    netsh advfirewall set allprofiles state off
  5. Enable Firewall for the current profile:
    netsh advfirewall set currentprofile state off
  6. Enable Firewall for a specific profile(s).
    netsh advfirewall set publicprofile state off
    Replace public with domain or private as appropriate. Check the Network Profiles section for more on this.
  7. Check if Firewall is disabled:
    netsh advfirewall show all
    cmd-netsh-advfirewall-show-all

Network Profiles

You can enable/disable the firewall for Domain, Public, Private profiles, or any combination of the three. Simply use the appropriate profiles in the commands above.

  • Domain Profile: This applies to networks where the host system can authenticate to a domain controller. It’s applicable for business environments because of the high level of security and authentication.
  • Private Profile: It is a user-assigned profile designed for trusted networks such as home or work networks. It’s generally safe to turn on Network Discovery and File sharing.
  • Public Profile: It is the default profile, designed for public networks such as public Wi-Fi hotspots. We recommend turning off network discovery and file sharing for security reasons.

Related Questions

How to Enable/Disable Firewall Through GUI?

Enabling/Disabling the firewall via GUI is very simple. To do so:

  1. Press Windows + R to launch Run.
  2. Type windowsdefender://network/ and press Enter to open the Firewall and Network protection window.
  3. Click on your active profile and press the switch to turn the firewall on/off.
    disable-firewall-gui-windows-security

How to Allow an App through Windows Firewall?

A firewall monitors your network traffic and blocks harmful/inappropriate content. Occasionally, it can block or interfere with a trusted app that you need. In such cases, you can allow an app through the firewall with the following steps:

  1. Press Windows + R to launch Run.
  2. Type windowsdefender://network/ and press Enter.
  3. Click on Allow an App through Firewall.
  4. Press Change Settings.
  5. Check the tick box to allow the app through the app. Use Allow Another App if you don’t see your app on the list.
    Windows-Defender-Firewall-Allowed-Apps

  6. Press OK to save the changes.

GUI vs. CLI. Which Is Better For Disabling Firewall?

You can use both GUI (Control Panel, Windows Settings) and CLI (Powershell, Command Prompt) to disable Firewall. It’s just a matter of preference.

Most users prefer GUI (Graphical User Interface) as it’s easier to understand and navigate. But CLI (Command Line Interface) is more efficient as you only need to enter a line of code to accomplish the same thing.

Is It Safe To Disable Windows Firewall?

A firewall is an important layer of security for your network. Ideally, you should use an antivirus along with Windows Firewall for proper protection.

It’s fine to disable the firewall temporarily. But we do not recommend keeping your firewall disabled in the long term. This would leave your network vulnerable to unauthorized access, malicious programs, and other cyber threats.

How to Change Sharing Settings for Network Profiles?

  1. Press Windows + I to launch Settings.
  2. Go to Network and Internet > Ethernet.
  3. Press Change Advanced Sharing Settings on the right.
  4. Adjust sharing settings as appropriate and click Save Changes.
    Network-Advanced-Sharing-Settings

Wondering how to Configure Windows Firewall Rules with PowerShell? We will help you it.

Here at Bobcares, we have seen several such Firewall related queries as part of our Server Management Services

Today, let’s see some of its benefits and how our Support Engineers configure it.

Configure Windows Firewall Rules with PowerShell

Usually, Windows Firewall settings are managed from the graphic console: Control Panel -> System and Security -> Windows Defender Firewall.

Previously, we could use the following command to manage Windows Firewall rules and settings:

netsh advfirewall firewall

There are 85 commands available in the NetSecurity module on Windows. We can display the whole list:

Get-Command -Module NetSecurity

How to Manage Windows Firewall Network Profiles from PowerShell

Usually, there are three types of network profiles in Windows Firewall:

  • Domain – can apply to the computers in an Active Directory domain
  • Private – home or corporate networks
  • Public – public networks

Generally, network Location Awareness (NLA) keeps the information about network types in its database. We can change our network profile (location) if it has been detected incorrectly.

  • Firstly, to enable all three network profiles: Domain, Public and Private, use this command:
Set-NetFirewallProfile -All -Enabled True
  • Or, set the specific profile instead All:
Set-NetFirewallProfile -Profile Public -Enabled True
  • In order to,  disable the firewall for all three network location, use the command:
Set-NetFirewallProfile -All -Enabled False
  • Generally, using the Set-NetFirewallProfile cmdlet, we can change profile options (a default action, logging, a path to and a size of a log file, notification settings, etc.).
  • Next, allow all outbound connections and block inbound ones (except allowed ones) in the profile settings.
  • Let us change the default action for the Public profile to block all inbound connections.
Set-NetFirewallProfile –Name Public –DefaultInboundAction Block
  • We can display the current profile settings as follows:
Get-NetFirewallProfile -Name Public
  • If we manage Windows Firewall settings using GPO, we can display the current resulting profile settings as follows:
Get-NetFirewallProfile -policystore activestore
  • Make sure to apply all firewall settings to all network interfaces of the computer.
Get-NetFirewallProfile -Name Public | fl DisabledInterfaceAliases
  • If all interfaces are protected, the command will return the following:
DisabledInterfaceAliases : {NotConfigured}
  • To disable the specific interface profile (to display the list of interface names, use the Get-NetIPInterface):
Set-NetFirewallProfile -Name Public -DisabledInterfaceAliases “Ethernet0”
  • As we can see, Public profile is no longer applied to Ethernet0:
DisabledInterfaceAliases : {Ethernet0}
  • Set network connection logging options at the profile level.

By default, Windows Firewall logs are stored in %systemroot%\system32\LogFiles\Firewall and the file size is 4MB.

  • Enable all connection logging and change the maximum file size:
Set-NetFireWallProfile -Profile Domain -LogBlocked True -LogMaxSize 20000 -LogFileName ‘%systemroot%\system32\LogFiles\Firewall\pfirewall.log’

How to Create, Edit or Remove Windows Firewall Rules with PowerShell

There are 9 cmdlets to manage our firewall rules:

New-NetFirewallRule
Copy-NetFirewallRule
Disable-NetFirewallRule
Enable-NetFirewallRule
Get-NetFirewallRule
Remove-NetFirewallRule
Rename-NetFirewallRule
Set-NetFirewallRule
Show-NetFirewallRule

For example, if we want to allow inbound TCP connections to ports 80 and 443 for Domain and Private profiles, use this command:

New-NetFirewallRule -DisplayName ‘HTTP-Inbound’ -Profile @(‘Domain’, ‘Private’) -Direction Inbound -Action Allow -Protocol TCP -LocalPort @(’80’, ‘443’)
  • Firstly, to allow or block network access for an app. For example, we want to block outbound connections for Firefox:
New-NetFirewallRule -Program “C:\Program Files (x86)\Mozilla Firefox\firefox.exe” -Action Block -Profile Domain, Private -DisplayName “Block Firefox browser” -Description “Block Firefox browser” -Direction Outbound
  • Then, to allow inbound RDP connection on port 3389 from one IP address only:
New-NetFirewallRule -DisplayName “AllowRDP” –RemoteAddress 192.168.2.200 -Direction Inbound -Protocol TCP –LocalPort 3389 -Action Allow
  • Next, to allow ping (ICMP) for addresses from the specified IP subnet or IP range, use these commands:
$ips = @(“192.168.2.15-192.168.2.40”, “192.168.100.15-192.168.100.200”, ”10.1.0.0/16”)
New-NetFirewallRule -DisplayName “Allow inbound ICMPv4” -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -RemoteAddress $ips -Action Allow
New-NetFirewallRule -DisplayName “Allow inbound ICMPv6” -Direction Inbound -Protocol ICMPv6 -IcmpType 8 -RemoteAddress $ips -Action Allow
  • In order to, edit an existing firewall rule, the Set-NetFirewallRule cmdlet is used. For example, to allow inbound connections from the specified IP address for the rule created earlier:
Get-NetFirewallrule -DisplayName ‘HTTP-Inbound’ | Get-NetFirewallAddressFilter | Set-NetFirewallAddressFilter -RemoteAddress 192.168.1.10
  • To add multiple IP addresses to a firewall rule, use this script:
$ips = @(“192.168.2.15”, “192.168.2.17”,”192.168.100.15”)
Get-NetFirewallrule -DisplayName ‘WEB-Inbound’|Set-NetFirewallRule -RemoteAddress $ips
  • In order to, display all IP addresses in a firewall rule:
Get-NetFirewallrule -DisplayName ‘Allow inbound ICMPv4’|Get-NetFirewallAddressFilter
  • Then, enable/disable firewall rules using Disable-NetFirewallRule and Enable-NetFirewallRule cmdlets.
Disable-NetFirewallRule –DisplayName ‘WEB-Inbound’
  • Next, to allow ICMP (ping), run this command:
Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In
  • In order to  remove a firewall rule, the Remove-NetFirewallRule cmdlet is used.

Listing Windows Firewall Rules with PowerShell

  • Firstly, we can display the list of active firewall rules for our inbound traffic as follows:
Get-NetFirewallRule | where {($_.enabled -eq $True) -and ($_.Direction -eq “Inbound”)} |ft
  • Next, to display the list of outbound blocking rules:
Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound
  • Then, to display an app name in a rule:
Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound | %{$_.Name; $_ | Get-NetFirewallApplicationFilter
  • As we can see, the Get-NetFirewallRule cmdlet does not show network ports and IP addresses for our firewall rules.

To display the detailed information about allowed inbound (outbound) connections in a more convenient way showing the port numbers, use the following PowerShell script:

Get-NetFirewallRule -Action Allow -Enabled True -Direction Inbound |
Format-Table -Property Name,
@{Name=’Protocol’;Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},
@{Name=’LocalPort’;Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}},
@{Name=’RemotePort’;Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},
@{Name=’RemoteAddress’;Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},
Enabled,Profile,Direction,Action

.

Need any further assistance to configure filters in Nagios log server? – We’re available 24*7 

Conclusion

Today, we saw how our Support Techs configure Windows Firewall Rules with PowerShell

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

SEE SERVER ADMIN PLANS

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как открыть файл emz в windows 10
  • Как установить linux mint второй системой с windows 10
  • Windows 10 technical preview wallpapers
  • Windows kernel mode driver visual studio
  • Компьютер не обнаруживает второй монитор windows 10