Code Monkey home page Code Monkey logo

windowsfirewallhelper's Introduction

Windows Firewall Helper Class Library

A class library to manage the Windows Firewall as well as adding your program to the Windows Firewall Exception list.

This project supports dotNet4.6, NetStandard2 and NetCore5, therefore, is compatible with NetCore2+ and any version of dotNet equal or greater than version 4.6.

Even though it is possible to reference this library under Linux or Mac; it's obviously not going to work.

This readme file is for the version 2 of this library. Please check the V1 branch for older readme file.

How to get

This library is available as a NuGet package at nuget.org.

Help me fund my own Death Star

--OR--

You can always donate your time by contributing to the project or by introducing it to others.

How to use

The starting point of this library is the FirewallManager static class which can be used to get the instance of the class managing the firewall currently on the system.

If you are only targeting WinVista+ consider using the FirewallWAS.Instance static property to access the library's functionality. It allows for more flexibility and is easier to work with.

WindowsFirewallHelper.FirewallManager Class

This static class contains properties about the currently active Windows Firewall management class instance or the registered third party firewall products. This class also provides methods to register a third-party firewall product.

WindowsFirewallHelper.FirewallManager Static Properties

  • FirewallManager.Instance: Gets an instance of the Windows Firewall management class.
  • FirewallManager.Version: Gets the type of firewall that FirewallManager.Instance property returns.
  • FirewallManager.IsServiceRunning: Gets a boolean value indicating if the Windows Firewall Service is currently running.
  • FirewallManager.RegisteredProducts: Gets an array containing all registered third party firewall products.

WindowsFirewallHelper.FirewallManager Static Methods

  • FirewallManager.RegisterProduct(): Registers a third-party firewall product returning a handle that will unregisters the product while getting disposed.

WindowsFirewallHelper Namespace

This namespace contains shared and general classes as well as the main starting point of this library, FirewallManager class.

WindowsFirewallHelper Classes

  • FirewallManager: A static class to manage the current active firewall
  • FirewallProtocol: A class representing a Firewall Protocol
  • FirewallLegacy: Contains properties and methods of Windows Firewall v1 - Implementing the IFirewall interface
  • FirewallLegacyProfile: Contains properties of a Windows Firewall v1 profile - Implementing the IFirewallProfile interface
  • FirewallWAS: Contains properties and methods of Windows Firewall with Advanced Security (Vista+) - Implementing the IFirewall interface
  • FirewallWASProfile: Contains properties of a Windows Firewall with Advanced Security profile (Vista+) - Implementing the IFirewallProfile interface
  • FirewallWASRuleGroup: Contains properties and methods for managing a Windows Firewall with Advanced Security rule group (Vista+)
  • FirewallWASInternetControlMessage: Representing an Internet Control Message (ICM) type
  • FirewallProduct: Representing a third-party firewall product
  • FirewallProductRegistrationHandle: Representing a third-party firewall product registration handle that will automatically unregisters the product while getting disposed.

WindowsFirewallHelper Interfaces

  • IFirewall: Defines expected methods and properties of a firewall program or API
  • IFirewallProfile: Defines expected properties of a firewall profile
  • IFirewallRule: Defines expected properties of a firewall rule
  • IAddress: Defines expected methods of a network address

WindowsFirewallHelper.FirewallRules Namespace

This namespace contains classes that can be used for direct manipulation of a firewall rule.

WindowsFirewallHelper.FirewallRules Classes

  • FirewallLegacyApplicationRule: Contains properties of a Windows Firewall v1 application rule - Implementing the IFirewallRule interface
  • FirewallLegacyPortRule: Contains properties of a Windows Firewall v1 port rule - Implementing the IFirewallRule interface
  • FirewallWASRule: Contains properties of a Windows Firewall with Advanced Security rule - Implementing the IFirewallRule interface
  • FirewallWASRuleWin7: Contains properties of a Windows Firewall with Advanced Security rule for Windows 7+ - Extending the FirewallWASRule class
  • FirewallWASRuleWin8: Contains properties of a Windows Firewall with Advanced Security rule for Windows 8+ - Extending the FirewallWASRuleWin7 class

WindowsFirewallHelper.Exceptions Namespace

This namespace contains exception classes that might be thrown when using this library

WindowsFirewallHelper.Exceptions Classes

  • FirewallLegacyNotSupportedException: The exception that is thrown when an invoked method or action is not supported with the 'Windows Firewall API v1' - Extending the NotSupportedException class
  • FirewallWASNotSupportedException: The exception that is thrown when an invoked method or action is not supported with the 'Windows Firewall with Advanced Security' - Extending the NotSupportedException class
  • FirewallWASInvalidProtocolException: The exception that is thrown when a passed FirewallProtocol is invalid for a 'Windows Firewall with Advanced Security' action or method - Extending the `InvalidOperationException`` class

WindowsFirewallHelper.Addresses Namespace

This namespace contains the classes needed for manipulating or understanding a network address or a network service.

WindowsFirewallHelper.Addresses Classes

  • SingleIP: Represents a single network IP address - Implementing the IAddress interface
  • IPRange: Represents a range of network IP addresses - Implementing the IAddress interface
  • NetworkAddress: Represents a range of network IP addresses by subnet - Implementing the IAddress interface
  • SpecialAddress: An abstract class represents a special network address or network service - Implementing the IAddress interface
  • DefaultGateway: Represents the default network gateway - Extending the `SpecialAddress`` class
  • LocalSubnet: Represents thelocal network subnet - Extending the `SpecialAddress`` class
  • DHCPService: Represents the DHCP service - Extending the `SpecialAddress`` class
  • DNSService: Represents the DNS service - Extending the `SpecialAddress`` class
  • WINSService: Represents the WINS service - Extending the `SpecialAddress`` class

WindowsFirewallHelper.COMInterop Namespace

This namespace contains the interfaces and enums that is used to access the underlying COM objects. Some of these types are public and can be used to directly modify a COM object. Usually firewall rules. Rest of types are internal to this library.

Examples

Check the 'WindowsFirewallHelper.Sample' and 'WindowsFirewallHelper.NetCoreSample' projects as a brief example of what can be done using this class library. Screenshot

Basic examples

  • Creating and registering a new application exception rule for outbound traffic on the currently active profile:
var rule = FirewallManager.Instance.CreateApplicationRule(
    @"MyApp Rule",
    FirewallAction.Allow,
    @"C:\MyApp.exe"
);
rule.Direction = FirewallDirection.Outbound;
FirewallManager.Instance.Rules.Add(rule);
  • Creating and registering a new port rule for inbound traffic on the currently active profile:
var rule = FirewallManager.Instance.CreatePortRule(
    @"Port 80 - Any Protocol",
    FirewallAction.Allow,
    80,
    FirewallProtocol.TCP
);
FirewallManager.Instance.Rules.Add(rule);
  • Getting the list of all registered rules:
var allRules = FirewallManager.Instance.Rules.ToArray();
  • Removing a rule by name:
var myRule = FirewallManager.Instance.Rules.SingleOrDefault(r => r.Name == "My Rule");
if (myRule != null)
{
    FirewallManager.Instance.Rules.Remove(myRule);
}
  • Disabling notifications for all firewall profiles:
foreach (var profile in FirewallManager.Instance.Profiles)
{
    profile.ShowNotifications = false;
}

Advanced examples

  • Creating a heavily customized application rule (Some parts of the following code are only applicable to Windows Vista, Windows 7 and above):
var rule = FirewallManager.Instance.CreatePortRule(
    @"Port 80 - Any Protocol",
    FirewallAction.Allow,
    80,
    FirewallProtocol.Any
);
if (rule is FirewallWASRule wasRule)
{
    wasRule.Interfaces = NetworkInterface.GetAllNetworkInterfaces()
        .Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
        .ToArray();
    wasRule.ICMPTypesAndCodes = new[]
    {
        new FirewallWASInternetControlMessage(InternetControlMessageKnownTypes.Echo),
        new FirewallWASInternetControlMessage(InternetControlMessageKnownTypes.EchoReply)
    };
    if (rule is FirewallWASRuleWin7 wasRuleWin7)
    {
        wasRuleWin7.EdgeTraversalOptions = EdgeTraversalAction.Deny;
    }
}
rule.Direction = FirewallDirection.Outbound;
FirewallManager.Instance.Rules.Add(rule);
  • Working directly with the desired firewall management class without using the FirewallManager to add a new port rule (Following example is limited to Windows 8 and above):
if (FirewallWAS.IsSupported && FirewallWASRuleWin8.IsSupported)
{
    var rule = new FirewallWASRuleWin8(
        "My Port Rule",
        1080,
        FirewallAction.Allow,
        FirewallDirection.Inbound,
        FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public
    )
    {
        Description = "'My Port Rule' Allows Inbound traffic to my local Proxy Server from Wireless Adapters",
        NetworkInterfaceTypes = NetworkInterfaceTypes.Wireless,
        Protocol = FirewallProtocol.TCP
    };
    FirewallWAS.Instance.Rules.Add(rule);
}

License

The MIT License (MIT)

Copyright (c) 2016-2020 Soroush

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

windowsfirewallhelper's People

Contributors

ammarheidari avatar falahati avatar paulirwin avatar phyxionnl avatar verdesgrobert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

windowsfirewallhelper's Issues

Using WindowsFirewallHelper with .NET Core 2.1

Have had great success with .NET Framework but completely blocked when trying to use with .NET Core. Adding nuget package appears to work but DLL obviously doesn't get added, using WindowsFirewallHelper doesn't resolve. Pulling the source inexplicably has INetFwRule3 undefined in master and v1.3.6543.29360 tag. Any suggestions on getting this to work with .NET Core and/or resolving missing INetFwRule3 in source so I can attempt to build from source under .NET Core?

Remote Machines

Can you make this work on remote machines also? Or just local? I have searched and cannot figure out how to use on remote.

Modifying remoteaddresses - How to?

It is unclear to me how to modify the RemoteAddresses property (or other addresses) for a rule.
For example, I want to add and/or remove remote addresses for an existing rule.

I am able to get a reference to the existing rule I want to modify, however there is no constructor for IAddress, nor any methods that let one modify the address and subsequently assign the array of IAddress to the rule's RemoteAddresses property.

Ultimately my goal is to simply get a reference to the rule and then apply the new list of RemoteAddresses for the rule.

Your help would be most appreciated.

Exception thrown: 'System.NotSupportedException' in WindowsFirewallHelper.dll

I'm getting the following exceptions being thrown whenever I call any of the Firewall functions

Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Private.CoreLib.dll
Exception thrown: 'System.Runtime.InteropServices.COMException' in WindowsFirewallHelper.dll
Exception thrown: 'System.NotSupportedException' in WindowsFirewallHelper.dll

So in this example:

            if (FirewallManager.IsServiceRunning)
            {
                try
                {
                    var activeProfile = FirewallManager.Instance.GetActiveProfile();
                    var rules = FirewallManager.Instance.Rules.ToList();

I'll get 3 sets of these exceptions thrown (one for each reference to FirewallManager

The strange thing is that it's all working fine, no other errors or issues.

I'd prefer to not have any exceptions being thrown... Is there a way to prevent it?

Thanks.

Meaning of FirewallManager.IsServiceRunning and FirewallManager.Version

Hi,

at first a big thanks for wrapping nicer code around the windows firewall!
I tried to use WindowsFirewallHelper to add a rule at program start to my computers firewall. After a while and with your example code I found that IsServiceRunning returns false and Version returns None. I tried on two machines running Windows 11 with same results.
On both machines "Domain Networks" is disabled, private and public networks are enabled.
Do the results refer to the disabled "Domain Networks" firewall or does it mean something different?

Thanks,
Christian

Can't access FirewallWAS.Rules in v2.1.4.81

Hi,

I'm using FirewallHelper in a .NET Framework 4.8 project and have just updated from 1.6xx to 2.1.4.81. I can't use the FirewallWAS.Rules method because it tells me that I need C# 8.0 or later and Framework 4.8 is limited to 7.3. CS8370 is raised saying that recursive patterns are not available in C#7.3. See embedded image.

I had to look through the change log to get some essential migration information; a useful addition to your documentation would be a basic migration guide saying things such as "profiles are now specified in the GetProfile constructor in FirewallManager.Instance.GetProfile()" and "change all FirewallAPIV2 references to FirewallWAS etc.

Many thanks, Peter

image

Exception thrown: 'System.NotSupportedException' in WindowsFirewallHelper.dll

I get a warning like this in the immediate window when FirewallManager.Instance.Rules.SingleOrDefault is executed.

I use VS2022 with C# Desktop with Framework 7.0.
The program works fine but a warning appears like that. Can it be ignored?

Thanks.

Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Private.CoreLib.dll
Exception thrown: 'System.Runtime.InteropServices.COMException' in WindowsFirewallHelper.dll
Exception thrown: 'System.NotSupportedException' in WindowsFirewallHelper.dll
Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Private.CoreLib.dll
Exception thrown: 'System.Runtime.InteropServices.COMException' in WindowsFirewallHelper.dll
Exception thrown: 'System.NotSupportedException' in WindowsFirewallHelper.dll

                var wcfHttpRuleInName = String.Format("DiscountCard - WcfHttpRuleIn: Port {0} - Protocol {1}", Settings.Default.ServiceHttpPort, FirewallProtocol.Any);
                var wcfHttpRuleAction = FirewallAction.Allow;
                var wcfHttpRulePort = (ushort)Settings.Default.ServiceHttpPort;
                var wcfHttpRuleProtocol = FirewallProtocol.Any;
                //
                var isWcfHttpRuleInNameFounded = FirewallManager.Instance.Rules.SingleOrDefault(r => r.Name.Equals(wcfHttpRuleInName));
                if (isWcfHttpRuleInNameFounded == null)
                {
                    var ruleIn = FirewallManager.Instance.CreatePortRule(
                        wcfHttpRuleInName,
                        wcfHttpRuleAction,
                        wcfHttpRulePort,
                        wcfHttpRuleProtocol
                    );
                    ruleIn.Direction = FirewallDirection.Inbound;
                    FirewallManager.Instance.Rules.Add(ruleIn);
                }

image

Version on NuGet not in sync with GitHub

The source code on GitHub for version 1.6.3.40 includes the bug fix for port range "Must include last element of the range" (4d81786) for "PortHelper.cs" (https://github.com/falahati/WindowsFirewallHelper/blob/1.6.3.40/WindowsFirewallHelper/Helpers/PortHelper.cs). However, the exact same version on NuGet.org still has this bug and a look at the code in the package confirms this.

It looks like something failed in the pipeline for the PR, but I can´t find the details.

Would it be possible to make a new release that includes the port range fix?

How to add port range?

Hello,

I want to add a port range to a rule but it allows me o add just as short/int; I need to add a port range like "5000-7000" as a string. I can't add 2000 different rules for it.

How can I handle this?

Thank you.

Incorrect StartAddress and EndAddress properties when using small subnet masks

When parsing CIDR address notation to generate a NetworkAddress type, the Address and SubnetMask properties store the intended values. However, the logic for StartAddress and EndAddress attempt to exclude the lowest (original network) IP and the highest (broadcast) IP. This works for large subnet masks, but is improperly executed when using a small mask to request a small number of IP addresses per this sample program:

var addresses = new string[] {
	"1.1.1.1/8",
	"1.1.1.1/16",
	"1.1.1.1/30",
	"1.1.1.1/31",
	"1.1.1.1/32"
};

foreach(string a in addresses)
{
    NetworkAddress na = NetworkAddress.Parse(a);
    Console.WriteLine($"CIDR: {a}\nAddress: {na.Address}\nSubnetMask: {na.SubnetMask}\nStartAddress: {na.StartAddress}\nEndAddress: {na.EndAddress}\n");
}
CIDR: 1.1.1.1/8
Address: 1.1.1.1
SubnetMask: 255.0.0.0
StartAddress: 1.0.0.1
EndAddress: 1.255.255.254

CIDR: 1.1.1.1/16
Address: 1.1.1.1
SubnetMask: 255.255.0.0
StartAddress: 1.1.0.1
EndAddress: 1.1.255.254

CIDR: 1.1.1.1/30
Address: 1.1.1.1
SubnetMask: 255.255.255.252
StartAddress: 1.1.1.1
EndAddress: 1.1.1.2

CIDR: 1.1.1.1/31
Address: 1.1.1.1
SubnetMask: 255.255.255.254
StartAddress: 1.1.1.1
EndAddress: 1.1.1.0

CIDR: 1.1.1.1/32
Address: 1.1.1.1
SubnetMask: 255.255.255.255
StartAddress: 1.1.1.1
EndAddress: 1.1.1.1

Note that StartAddress and EndAddress are reversed for the /31 case.

At a high level, these results are counter-intuitive to begin with as when requesting a /30, one would expect 4 IP addresses when only 2 are provided. When requesting a /31, intuitively 2 IP addresses would be provided. Seemingly returning the full range without truncation would be a better behavior than having both '/31' and '/30' returning 2 IP addresses.

Enhance sample app with additional items

Add 2 items to sample Winforms app

  • An option to list 3rd party registered firewalls
  • Ability to set the rule name and associated profiles in the Add Port dialog

Global firewall status?

Hi,

I can check if firewall profiles are enabled. I would like to check if firewall is enabled too. Is that possible? How can I check it?

Thanks in advance!

How to Modify Existing Entries?

The readme contains examples of adding and removing entries, but not of modifying existing entries.

Let's say I get an instance of a rule like var rule = FirewallManager.Instance.Rules.First(x => x.Name == "Foo" && x.Direction == FirewallDirection.Inbound). If I use a setter on that rule instance, is that sufficient? Or do I need to pass it to FirewallManager.Instance.Rules.Add? Or would that create a duplicate of the rule? Do I need to delete the old one, create a new one, copy the properties over, and add the new one?

Dialog box "Windows Security Alert". Project selects checkbox "Private networks, such as my home or work network" itself

User will have this dialog if my project is run for the first time:
image
How to make my project communicating in private networks without the user's request?
I only have tried to code as in an example:
var rule = FirewallManager.Instance.CreateApplicationRule( @"MyApp Rule", FirewallAction.Allow, @"C:\MyApp.exe" ); rule.Direction = FirewallDirection.Outbound; FirewallManager.Instance.Rules.Add(rule);
But I get an exception UnauthorizedAccessException in the last row:
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at WindowsFirewallHelper.COMInterop.INetFwRules.Add(INetFwRule rule)
at WindowsFirewallHelper.Collections.FirewallWASRulesCollection'1.InternalAdd(INetFwRule native)
at WindowsFirewallHelper.InternalHelpers.Collections.ComCollectionBase'4.Add(TManaged item)

Nuget not working in .net core 2.1

I am attempting to add this to a .net core 2.1 project, but it will not add and just has the yellow hazard sign. I've tried multiple versions with no luck. any ideas?

Q: Changes to the rules by other programs

WindowsFirewallHelper caches the underlying COM object and since Windows Firewall COM API does no reflects updates fast enough you can, in theory, get a result that is outdated. How rarely this happens depends on the underlying Firewall API and therefore it might be hard to reproduce.

#32 might be used to detect such changes in the future.

Workaround
Since with version 2 of this library, it is possible to create multiple instances of any IFirewall implemented class, creating a new instance should, in theory, solve this problem by creating a new COM object.

Vista+:
var rules = new FirewallWAS().Rules.ToArray()

XP+:
var rules = new FirewallLegacy().Rules.ToArray()

Doing so leaves the COM object lifetime management to the user of the library.
There is no way to do this with version 1 of this library since these constructors are marked as internal.

Solution
Should add a new IFirewall.Refresh() or IFirewall.Reload() method to clear the COM cache of an instance. This is especially handy when using the FirewallManager class.

Ability to directly get / set the underlying Rule RemoteAddresses and LocalAddresses string

Is it possible (or could it be possible) to directly get/set the underlying Rule's RemoteAddresses and LocalAddresses properties through WIndowFirewallHelper?

I understand the entire objective is to safely wrap these properties using arrays of IAddress, but it would be nice to be able to get/set the raw string properties if for no other reason than debugging issues like my previously posted issue trying to assign a single IPV6 address.

EG:
var mystring=objRule.RemoteAddressesString;
and
objRule.RemoteAddresses=mystring;

Firewall profile - block

How can I block all connections but those that match an Allow rule? Seems likeprofile.DefaultInboundAction = FirewallAction.Block sets the firewall to block all connections, ignoring any allow rules. I'm looking for the option that matches Block (default) - the choice available in Windows Firewall With Advanced Security which blocks all connections except those that match an Allow rule?

Q: How to add a IP/Subnet

I'm writing a little application to read my security event logs and then block any IP address from a range outside my own country i.e. it will read 149.12.0.132 from the event then I want to add the address 149.0.0.0/8 to my blocking rule, SingeIP.parse() does not support this so how can I add an address like this?

Question about notification feature

Hi falahati, your class library appears to be quite sophisticated for managing the windows firewall rules - nice work!

However one feature which seems to be missing (or would be nice to have) in the library is a way to get notified when packages are dropped (or connection blocked) together with the information about which rule blocked a connection. Essentially what is shown in EventViewer > security > event 5157.

This would be very useful for troubleshooting and when implementing a firewall UI.

Is this something you would consider or is it maybe available but I haven't seen it?

Thx. harry

Problems with Assigning IPV6 SingleIP, RemoteAddresses issue with IPV6

Thanks for prior issue help.

I am trying to assign a SingleIP IPV6 address to Rule.RemoteAddresses.
Although it appears it may work, at some point when the joined string array is applied in StandardRule.cs to UnderlyingObject.RemoteAddresses something, presumably NetFwTypeLib, changes the single IPV6 address into a range.

For example:
2607:fea8:4260:31a::9
becomes
2607:fea8:4260:31a::9-2607:fea8:4260:31a::9

This creates a problem when you subsequently try to read and return Rule.RemoteAddresses later because IPRange.parse doesn't recognize the single IP range, and SingleIP also doesn't recognize what appears to be a range. As a result it simply doesn't get returned in the list of IPaddresses from Rule.RemoteAddresses.

Here's a small console app that should demo the problem more clearly (I hope). Note I am using the latest code you have here as of Nov 24 rather than the released Nuget version which also has some problems with IPV6 you already fixed yesterday.

`using System;
using System.Collections.Generic;
using System.Linq;
using WindowsFirewallHelper;

namespace AddressTest
{
class Program
{
static void Main(string[] args)
{
setRemoteAddresss();
Console.WriteLine("Press any key to end.");
var c = Console.ReadKey();
}

    static void setRemoteAddresss()
    {
        var RuleName = "Remote Desktop - User Mode (TCP-In)";
        var objRule = (from obj in FirewallManager.Instance.Rules where obj.Direction == FirewallDirection.Inbound && obj.Name == RuleName orderby obj.Name select obj).FirstOrDefault();

        List<IAddress> NewIPs = new List<IAddress>();
        List<string> iplist = new List<string> { "2607:fea8:4260:31a::9" };

        foreach (var iptext in iplist)
        {
            NewIPs.Add(WindowsFirewallHelper.Addresses.SingleIP.Parse(iptext));
        }

        Console.WriteLine("Assigning these RemoteAddresses:");
        foreach (var objIP in NewIPs)
        {
            Console.WriteLine(objIP.ToString());
        }
        objRule.RemoteAddresses = NewIPs.ToArray();

        Console.WriteLine("RemoteAddresses actually assigned:");
        var assignedIPs = objRule.RemoteAddresses;
        foreach (var objIP in assignedIPs)
        {
            Console.WriteLine(objIP.ToString());
        }

        return;
    }
}

}
`

UnauthorizedAccessException when adding a new rule

This is my first approach to this library and not sure if I'm missing something else or it's a bug.
I get an UnauthorizedAccessException when adding a new rule.
I'm using version 2.2.0.86

// Create and add rules for this app
try {
string ruleRootName = @"Myapp ";
FirewallProfiles allProfiles = FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public;
string thePath = Assembly.GetExecutingAssembly().Location;
var r1 = FirewallManager.Instance.CreateApplicationRule(allProfiles, ruleRootName + @"Rule (Outbound)", FirewallAction.Allow, thePath);
r1.Direction = FirewallDirection.Outbound;
FirewallManager.Instance.Rules.Add(r1);
}
catch (UnauthorizedAccessException e) {
Utils.LogV("Failed to set firewall rules");
}

Problem creating ICMP rules [Help Wanted]

I wish to create a firewall rule to allow ICMP pings from one particular ip address.

The following test code throws an exception on line 1 saying "Value does not fall within the expected range.". I've tried setting Port parameter to 0, 1, 123 and Nothing, regardless it throws an exception unless I change the protocol to TCP.

Dim RuleICMPTest1 As IRule = FirewallManager.Instance.CreatePortRule(FirewallManager.Instance.GetProfile().Type, "Name", FirewallAction.Allow, 0, FirewallProtocol.ICMPv4)
RuleICMPTest1.Direction = FirewallDirection.Inbound
RuleICMPTest1.RemoteAddresses = {WindowsFirewallHelper.Addresses.SingleIP.Parse("192.168.0.1")}
RuleICMPTest1.Protocol = FirewallProtocol.ICMPv4
FirewallManager.Instance.Rules.Add(RuleICMPTest1)

The following test code throws an exception on line 2 saying "Value does not fall within the expected range."

Dim RuleICMPTest2 = New WindowsFirewallHelper.FirewallAPIv2.Rules.StandardRule("NAME2", CUShort(0), FirewallAction.Allow, FirewallDirection.Inbound, FirewallProfiles.Domain)
RuleICMPTest2.Protocol = FirewallProtocol.ICMPv4
RuleICMPTest2.RemoteAddresses = {WindowsFirewallHelper.Addresses.SingleIP.Parse("192.168.0.1")}
FirewallManager.Instance.Rules.Add(RuleICMPTest2)

I'm sure I'm doing something wrong but not sure what. Any help gratefully received.

The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

Hello, been using this library for a while now with great success, but recently had a user get this error. We've tried a number of steps to resolve the issue to no avail, does anyone have any clues as to what might be wrong with his machine?

Trace:

System.IO.FileNotFoundException: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
--
at WindowsFirewallHelper.COMInterop.INetFwRules.Remove(String name)
at WindowsFirewallHelper.FirewallAPIv2.Firewall.RulesOnItemsModified(Object sender, ActiveCollectionChangedEventArgs`1 e)
at System.Collections.ObjectModel.Collection`1.Remove(T item)

Very slow ActiveCollection<T>.Sync

ActiveCollection<T>.Sync is very inefficient and causes significant slowdowns. Getting rules takes tens of seconds when there are about 1000 firewall rules.

I implemented my own replacement using LINQ, but it seems like this library targets .NET 2.0, so I can't upstream the change. Is there any particular reason for that?

Sample - Create Port Rule fails

Adding a port rule in the sample Winforms application fails, and I believe would with any call to FirewallManager.Instance.CreatePortRule that includes the protocol. The problem occurs when the Protocol is set to {Any} with the port set. The error received is:

"Port number can only be specified for the UDP and TCP protocols."

However, the protocol isn't set to UDP or TCP before it is set to {Any} by the constructor tree for FirewallWASRuleWin8. The issue is on FirewallWASRule.cs:76, where the protocol is set to {Any} before the Property Initializer in the original constructor call back at FirewallWAS.cs:166 is executed.

Issue setting RemoteAddresses of a FirewallRule with a range of IPv6 addresses

For the following code

rule.RemoteAddresses = remoteAddresses;

when assigning an array of remoteAddresses which includes an IPv6 address range eg
1234:1030:20e:3::6f/127
start IP 1234:1030:20e:3::6e
last IP 1234:1030:20e:3::6f

it fails to set the remoteAddresses property and throws an exception

Exception Stack Trace
" at WindowsFirewallHelper.COMInterop.INetFwRule.set_RemoteAddresses(String value)\r\n at WindowsFirewallHelper.FirewallRules.FirewallWASRule.set_RemoteAddresses(IAddress[] value) in C:\Users\s_fal\Documents\Personal\Open-Source Projects\WindowsFirewallHelper\WindowsFirewallHelper\FirewallRules\FirewallWASRule.cs:line 584\r\n at FirewallService.CreateFirewallRule(String name, FirewallAction action, FirewallDirection direction, FirewallProtocol protocol, UInt16[] destinationPortsList, IAddress[] remoteAddresses, IAddress[] localAddresses) in ...

This works fine when the IPv6 CIDR is /128 eg 1234:1030:20e:3::6f/128

Images for context

MicrosoftTeams-image
MicrosoftTeams-image (1)

IPV6 problem with new WindowsFirewallHelper.Addresses.NetworkAddress(objIP);

Attempting to create new WindowsFirewallHelper.Addresses.NetworkAddress from a System.Net.IPAddress object that is using an IPV6 address of: 2a04:4e42:400::323
(this is one of the DNS entries for CNN.COM incidentally).

Example:
var systemIP = IPAddress.Parse("2a04:4e42:400::323"); var fwhelperIP = new WindowsFirewallHelper.Addresses.NetworkAddress(systemIP);

This throws an error "Addresses of different family can not be used."

I also notice the System.Net.IPAddress object throws a SocketException error when trying to access the .Address property which may be related.

Seems like this should work. Thoughts?

Basic Example doesnt work

You wrote

var rule = FirewallManager.Instance.CreateApplicationRule(
    @"MyApp Rule",
    FirewallAction.Allow,
    @"C:\MyApp.exe"
);
rule.Direction = FirewallDirection.Outbound;
FirewallManager.Instance.Rules.Add(rule);

is the basic example for adding a new rule, I get the Error that the FireWallProfiles profiles is missing.
So I added before the rule name

FirewallManager.Instance.GetProfile().Type
But I get exception that E_ACCESSDENIED for creating a new rule.

FirewallRule objects fail to serialize

It is caused by an underlying failure of the IAddress [] to properly serialize.

Here's a minimum viable demo of the broken behavior:

using System;
using System.Linq;
using Newtonsoft.Json;
using WindowsFirewallHelper;

namespace FirewallHelperTest
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (IFirewallRule rule in FirewallManager.Instance.Rules.ToArray())
            {
                Console.WriteLine(JsonConvert.SerializeObject(rule));
            }
        }
    }
}

Which results in:

Newtonsoft.Json.JsonSerializationException
  HResult=0x80131500
  Message=Error getting value from 'ScopeId' on 'WindowsFirewallHelper.Addresses.SingleIP'.
  Source=Newtonsoft.Json
  StackTrace:
   at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)

Inner Exception 1:
SocketException: The attempted operation is not supported for the type of object referenced

You don't need to serialize the whole Rule for this behavior. I isolated each field to determine it was the addresses. For example, this also will not work:
JsonConvert.SerializeObject(rule.LocalAddresses)

Problem creating ICMP rules [Help Wanted] (again!)

Hi,

Today I've updated a legacy project from v1.4.6592.8627 to v2.1.4.81

Most of my code continues to work, but I'm unable to suss how to create a rule to allow ICMP.

Back in 2019 in issue #12 you helped me and gave me the following example.

Dim Rule = New WindowsFirewallHelper.FirewallAPIv2.Rules.StandardRule("NAME2", FirewallAction.Allow, FirewallDirection.Inbound, FirewallProfiles.Domain)
Rule.Protocol = FirewallProtocol.ICMPv4
Rule.RemoteAddresses = {WindowsFirewallHelper.Addresses.SingleIP.Parse("192.168.0.1")}
FirewallManager.Instance.Rules.Add(Rule)

I've been unable to find how to replicate this functionality in v2 of your library. I'd be most grateful if you could assist me!

Cheers

Steve

Problem setting LocalPorts / RemotePorts [Help Wanted]

' 1st Test Case
Dim Rule As IRule = FirewallManager.Instance.CreateApplicationRule(FirewallManager.Instance.GetProfile().Type, "Test Name", FirewallAction.Allow, "MyApp.exe")
Rule.Direction = FirewallDirection.Inbound
Rule.RemoteAddresses = {WindowsFirewallHelper.Addresses.SingleIP.Parse("192.168.0.1)}

Rule.LocalPorts = {CUShort(10050)} 'Test 1
Rule.RemotePorts = {CUShort(10050)} 'Test 2

' 2nd Test Case
Dim AllRulesTest = FirewallManager.Instance.Rules

For Each SingelRuleTest As IRule In AllRulesTest
If SingelRuleTest.LocalPorts.Length > 0 Then
Console.WriteLine("{0}, {1}, {2}", SingelRuleTest.Name, SingelRuleTest.LocalPorts, SingelRuleTest.Profiles.ToString(), SingelRuleTest.RemoteAddresses.ToString)
Rule.LocalPorts = SingelRuleTest.LocalPorts 'Test 3 - You'd think this would work as its taking a copy of LocalPorts from an existing rule.
End If

Next

All attempts to set LocalPorts or RemotePorts results in an exception "Value does not fall within the expected range."

Any advice gratefully received.

Rule.Name returns unexpected string after assigning to Rule.RemoteAddresses

Assume a rule named: "Remote Desktop - User Mode (TCP-In)"

var objRule = (from obj in FirewallManager.Instance.Rules where obj.Direction == FirewallDirection.Inbound && obj.Name == Default.RuleName orderby obj.Name select obj).FirstOrDefault();

Before assignment:
objRule.Name == "Remote Desktop - User Mode (TCP-In)"

A list of IPs is assigned:
objRule.RemoteAddresses=List AddressList;

Unexpectedly - Immediately after the assignment :
objRule.Name== "@FirewallAPI.dll,-28775 "

Reloading the rule returns the expected name:
var objRuleRefreshed = (from obj in FirewallManager.Instance.Rules where obj.Direction == FirewallDirection.Inbound && obj.Name == Default.RuleName orderby obj.Name select obj).FirstOrDefault();
objRuleRefreshed.Name"Remote Desktop - User Mode (TCP-In)"

This may be an issue with Windows firewall API rather than WindowsFirewallHelper, but it concerns me that subsequent property assignments to the same rule object may fail if the rule's name property has changed for some reason. I think this bears further examination...

How to specify remote IP address

How do you specify a remote IP address as part of the scope of an outbound rule? Example, I want to create a rule for an app that blocks outbound connections to a specific IP address.

Assigning IPV6 Localhost address ::1 to RemoteAddresses throws exception

When one of the addresses in the array of IAddress that is assigned to Rule.RemoteAddresses is ::1 an exception is thrown. ::1 is IPV6 for LocalHost.
IPV4 127.0.0.1 works fine.

Example assignment. NewIPs is an array of IAddress:
objRule.RemoteAddresses = NewIPs.ToArray();

Here's the list of IP addresses in NewIPs. Note the last one is ::1
IP addresses:173.35.205.201,99.248.70.97,66.96.146.81,::1

Here's the exception and stacktrace:

Exception from HRESULT: 0xD000000D at NetFwTypeLib.INetFwRule.set_RemoteAddresses(String remoteAddrs)
at WindowsFirewallHelper.FirewallAPIv2.Rules.StandardRule.set_RemoteAddresses(IAddress[] value)
at FWManagerService.FirewallJobProcessor.ApplyAuthorizedRemoteAddresses(List`1 lstAuthIPs) in D:\VBapps\FWmanager\FWManagerService\Code\FirewallJobProcessor.cs:line 291

Windows Firewall Service requires restart for RDP to work (Details inside)

Using: Windows 7 Embedded Standard SP1

Hey guys, I am trying to get RDP to work correctly. I have opened all the necessary firewall ports and predefined rules in the inbound rules list and enabled all the necessary GPO's and registry items.

For some reason, even though Windows Firewall is set to automatically start, and the service itself says "started," but for the rules to actually apply correctly, restarting the service works and I am able to RDP into the device.

I have checked msconfig to see if the service is enabled on startup, and it is.

Any help would be appreciated. Thanks!

`InvalidComObjectException` is thrown when executing in a STA

Hi.

Thank you for WindowsFirewallHelper.

An InvalidComObjectException is thrown when executing in a STA.

I expected to be able to call FirewallManager in a STA.

I've attached a reproducible Visual Studio 2015 project here:

WindowsFirewallHelperTests.zip

It contains a unit test with ClassInitialize and ClassCleanup methods that access FirewallManager.Instance.Rules.

It also contains a testsettings file which is configured to execute tests in a STA.

In Visual Studio, select Test > Test Settings > Select Test Settings File, and open the Local.testsettings file.

When run, the test will succeed, but the following is displayed in the Output window, under the Tests view:

------ Run test started ------
Class Cleanup method UnitTest1.ClassCleanup failed. Error Message: System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used.. Stack Trace:     at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
   at NetFwTypeLib.INetFwPolicy2.get_Rules()
   at WindowsFirewallHelper.FirewallAPIv2.Firewall.SyncRules()
   at WindowsFirewallHelper.FirewallAPIv2.Firewall.get_Rules()
   at WindowsFirewallHelperTests.UnitTest1.ClassCleanup() in c:\users\rami.abughazaleh\documents\visual studio 2015\Projects\WindowsFirewallHelperTests\WindowsFirewallHelperTests\UnitTest1.cs:line 18

========== Run test finished: 1 run (0:00:03.0169385) ==========

The exception occurs in the ClassCleanup method.

If you manually edit Local.testsettings, change
<ExecutionThread apartmentState="STA"/> to <ExecutionThread apartmentState="MTA"/>, and then re-run the test, it will still succeed, but the exception is not thrown.

I expected the exception to not get thrown in the ClassCleanup method.

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.