0

I need to add a firewall rule with my WPF program. In Powershell i have a working solution:

New-NetFirewallRule -DisplayName $Description -Direction Inbound -Action Allow -Profile Any -EdgeTraversalPolicy Allow -Protocol TCP -LocalPort 80, 443.

Is quite simple.

What is the equivalent in C#? netsh? I found this https://stackoverflow.com/a/29652140/10194386:

System.Diagnostics.Process.Start("netsh.exe", "whatever you would need to write as parameters");

Is there a better solution?

Thanks a lot!

Edit:

I tryed the link from @Cpt.Whale stackoverflow.com/a/34018032/7411885

private void btn_set_FW_Click(object sender, RoutedEventArgs e)
        {
            Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
            var currentProfiles = fwPolicy2.CurrentProfileTypes;

            // Let's create a new rule
            INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            inboundRule.Enabled = true;
            //Allow through firewall
            inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            //Using protocol TCP
            inboundRule.Protocol = 6; // TCP
                                      
            inboundRule.LocalPorts = "81"; //Port 81
            //Name of rule
            inboundRule.Name = "MyRule";
            // ...//
            inboundRule.Profiles = currentProfiles;

            // Now add the rule
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            firewallPolicy.Rules.Add(inboundRule);
        }

But i get some errors:

CS1061 - "INetFwRule2" does not contain a definition for "Protocol". CS1061 - "INetFwRule2" does not contain a definition for "LocalPorts". CS1061 - "INetFwRule2" does not contain a definition for "Name". CS1061 - "INetFwRule2" does not contain a definition for "Profiles". CS5103 - Argument "1": Conversion of "MyAPP.INetFwRule2" to "NetFwTypeLib.INetFwRule" not possible.

where is my mistake?

Wishy
  • 39
  • 5
  • Does this answer your question? [Execute PowerShell Script from C# with Commandline Arguments](https://stackoverflow.com/questions/527513/execute-powershell-script-from-c-sharp-with-commandline-arguments) – Charlieface Jun 20 '22 at 13:15
  • The following may also be helpful: https://stackoverflow.com/questions/58211358/how-to-automate-either-powershell-or-powershell-core-for-same-machine/58211901#58211901 – Tu deschizi eu inchid Jun 20 '22 at 13:25
  • @Charlieface Thanks for this link. But in the answer he still run a extra script, right? – Wishy Jun 20 '22 at 13:32
  • i am looking for the easyest way to add a firewall rule to the system by clicking on a button in my wpf app. is there nothin like registryKey: Example: `using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) { using (var subKey = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\etc", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl)) { subKey.SetValue("MyKey", "1", RegistryValueKind.DWord); } }` – Wishy Jun 20 '22 at 13:45
  • If you want to keep it entirely in C#, then you could follow the example here using `NetFwTypeLib`: https://stackoverflow.com/a/34018032/7411885 – Cpt.Whale Jun 20 '22 at 16:38
  • Not sure why you are getting those errors, the interface definitely has those properties https://learn.microsoft.com/en-us/windows/win32/api/netfw/nn-netfw-inetfwrule. Perhaps you didn't import the type library correctly – Charlieface Jun 21 '22 at 10:14
  • maybe this is my problem: "The COM tab lists all COM components that are available for referencing. If you want to add a reference to a registered COM DLL that contains an internal manifest, unregister the DLL first. Otherwise, Visual Studio adds the assembly reference as an ActiveX control instead of as a native DLL." found here: [link]https://learn.microsoft.com/en-us/visualstudio/ide/how-to-add-or-remove-references-by-using-the-reference-manager?view=vs-2022 – Wishy Jun 21 '22 at 11:46
  • My Problem was the Project Target Framework! I used .NET Framework 4.8, but whit .NET 6.0 i have no Errors! My only Problem is now that my rules use multiple ports and a have no clue how to modify this: `inboundRule.LocalPorts = "81"; ` to something like `inboundRule.LocalPorts = "81, 443, 554";` this ist working `inboundRule.LocalPorts = "81-44";` but not what i need. Any help to put me in the right direction? – Wishy Jun 24 '22 at 06:57

1 Answers1

0

Finaly got success!

  • Make sure your WPF Project is .NET 6.0 and not .NET Framework 4.8.
  • Link to NetFwTypeLib
  • add using NetFwTypeLib;

and here my code (thanks to https://stackoverflow.com/a/34018032/10194386)

Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
//var currentProfiles = fwPolicy2.CurrentProfileTypes;

// Let's create a new rule
INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
inboundRule.Name = "My Firewall Rule";
inboundRule.Description = "FirewallRule Example for stack overflow.";
inboundRule.Enabled = true;    
inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;            
inboundRule.Protocol = 6; // TCP
inboundRule.LocalPorts = "42,80-82,"; //Multiple Ports, no Space allowed!
inboundRule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
inboundRule.EdgeTraversal = true;   

// Now add the rule
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(inboundRule);
Wishy
  • 39
  • 5