Created
January 10, 2017 14:02
-
-
Save dazfuller/407587159a2b29bd54e17c7354d10e7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.DESCRIPTION | |
A runbook which finds unrestricted inbound RDP rules on the standard RDP port and | |
changes their action to Deny | |
.NOTES | |
AUTHOR: @dazfuller | |
LASTEDIT: Jan 10, 2017 | |
#> | |
workflow DisableRDPRules | |
{ | |
$connectionName = "AzureRunAsConnection" | |
try | |
{ | |
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName | |
"Logging into Azure..." | |
Login-AzureRmAccount ` | |
-ServicePrincipal ` | |
-TenantId $servicePrincipalConnection.TenantId ` | |
-ApplicationId $servicePrincipalConnection.ApplicationId ` | |
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint | |
} | |
catch | |
{ | |
if (!$servicePrincipalConnection) | |
{ | |
$errorMessage = "Connection $connectionName not found." | |
throw $errorMessage | |
} | |
else | |
{ | |
Write-Error -Message $_.Exception | |
throw $_.Exception | |
} | |
} | |
# Get each resource group | |
$resourceGroups = Get-AzureRmResourceGroup | |
ForEach -Parallel ($rg in $resourceGroups) | |
{ | |
# Get NSGs in the resource group | |
$networkSecurityGroups = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $rg.ResourceGroupName | |
ForEach ($nsg in $networkSecurityGroups) | |
{ | |
# Find rules which are on the standard RDP rule allowing all external traffic in | |
$securityRules = $nsg.SecurityRules | Where-Object -FilterScript { ($_.Access -eq "Allow") -and ($_.DestinationPortRange -eq "3389") -and ($_.SourceAddressPrefix -match "^\*|Internet.*$") } | |
# For each rule found, modify it so that it becomes denied | |
ForEach ($securityRule in $securityRules) | |
{ | |
Write-Output "Rule found allowing unrestricted inbound traffic on standard RDP port for NSG $($nsg.Id)" | |
# Read the rule back in | |
$rule = Get-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name $securityRule.Name | |
# Change the rules configuration and apply it to the NSG | |
Set-AzureRmNetworkSecurityRuleConfig ` | |
-NetworkSecurityGroup $nsg ` | |
-Name $rule.Name ` | |
-Description "Rule disabled by azure automation runbook" ` | |
-Access Deny ` | |
-Protocol $rule.Protocol ` | |
-Direction $rule.Direction ` | |
-Priority $rule.Priority ` | |
-SourceAddressPrefix $rule.SourceAddressPrefix ` | |
-SourcePortRange $rule.SourcePortRange ` | |
-DestinationAddressPrefix $rule.DestinationAddressPrefix ` | |
-DestinationPortRange $rule.DestinationPortRange | Set-AzureRmNetworkSecurityGroup | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment