Search code examples
windowswindows-serviceswindows-firewallwindows-firewall-api

Creating a rule with the Windows Firewall API that applies to all applications run by a service


I'm trying set up a firewall rule for a Windows service to deny all inbound and outbound TCP and UDP connections except a whitelist of hosts and ports using the Windows Service Hardening API, following the VBScript example here.

Now, this service may spawn new processes (as it is a continuous integration build and test agent), so it's not sufficient to just set NewOutboundRule.ApplicationName = "%systemDrive%\WINDOWS\system32\svchost.exe" as in the example script above - I need a rule to applies to all applications run by the service.

However, if I try and set up a new inbound rule where the allegedly optional ApplicationName property isn't specified on the INetFw interface, the call to add the new rule fails (at the line wshRules.Add NewOutboundRule in the script above). Everything else is correct, as if I specify the ApplicationName, the call succeeds.

Is there some way to create rules that apply to all possible values of ApplicationName, or some alternative way of doing this?


Solution

  • After some experimentation, it turns out that the WSH rules work like this: The call to INetFwServiceRestriction::RestrictService (with restrictService=TRUE) only needs to contain the name of the primary executable which is called to start the service. If that process spawns a new process using any other executable, by default that new process has ALL inbound and outbound network connections blocked. This is true even if exceptions have been added for the primary executable via INetFwServiceRestriction::Rules.

    So, if secondary executables run by the service need network access, it's necessary to add explicit INetFwRule exceptions for these executables as well. This makes sense - the call to RestrictService blocks everything, and then a whitelist of exceptions which include the application names can be added.