Skip to content

Instantly share code, notes, and snippets.

@machv
Created October 15, 2021 08:43
Show Gist options
  • Save machv/608175b1c561a58032cbef94f69772cb to your computer and use it in GitHub Desktop.
Save machv/608175b1c561a58032cbef94f69772cb to your computer and use it in GitHub Desktop.
Update NSG with Exchange Online SMTP endpoints
$nsgName = "litware-sccm012021-05-10T04-44-28-34"
$nsgResourceGroup = "litware-infra"
$priority = 200
$sourceAddressPrefix = "*" # zdrojový server/prefix pro odesílání SMTP přes ExO
#region Helper functions
function Set-NsgRule {
param(
$nsg,
$smtpEndpoint,
$addresses,
$family
)
$ruleName = "$($smtpEndpoint.serviceArea.ToLower())-$($smtpEndpoint.id)-$family"
$existingRule = Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name $ruleName -ErrorAction SilentlyContinue
if($existingRule -and $existingRule.DestinationAddressPrefix -ne $addresses) {
Remove-AzNetworkSecurityRuleConfig -Name $ruleName -NetworkSecurityGroup $nsg | Out-Null
}
$nsg | Add-AzNetworkSecurityRuleConfig -Direction Outbound -Name $ruleName -Priority $priority -Protocol Tcp -SourceAddressPrefix $sourceAddressPrefix -DestinationAddressPrefix $addresses -DestinationPortRange $smtpEndpoint.tcpPorts -SourcePortRange * -Access Allow | Out-Null
$global:priority += 1
$priority
}
function Get-FamilyIpAddresses {
param(
[parameter(Mandatory = $true)]
$Addresses,
[parameter(Mandatory = $true)]
[ValidateSet("Ipv4", "Ipv6")]
$AddressFamily
)
if($AddressFamily -eq "Ipv4") {
$Addresses | Where-Object { $_.Contains(".") }
}
if($AddressFamily -eq "Ipv6") {
$Addresses | Where-Object { $_.Contains(":") }
}
}
#endregion
#region Update NSG
$nsg = Get-AzNetworkSecurityGroup -Name $nsgName -ResourceGroupName $nsgResourceGroup
$endpoints = Invoke-RestMethod -Method Get -Uri "https://endpoints.office.com/endpoints/worldwide?clientrequestid=3fa58f87-1b7c-4d82-a802-1737f2745ac0&ServiceAreas=Exchange"
$smtpEndpoints = $endpoints | Where-Object { $_.tcpPorts.Split(",").Contains("25") }
foreach($smtpEndpoint in $smtpEndpoints) {
# NSG accept addresses only from the same protocol family
$v4Addresses = Get-FamilyIpAddresses -Addresses $smtpEndpoint.ips -AddressFamily Ipv4
if($v4Addresses -and $v4Addresses.Count -gt 0) {
Set-NsgRule -family "v4" -nsg $nsg -smtpEndpoint $smtpEndpoint -addresses $v4Addresses
}
$v6Addresses = Get-FamilyIpAddresses -Addresses $smtpEndpoint.ips -AddressFamily Ipv6
if($v6Addresses -and $v6Addresses.Count -gt 0) {
Set-NsgRule -family "v6" -nsg $nsg -smtpEndpoint $smtpEndpoint -addresses $v6Addresses
}
}
# Save changes
$nsg | Set-AzNetworkSecurityGroup
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment