Windows Server,  Windows XP

Quick And Dirty Windows Firewall Scripting

Here ya’ go!

netsh advfirewall firewall add rule name=”KryptedWebhook” dir=in protocol=tcp localport=8443 profile=private remoteip=any action=allow

Wait, what’s that?!?! Let’s break down the options I used here:

  • advfirewall: Yup, it’s the new firewall.
  • firewall: Yup, it’s a firewall.
  • add: I’m adding a new rule. I also could have used delete along with the rule name and removed one. Or show to see one. Or set to augment one.
  • rule: It’s all about rules. Each rule allows for a port and/or an action.
  • name: Every rule needs a unique name. Namespace conflicts will result in errors. If programmatically creating rules, I’ve found it undesirable to use a counter and instead moved to using GUIDs and a hash table.
  • dir: The direction traffic is flowing. In is for incoming traffic or out would be to block outgoing traffic.
  • protocol: Use the protocol, typically tcp or ump, but if pings, might be one of the icmps.
  • localport: The port that is being used (there’s also a remoteport operator for reflections).
  • profile: I mostly use profile of private.
  • remoteip: Set to any but could be set to a given IP for increased security (yes, I know people can spoof these – so your version of the word might be different.
  • action: I used allow, but could have been block (which denies traffic) or bypass.

For further security, I might add a security operator, to allow for an authentication string. You can

You might also need to allow traffic for a given app. To do so, let’s add a rule that does so, the only option for which not mentioned above is program, which is the path to the binary we’re allowing:

netsh advfirewall firewall add rule name="My Application" dir=in action=allow program="C:\kryptedscripts\kryptedcompiledwebapp.exe" enable=yes

To then see the rules and validate that your rules were indeed installed, use:

netsh advfirewall firewall show rule name=all

The reason I call this quick and dirty is that I’m really only covering a small subset of options. Additionally, it would be a bit more modern to do this via powershell using New-NetFirewallRule or one of the many, many other commandlets, such as Copy-NetFirewallRule, Enable-NetFirewallRule, Disable-NetFirewallRule, Get-NetFirewallAddressFilter, Get-NetFirewallApplicationFilter, Get-NetFirewallInterfaceFilter, Get-NetFirewallInterfaceTypeFilter, Get-NetFirewallPortFilter, Get-NetFirewallRule, Get-NetFirewallSecurityFilter, New-NetFirewallRule, Open-NetGPO (cause you can configure the firewall through a GPO), Remove-NetFirewallRule, Rename-NetFirewallRule, Save-NetGPO, Set-NetFirewallRule, Set-NetFirewallSetting, and Show-NetFirewallRule.