Security Series: App Service IP Restrictions

Index
TLDR;
Azure App Service IP Restrictions are powerful and an easy win in terms of base security for Sitecore sites. However, the list of rules becomes unwieldy to manage when adding/removing/editing rules at scale. As developers, we are digital aristocrats, and we should not be burdened by the monotonous toil of pointing and clicking over 9000 times in one sitting. Instead, we'll use a PowerShell script within a dedicated Azure DevOps release pipeline to manage the rules.
Overview
Imagine you have a list of 200 IP addresses that you want to allow access to your App Service. Whether due to cost, complexity, or simply project constraints, you're not using a WAF such as Cloudflare or Front Door, so you're stuck with App Service IP Restrictions. There are a number of matters to figure out:
- How to format the IP list
- Where to store the IP list
- How to get the IP list into the script
- How to apply the IP list to the App Service
How to format the IP list
Presumably, each of your IP addresses will be accompanied with a description. This step is entirely up to you, but in my case I'm going with JSON. JSON ensures that the list is extensible and easy to parse.
[ { "ip": "192.168.1.1", "description": "John Doe home IP" }, { "ip": "192.168.1.2", "description": "Jane Doe work IP" }]Where to Store the IP List
You can store the IP list in a number of different places. Considerations to keep in mind are:
- The format of the list
- The size of the list (the storage location may have character / size limits)
- The editing experience -- where you store the list should be compatible with the format of the list. For example, editing JSON in a single line text field isn't a great experience and may be error prone.
- The ability to "version" the list
- The ability to reference and adjust the IPs depending on the environment (dev/test/prod)
Some options for where to store the IP list are:
- Key Vault
- Blob Storage
- Code repo (not recommended)
- DevOps variables
- Directly in the script that calls the Azure CLI
The Script
As mentioned previously, we'll use an Azure DevOps release pipeline with one step which is an inline PowerShell script. The script will fetch the IP list from the source, and then apply the IP list to the App Service using the Azure CLI. Beyond that, the code speaks for itself.
# Fetch IPs from external source; in this case, an API endpoint that returns the list of IPs and descriptions in JSON formatWrite-Host "Fetching IPs from some external source..."$response = Invoke-RestMethod -Uri ${env:IP_LIST_ENDPOINT} -Method GET -Headers @{ "Content-Type" = "application/json"}if (-not $response) { throw "Failed to fetch IPs from source."}
Write-Host "Successfully fetched IPs"
# Parse the response into a list of IPs and descriptions$allowedIPList = foreach ($item in $response.items.ip_addresses) { [PSCustomObject]@{ IP = $item.ip Description = $item.description }}
# Print the list of IPs to the console.$allowedIPList | Format-Table -AutoSize
if ($allowedIPList.Count -eq 0) { Write-Host "No IPs to update." exit}
# TODO: make this dynamic$resourceGroupName = "mc-xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"$appName = "mc-xxxxxx-xxxx-xxxx-xxxx-xxxx-cm"
# Fetch the existing IP restrictions# Note that Azure CLI has read limits per hour per subscription$existingRestrictions = az webapp config access-restriction show ` --resource-group $resourceGroupName ` --name $appName ` --query "ipSecurityRestrictions" | ConvertFrom-Json
# Sample output (when not using --query "ipSecurityRestrictions" ):# {# "ipSecurityRestrictions": [# {# "action": "Allow",# "additional_properties": "",# "description": null,# "headers": null,# "ip_address": "AzureDevOps",# "name": "AzureDevOps",# "priority": 100,# "subnet_mask": null,# "subnet_traffic_tag": null,# "tag": "ServiceTag",# "vnet_subnet_resource_id": null,# "vnet_traffic_tag": null# },# {# "action": "Allow",# "additional_properties": "",# "description": null,# "headers": null,# "ip_address": "AzureCloud",# "name": "AzureCloud",# "priority": 110,# "subnet_mask": null,# "subnet_traffic_tag": null,# "tag": "ServiceTag",# "vnet_subnet_resource_id": null,# "vnet_traffic_tag": null# },# {# "action": "Allow",# "additional_properties": "",# "description": "Allow all access",# "headers": null,# "ip_address": "Any",# "name": "Allow all",# "priority": 2147483647,# "subnet_mask": null,# "subnet_traffic_tag": null,# "tag": null,# "vnet_subnet_resource_id": null,# "vnet_traffic_tag": null# }# ],# "ipSecurityRestrictionsDefaultAction": "Allow",# "scmIpSecurityRestrictions": [# {# "action": "Allow",# "additional_properties": "",# "description": "Allow all access",# "headers": null,# "ip_address": "Any",# "name": "Allow all",# "priority": 2147483647,# "subnet_mask": null,# "subnet_traffic_tag": null,# "tag": null,# "vnet_subnet_resource_id": null,# "vnet_traffic_tag": null# }# ],# "scmIpSecurityRestrictionsDefaultAction": "Allow",# "scmIpSecurityRestrictionsUseMain": true# }
Write-Host "Existing App Service IP restrictions (JSON):"$existingRestrictions | ConvertTo-Json | Write-Host
# Priority min value is 0 and max is 2147483647 -- multiple rules can have the same priority$priority = 100
# Adding the AzureDevOps and AzureCloud service tags to the App Service to ensure that both Azure and Azure DevOps can still access the App Service$allowedServiceTags = @("AzureDevOps", "AzureCloud")foreach ($tag in $allowedServiceTags) { $existingTag = $existingRestrictions | Where-Object { $_.tag -eq "ServiceTag" -and $_.name -eq $tag }
if ($null -ne $existingTag) { Write-Output "Service Tag: $tag already exists. Skipping..." continue }
Write-Output "Attempting to add Service Tag: $tag" try { # Note that there is an Azure CLI limit of 1,200 write operations per hour per subscription az webapp config access-restriction add ` --resource-group $resourceGroupName ` --name $appName ` --rule-name $tag ` --priority $priority ` --action Allow ` --service-tag $tag | Out-Null $priority += 10 } catch { throw "Failed to add Service Tag. Error: $_" }}
Write-Host "Calculating which IPs need to be added..."$allowedIPsToAdd = $allowedIPList | Where-Object { $ip = $_.IP
if ([string]::IsNullOrWhiteSpace($ip)) { Write-Host "Skipping empty IP address" return $false }
-not ($existingRestrictions | Where-Object { ($_.ip_address -eq $ip -or $_.ip_address -eq "$ip/32") -and $_.tag -ne "ServiceTag" })}
if ($allowedIPsToAdd.Count -eq 0) { Write-Host "All allowed IPs are already in the Azure App Service" exit}
Write-Host "$($allowedIPsToAdd.Count) IPs will be added to the Azure App Service"Write-Host "Allowed IPs to add (JSON):"$allowedIPsToAdd | ConvertTo-Json | Write-Host
foreach ($allowedIP in $allowedIPsToAdd) { $allowedIPAddress = $allowedIP.IP $allowedIPDescription = $allowedIP.Description
$ruleName = $allowedIPDescription
# Use IP address as rule name if no description is provided if ([string]::IsNullOrWhiteSpace($ruleName)) { $ruleName = $allowedIPAddress }
# Note that the rule name is required, and it must not be longer than 32 characters $ruleName = $ruleName.Substring(0, [Math]::Min(32, $ruleName.Length))
Write-Output "Adding IP: $allowedIPAddress with rule name: $ruleName" try { # Note that there is an Azure CLI limit of 1,200 write operations per hour per subscription az webapp config access-restriction add ` --resource-group $resourceGroupName ` --name $appName ` --rule-name $ruleName ` --description $allowedIPDescription ` --priority $priority ` --action Allow ` --ip-address $allowedIPAddress | Out-Null
$priority += 10 } catch { throw "Failed to add IP. Error: $_" }}A few followup notes:
- The Azure CLI is slow. In my experience, each add operation took about 10 seconds, so this will eat up your release minutes.
- For the "Advanced tool site" (
your-app-service-cm.scm.azurewebsites.net/DebugConsole) restrictions, you can easily set it to use the same rules as the main site. Just set it and forget it in the Azure Portal.
Where This Method of Security Falls Short
- There is a limit of 512 access restriction rules, so use CIDR. Tie it to your internal IDP server. You can add rules for that.
- Updating via Azure CLI is slow.
- If you want to analyze requests that get served a 403 (which may be useful in some cases), you won't be able to see them neither in the Web Server Logs log stream, nor in Application Insights requests.
Play smart,
-MG





