Search This Blog

Thursday, October 1, 2020

Windows 10 Firewall Ports

From time to time I have to open a port to do something and close it back up when I'm done. As I do this fairly often (but not often enough to memorize) I created this recipe. There is an example using Docker below.


ugh! an error! what to do?



Background Information...


How to do this by the Windows user Interface (UI)

https://www.google.com/search?q=windows+10+firewall+enable+localhost%3A80+traffic

How to do this with Powershell

https://www.google.com/search?q=powershell+TCP+Port+80+in+Windows+Firewall 

https://docs.microsoft.com/en-us/powershell/module/netsecurity/new-netfirewallrule?view=win10-ps

https://serverfault.com/questions/883266/powershell-how-open-a-windows-firewall-port


 

Powershell 


Open the port


New-NetFirewallRule -DisplayName "Allow inbound TCP port 81" -Direction inbound -LocalPort 81 -Protocol TCP -Action Allow
Name                  : {af16f2f3-3221-4191-8c5a-f44a5f60ca58}
DisplayName           : Allow inbound TCP port 81


Test (while something is listening on the port)


 Get-NetFirewallRule -Name '{af16f2f3-3221-4191-8c5a-f44a5f60ca58}'

    ** You can also see this in the Windows firewall inbound rules

$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.Connect("localhost","81")
$tcp.Connected
True


Close the port back up


Remove-NetFirewallRule -Name '{af16f2f3-3221-4191-8c5a-f44a5f60ca58}'

** If you test again, you should get a failure (or, your listening port was not blocked already). And, the control panel, on refresh, will show the rule is missing.

You're done! 



Example


As a semi-practical example, Start a Docker container, test and clean up. For this to be a real example, you would have to imagine that port 81 was the blocked port. On port 80, I got stuff running there already. So, I did this on port 81.


Open the Port


New-NetFirewallRule -DisplayName "Allow inbound TCP port 81" -Direction inbound -LocalPort 81 -

Start the getting-started container


docker run -d -p 81:80 docker/getting-started
6d44c9240e688b69a212fe24e58d2302b658bfcbcee787030943b04f12cde38b

Test that the container is running and on the proper port.


docker ps
CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS                NAMES
6d44c9240e68        docker/getting-started   "/docker-entrypoint.…"   6 seconds ago       Up 4 seconds        0.0.0.0:81->80/tcp   goofy_elion

Test the port via Powershell


(New-Object System.Net.Sockets.TCPClient –Argument "localhost","81").Connected
True

Open page in local browser http://localhost:81

 

Hooray! It works!   : ) 


Clean up the container


docker stop 6d44c9240e68
6d44c9240e68

Remove the firewall rule by Powershell


Remove-NetFirewallRule -Name '{af16f2f3-3221-4191-8c5a-f44a5f60ca58}'



You're done again!