Audit Azure Network Security Groups / Backup NSG Rulebases
- Charles Smith
- Oct 5, 2020
- 2 min read
For security auditing, backups and also troubleshooting it can be very helpful to export your NSGs to CSV files
Here is a script using the Get-AzNetworkSecurityGroup that can loop through defined Azure subscriptions, and then find an export all NSGs and their rulebases to a CSV file.
##### Author Charles Smith - CVSConsult Ltd 2020 #####
#define subscriptions in scope - edit this with your subscription name(s)
$subs = @("SUBSCRIPTION1","SUBSCRIPTION2")
#Set date variable
$datestring = (Get-Date).ToString("s").Replace(":","-")
#loop through each subscription
Foreach ($sub in $subs) {
select-azsubscription -subscriptionid $sub
#Get NSGs in the subscription to an object
$nsgs = Get-AzNetworkSecurityGroup
$nsgcount = $nsgs.count
#Loop through each NSG in the subscription:
$count = 1
Foreach ($nsg in $nsgs) {
write-progress -activity "Exporting NSGs from $sub to CSV" -status "NSG $count of $nsgcount" -percentcomplete (($count/$nsgcount) *100)
#Get the VNET & Subnet from NSG:
$vnet = $null
$subnet = $null
try { $vnet = ((($nsg.subnets.id).split("/virtualNetworks/"))[1]).split("/subnets/")[0] } catch { write-host $nsg.name " not associated with any subnets" }
try { $subnet = ((($nsg.subnets.id).split("/virtualNetworks/"))[1]).split("/subnets/")[1] } catch {}
#Loop through each rule in the NSG:
$Rules = $nsg.SecurityRules
foreach ($Rule in $Rules) {
#Convert arrays to single cell values wrapped with "
$srcips = $rule.SourceAddressPrefix -join ','
$srcips = "`"$srcips`""
$srcports = $rule.SourcePortrange -join ','
$srcports = "`"$srcports`""
$dstips = $rule.DestinationAddressPrefix -join ','
$dstips = "`"$dstips`""
$dstports = $rule.DestinationPortrange -join ','
$dstports = "`"$dstports`""
#Create a new PS object for the rule and populate with the NSG rule data
$obj = $null
$obj = New-Object PSObject
$obj | Add-Member -type NoteProperty -Name Subscription -Value $sub
$obj | Add-Member -type NoteProperty -Name NSG -Value $nsg.Name
$obj | Add-Member -type NoteProperty -Name VNET -Value $vnet
$obj | Add-Member -type NoteProperty -Name Subnet -Value $subnet
$obj | Add-Member -type NoteProperty -Name RuleName -Value $rule.Name
$obj | Add-Member -type NoteProperty -Name Priority -Value $rule.Priority.ToString()
$obj | Add-Member -type NoteProperty -Name Direction -Value $rule.Direction
$obj | Add-Member -type NoteProperty -Name Access -Value $rule.Access
$obj | Add-Member -type NoteProperty -Name SourceAddress -Value $srcips
$obj | Add-Member -type NoteProperty -Name SourcePort -Value $srcports
$obj | Add-Member -type NoteProperty -Name DestinationAddress -Value $dstips
$obj | Add-Member -type NoteProperty -Name DestinationPort -Value $dstports
$obj | Add-Member -type NoteProperty -Name Description -Value $rule.Description
$obj | export-csv c:\temp\nsg-export-$datestring.csv -append
}
$count++
}
}
Comments