Новое правило сетевого брандмаура

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

Для управления настройками 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 включен.

отключить 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 мы отключим файервол на удаленных компьютерах из списка:

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

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

Get-NetFirewallProfile -Name Public

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

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

Get-NetFirewallProfile -policystore activestore

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

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

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 Мб. Вы можете изменить включить журналирование подключений и увеличить максимальный размер файла:

Создать новое правило 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 - создать новое правило Windows Firewall с помощью PowerShell

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

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

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

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

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 в строке):

В предыдущей статье мы показывали как с помощью 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 адреса для ранее созданного правила:

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

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

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

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"

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

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

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

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

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

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

:/>  Как установить gif на рабочий стол windows 10 без программ

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

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

Windows · December 16, 2023

Understanding the New-NetFirewallRule Command

The New-NetFirewallRule command is part of the NetSecurity module in PowerShell. It provides a way to create new firewall rules using a variety of parameters, such as the rule name, action, direction, protocol, local and remote ports, and more. By using this command, you can create rules that are tailored to your specific security needs.

Examples of New-NetFirewallRule Usage

Let’s look at some examples of how the New-NetFirewallRule command can be used to enhance the security of your hosting environment.

Example 1: Allowing Remote Desktop Access

New-NetFirewallRule -DisplayName "Allow RDP" -Direction Inbound -Protocol TCP -LocalPort 3389 -Action Allow

This command creates a new inbound firewall rule named “Allow RDP” that allows Remote Desktop Protocol (RDP) traffic on TCP port 3389. This is useful if you need to remotely manage your VPS server.

Example 2: Blocking a Specific IP Address

New-NetFirewallRule -DisplayName "Block IP" -Direction Inbound -RemoteAddress 192.168.1.10 -Action Block

Example 3: Allowing HTTP and HTTPS Traffic

New-NetFirewallRule -DisplayName "Allow HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
New-NetFirewallRule -DisplayName "Allow HTTPS" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow

These commands create two new inbound firewall rules that allow HTTP and HTTPS traffic on ports 80 and 443, respectively. This is necessary if you’re running a web server on your cloud hosting platform.

Advanced Usage of New-NetFirewallRule

The New-NetFirewallRule command also supports advanced features, such as specifying the interface type, creating rules for specific profiles (domain, private, public), and setting rule group names for easier management.

Example: Creating a Rule for a Specific Profile

New-NetFirewallRule -DisplayName "Allow SQL" -Direction Inbound -Protocol TCP -LocalPort 1433 -Action Allow -Profile Domain

This command creates a new inbound firewall rule named “Allow SQL” that allows traffic on TCP port 1433 for SQL Server, but only when the server is connected to a domain network. This adds an extra layer of security by ensuring the rule is not applied to public or private networks.

Conclusion

I’m using Powershell to query a few networkrelated things and want to alter existing firewall rules accordingly.

I’ve added a static PowershellHandler-class to my programm which is basicaly just sending a script and returning the rusult as a string.

private static string Command(string powerShellScript)
{
    string errorMsg = string.Empty;

    powerShell.AddScript(powerShellScript);

    // make sure return values are outputted
    powerShell.AddCommand("Out-String");

    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
    powerShell.Streams.Error.DataAdded += (object sender, DataAddedEventArgs e) =>
    {
        errorMsg = ((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString();
    };

    IAsyncResult result = powerShell.BeginInvoke<PSObject, PSObject>(null, outputCollection);

    // wait for powershell command/powerShellScript to finish executing
    powerShell.EndInvoke(result);

    StringBuilder sb = new StringBuilder();

    foreach (var outputItem in outputCollection)
    {
        sb.AppendLine(outputItem.BaseObject.ToString());
    }

    // clears the commands we added to the powershell runspace so it's empty the next time we use it
    powerShell.Commands.Clear();

    // if an error is encountered, return it
    if (!string.IsNullOrEmpty(errorMsg))
        return errorMsg;

    return sb.ToString().Trim();
}

This working fine with Resolve-DNSName

powerShellResult = PowerShellHandler.Command("Resolve-DNSName -Name " + fullyQualifiedDomainName + " -Server " + DnsServer + " | Select-Object IPAddress");
List<string> powerShellResultList = powerShellResult.Split("\r\n").ToList();
powerShellResult = PowerShellHandler.Command("(Invoke-WebRequest -uri \"" + uri + "\").Content");
List<string> powerShellResultList = powerShellResult.Split("\r\n").ToList();
powerShellResult = PowerShellHandler.Command("Get-NetFirewallRule -Enabled true | Select-Object Name, DisplayName");

powerShellResult ends up being

"The term 'Get-NetFirewallRule' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

When I run this in Powershell directly I get the expected result, so it should work

Get-NetFirewallRule -DisplayName "Apache Reverse Proxy"

Name                          : {FADD5C1C-67E7-4261-BFA8-DFB6F0665ED4}
DisplayName                   : Apache Reverse Proxy
Description                   :
DisplayGroup                  :
Group                         :
Enabled                       : True
Profile                       : Any
Platform                      : {}
Direction                     : Inbound
Action                        : Allow
EdgeTraversalPolicy           : Block
LooseSourceMapping            : False
LocalOnlyMapping              : False
Owner                         :
PrimaryStatus                 : OK
Status                        : Die Regel wurde erfolgreich vom Speicher aus analysiert. (65536)
EnforcementStatus             : NotApplicable
PolicyStoreSource             : PersistentStore
PolicyStoreSourceType         : Local
RemoteDynamicKeywordAddresses : {}
PolicyAppId                   :

I’ve tested the version used by C#

$PSVersionTable returns the same data as the Shell used to get the data above, so it basically runs the same shell

Name                           Value
----                           -----
PSVersion                      7.3.6
PSEdition                      Core
GitCommitId                    7.3.6
OS                             Microsoft Windows 10.0.22621
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Any hints, what might cause this? I am flat out of ideas.

Official Documentation: https://learn.microsoft.com/en-us/powershell/module/netsecurity/new-netfirewallrule

The New-NetFirewallRule cmdlet in PowerShell is used to create a new firewall rule in the Windows Firewall. It allows you to specify various parameters to define the behavior and settings of the rule.

Some of the key parameters that can be used with New-NetFirewallRule include:

By using these parameters (and others), you can create customized firewall rules to control the flow of network traffic on your system.

Some code snippets about this cmdlet from our scripts


                        if (-not $rule)
                        {
                            $null = New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Profile Any -Program $progPath -Action Allow -Protocol $prot
                        }
                    }
                }
    

Write-Host "Enable PSRemoting"
Enable-PSRemoting -Force
New-NetFirewallRule -Name "Allow WinRM HTTPS" -DisplayName "WinRM HTTPS" -Enabled True -Profile Any -Action Allow -Direction Inbound -LocalPort 5986 -Protocol TCP
$cert = Get-ChildItem "Cert:\LocalMachine\My" -Recurse | Where-Object { $_.DnsNameList -eq $env:COMPUTERNAME }
if(-Not $cert)
{
    

# Enable PSRemoting
Enable-PSRemoting -Force
New-NetFirewallRule -Name "Allow WinRM HTTPS" -DisplayName "WinRM HTTPS" -Enabled True -Profile Any -Action Allow -Direction Inbound -LocalPort 5986 -Protocol TCP
$cert = Get-ChildItem "Cert:\LocalMachine\My" -Recurse | Where-Object { $_.DnsNameList -eq $env:COMPUTERNAME }
if(-Not $cert)
{
    

This Cmdlet is used in following scripts

This page was generated automatically and may contain errors. It does not claim to be complete or correct. All information without guarantee.

:/>  Папка Temp в Windows 10

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.

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.

disable or enable firewall on windows with powershell

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.

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.

Set-NetFirewallProfile -All -Enabled False

Or specify a specific profile name instead of All:

Set-NetFirewallProfile -Profile Public -Enabled False

Set-NetFirewallProfile -All -Enabled True

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

Get-NetConnectionProfile check profile used for NIC

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.

Get-NetFirewallProfile -Name Public

Set-NetFirewallProfile

Get-NetFirewallProfile -policystore activestore

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

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:

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.

New-NetFirewallRule create new firewall rule with powershell

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

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

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:

List of all IP addresses in a firewall rule:

Remove one IP address from a firewall rule:

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'

netsh advfirewall reset

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

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"

List Active Rules in Windows Firewall

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

Get-NetFirewallrule - view firewall rule properties

Use PowerShell to List Firewall Rules with port nubbers

Windows · December 16, 2023

Understanding Set-NetFirewallRule

Basic Syntax


Set-NetFirewallRule -Name <string> [-Action <Allow|Block|Bypass>] [-Enabled <True|False>] [-Description <string>] [<CommonParameters>]

Examples of Set-NetFirewallRule

Enabling a Firewall Rule


Set-NetFirewallRule -Name "MyFirewallRule" -Enabled True

This command will enable the firewall rule named “MyFirewallRule,” allowing traffic that matches the rule’s criteria to pass through the firewall.

Changing the Action of a Rule


Set-NetFirewallRule -Name "MyFirewallRule" -Action Block

Updating the Description of a Rule


Set-NetFirewallRule -Name "MyFirewallRule" -Description "New description for MyFirewallRule"

This command will change the description of “MyFirewallRule” to the specified text.

Advanced Usage

The Set-NetFirewallRule command can also be used in conjunction with other cmdlets to perform more complex tasks. For example, you can use the Get-NetFirewallRule cmdlet to retrieve a list of firewall rules and then pipe the results to Set-NetFirewallRule to modify multiple rules at once.


Get-NetFirewallRule -DisplayName "MyApp*" | Set-NetFirewallRule -Enabled False

This command will disable all firewall rules that have a display name starting with “MyApp.”

:/>  Клавиши для вырезания текста на клавиатуре и выделения текста на клавиатуре с помощью сочетания клавиш

Conclusion

To make the environment more secure it’s important to properly define and configure the firewall of your machines. However, there might be times when a specific executable must be added as an exception to the Inbound or Outbound rules of the firewall in order to have access.

In this article, let’s have a look at how you can configure firewall rules via MSI with Advanced Installer, VBScript and Powershell.

Firewall rules with VBScript

Although you can use the HNetCfg.FwAuthorizedApplication object with VBScript to define firewall rules, the easiest method is to call the netsh.exe utility that it’s included in Windows. This command-line utility allows you to modify the network configuration of a certain machine that is currently running. One of the commands available for netsh is advfirewall which allows you to change to the netsh advfirewall context. Jumping further into the context, you can type

netsh advfirewall firewall
?          	- Displays a list of commands.
add        	- Adds a new inbound or outbound firewall rule.
delete     	- Deletes all matching firewall rules.
dump       	- Displays a configuration script.
help       	- Displays a list of commands.
set        	- Sets new values for properties of a existing rule.
show       	- Displays a specified firewall rule.

So basically if we want to add a firewall rule we can use:

netsh.exe advfirewall firewall add rule name=FRIENDLYNAME dir=IN/OUT action=ALLOW/DENY program=PATHTOEXE enable=YES/NO profile=domain

If we want to remove a firewall rule we can use:

netsh.exe advfirewall firewall delete rule name=FRIENDLYNAME
Dim WshShell
Dim programPath2, programfiless, programfiles
Set WshShell = CreateObject("Wscript.Shell")
programfiless=WshShell.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
programfiles=WshShell.ExpandEnvironmentStrings("%ProgramW6432%")
ProgramPath2 = programfiless & "\Program Files (x86)\Caphyon\Firewall App\HelloWorld.exe"
WshShell.Run "netsh.exe advfirewall firewall add rule name=HelloWorld dir=in action=allow program=" & chr(34) & ProgramPath2 & chr(34) & " enable=yes profile=domain ", 0, False
  • Dim WshShell: Declares a variable named WshShell to hold a reference to the Windows Script Host Shell object.
  • Dim programPath2, programfiless, programfiles: Declares variables to store the paths of program files.
  • Set WshShell = CreateObject(“Wscript.Shell”): Creates an instance of the Windows Script Host Shell object.
  • programfiless = WshShell.ExpandEnvironmentStrings(“%ProgramFiles(x86)%”): Retrieves the path of the “Program Files (x86)” folder using the %ProgramFiles(x86)% environment variable.
  • programfiles = WshShell.ExpandEnvironmentStrings(“%ProgramW6432%”): Retrieves the path of the “Program Files” folder using the %ProgramW6432% environment variable.
  • ProgramPath2 = programfiless & “\Program Files (x86)\Caphyon\Firewall App\HelloWorld.exe”: Concatenates the program file path with the specific file name to create the full path of the executable file “HelloWorld.exe”.
  • WshShell.Run “netsh.exe advfirewall firewall add rule name=HelloWorld dir=in action=allow program=” & chr(34) & ProgramPath2 & chr(34) & ” enable=yes profile=domain “, 0, False: Runs the netsh.exe command to add a firewall rule named “HelloWorld” with the specified properties. The command allows incoming traffic (dir=in), allows the specified program (program=) with the path of “HelloWorld.exe”, enables the rule (enable=yes), and applies the rule to the domain profile.

Next, open Advanced Installer and navigate to the Custom Actions Page. In here, search for the Launch attached file and select the location of the VBScript. Next, configure the custom action to execute as shown below:

Launch attached file

As a best practice it’s also important to remove the firewall rule during the uninstallation. For that, it means we need another Custom Action and a different VBScrit to remove our rule. The VBScript code is:

Dim WshShell
Set WshShell = CreateObject("Wscript.Shell")
WshShell.Run "netsh.exe advfirewall firewall delete rule name=HelloWorld"

configure the custom action

Firewall rules with PowerShell

While netsh is still available and widely used by the community, starting with Windows 8.1 you can use the buit-in NetSecurity PowerShell module to manage firewall operations.

In general, there are 85 commands available in this module that you can use in Windows 10/11, but we are only interested in two of them. To add a firewall rule you can simply do:

$HelloWorldLocation = ${env:ProgramFiles(x86)} + "\Caphyon\Firewall App\HelloWorld.exe"
New-NetFirewallRule -Program $HelloWorldLocation -Action Allow -Profile Domain -DisplayName “HelloWorld” -Description “Block Firefox browser” -Direction Inbound

To remove a firewall rule is even simpler as we only use the Remove-NetFirewallRule PowerShell cmdlet:

Remove-NetFirewallRule -DisplayName "HelloWorld"

Next, open Advanced Installer and navigate to the Custom Actions Page. In here, search for the Run PowerShell script file and select the location of the PowerShell script. Next, configure the custom action to execute as shown below:

Run PowerShell script file

remove firewall PowerShell script

Firewall rules with Advanced Installer

If you don’t like to code, Advanced Installer made it much simpler to add firewall rules. First, navigate to the Windows Firewall page.

Next, click on New Rule. This will open a new window in which you can define the necessary details for your exception:

Windows Firewall page

As you can see, you can easily choose the direction, display name, program path, protocol and other settings directly from the GUI. In our case we wanted to mimic the above usages of netsh and PowerShell and left everything as before in the GUI.

And that is it, Advanced Installer will automatically create the exception during the installation and during the uninstallation it will remove the exception from the firewall, not needing to create two separate actions for it.

remove the exception from the firewall

All you have to do is build and install the MSI package. After the installation, if we check the Inbound rules, our rule is there:

check the Inbound rules

advanced MSI packaging

MSI Packaging In-Depth Training Book

by Alexandru Marin

Оставьте комментарий