Search code examples
c#permissionswindows-firewallasp.net-core-middleware

Access denied when adding rule to Windows firewall (INetFwPolicy2) with C# from Core Middleware program


I'm trying to add a rule to Windows firewall in .Net Core Middleware (httpHandler) written in C# . The code looks like this:

INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
 var rule = firewallPolicy.Rules.Item("IPBan_0"); 
 string[] addrs = rule.RemoteAddresses.ToString().Split(',');
 if (Array.IndexOf(addrs, $"{ip}/255.255.255.255") == -1)
 {
     rule.RemoteAddresses += $",{ip}/255.255.255.255";  <--  Error Here 
 }

I assume I have to give "something" elevated privileges but not sure if I can give them to this firewallPolicy or the whole program... which I'd like to avoid if I could. I tried specifying the admin user in this web's basic settings but that didn't help.

What do I need to do in order to get this working?


Solution

  • Changing the firewall rules requires elevated permissions - for very good reasons. When the code runs in a web server process, that web server needs to have elevated permission, which is independent from the rights the user might have on the served web page.

    While it is possible to run a web server with admin rights, this is generally a bad idea, because it could make it easier for hackers to break into the server and take full control of it, so this should really only be used if there's no other way.