File: //var/opt/nydus/ops/customer_local_ops/operating_system/powershell/configure_port.ps1
param([Parameter(Mandatory)] [Int] $port,
[Parameter(Mandatory)] [String] $action)
function Ensure-NetFirewallRule {
param($displayName, $direction, $action, $protocol, $localPort)
if(Get-NetFirewallRule -DisplayName $displayName -ea SilentlyContinue){
Remove-NetFirewallRule -DisplayName $displayName
}
New-NetFirewallRule -DisplayName $displayName -Direction $direction -Action $action -Protocol $protocol -LocalPort $localPort
}
if ($action -eq "open") {
"Configuring firewall to open port $port"
$ruleName = "Open TCP $port"
Ensure-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Action Allow -Protocol TCP -LocalPort $port
netsh advfirewall firewall set rule name=$ruleName new localport=$port
# Remove any blocks. NOTE: The spaces in the rule names are required. That's how
# the rules were created by OH for the images, so need to keep them consistent.
Remove-NetFirewallRule -DisplayName "Block TCP $port " -ea SilentlyContinue
} elseif ($action -eq "close") {
"Configuring firewall to close port $port"
# Remove instances of the open port.
Remove-NetFirewallRule -DisplayName "Open TCP $port" -ea SilentlyContinue
# Block the port
$ruleName = "Block TCP $port "
Ensure-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Action Block -Protocol TCP -LocalPort $port
netsh advfirewall firewall set rule name=$ruleName new localport=$port
} else {
"Unknown action $action"
exit 1
}