Wednesday 5 February 2020

Powershell to clear allowed IP list and allow all IPs

Powershell to clear allowed IP list and allow all IPs


I found a few posts on setting specific IPs that are allowed through the ESXi Firewall for services such as SSH and Web Access for instance. What I lacked was a way to manipulate those when I realized I'd made a typo. I had inconsistent settings starting to develop and I wanted to script a way to reset to a blank page again!

The script below achieves that. I've also come up with an audit script to verify any rogue servers that have different settings from the default for two services sshServer and webAccess, the ones I was interested in. With lockdown mode it's probably a bit overkill but we get admins leaving things in an unconfigured way and having some extra insurance was desired.

If you have 80-100 hosts, this can save a lot of time picking through the gui!

This script removes the two subnets and returns the firewall to allow all IPs:

$Services = "webAccess","sshServer"
$remoteIP1 = "192.168.1.0/24"
$remoteIP2 = "10.1.1.0/24"
foreach($esx in Get-VMHost){
    $esxcli = Get-EsxCli -VMHost $esx
    foreach($service in $services){
        $esxcli.network.firewall.ruleset.allowedip.remove($remoteIP1,$service)
$esxcli.network.firewall.ruleset.allowedip.remove($remoteIP2,$service)
        }
    }
foreach($esx in Get-VMHost){
    $esxcli = Get-EsxCli -VMHost $esx
    foreach($service in $services){
        $esxcli.network.firewall.ruleset.set($true,$true,$service)
        }
    }

This scripts audits for these two services to sohow if they allow all IPs and reports any deviation:

$Services = "webAccess","sshServer"
foreach($esx in Get-VMHost){
    $esxcli = Get-EsxCli -VMHost $esx
$esx       
$esxcli.network.firewall.ruleset.allowedip.list('sshServer')
        $esxcli.network.firewall.ruleset.allowedip.list('webAccess')
    }

That should give you the name of the host that still lists IPs and doesn't list {All}:

Name                 ConnectionState PowerState NumCpu CpuUsageMhz CpuTotalMhz   MemoryUsageGB   MemoryTotalGB Version
----                 --------------- ---------- ------ ----------- -----------   -------------   ------------- -------
labesx01            ... Connected       PoweredOn      32         291       95760          12.188         255.654   6.7.0

AllowedIPAddresses : {All}
Ruleset            : sshServer


AllowedIPAddresses : {All}
Ruleset            : webAccess