Security Series: App Service IP Restrictions

> How to manage IP rules "at scale" using the Azure CLI
Cover Image for Security Series: App Service IP Restrictions

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 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.

Aristocratic

Overview

Imagine you have a list of IP 200 addresses that you want to allow access to your App Service. For some reason, 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:

  1. How to format the IP list
  2. Where to store the IP list
  3. How to get the IP list into the script
  4. 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.


_10
[
_10
{
_10
"ip": "192.168.1.1",
_10
"description": "John Doe home IP"
_10
},
_10
{
_10
"ip": "192.168.1.2",
_10
"description": "Jane Doe work IP"
_10
}
_10
]

Where to Store the IP List

You can store the IP list in a number of different places. Considerations to keep in mind are:

  1. The format of the list
  2. The size of the list (the storage location may have character / size limits)
  3. 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.
  4. The ability to "version" the list
  5. 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:

  1. Key Vault
  2. Blob Storage
  3. Code repo (not recommended)
  4. DevOps variables
  5. 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.


_191
# Fetch IPs from external source; in this case, an API endpoint that returns the list of IPs and descriptions in JSON format
_191
Write-Host "Fetching IPs from some external source..."
_191
$response = Invoke-RestMethod -Uri ${env:IP_LIST_ENDPOINT} -Method GET -Headers @{
_191
"Content-Type" = "application/json"
_191
}
_191
if (-not $response) {
_191
throw "Failed to fetch IPs from source."
_191
}
_191
_191
Write-Host "Successfully fetched IPs"
_191
_191
# Parse the response into a list of IPs and descriptions
_191
$allowedIPList = foreach ($item in $response.items.ip_addresses) {
_191
[PSCustomObject]@{
_191
IP = $item.ip
_191
Description = $item.description
_191
}
_191
}
_191
_191
# Print the list of IPs to the console.
_191
$allowedIPList | Format-Table -AutoSize
_191
_191
if ($allowedIPList.Count -eq 0) {
_191
Write-Host "No IPs to update."
_191
exit
_191
}
_191
_191
# TODO: make this dynamic
_191
$resourceGroupName = "mc-xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
_191
$appName = "mc-xxxxxx-xxxx-xxxx-xxxx-xxxx-cm"
_191
_191
# Fetch the existing IP restrictions
_191
# Note that Azure CLI has read limits per hour per subscription
_191
$existingRestrictions = az webapp config access-restriction show `
_191
--resource-group $resourceGroupName `
_191
--name $appName `
_191
--query "ipSecurityRestrictions" | ConvertFrom-Json
_191
_191
# Sample output (when not using --query "ipSecurityRestrictions" ):
_191
# {
_191
# "ipSecurityRestrictions": [
_191
# {
_191
# "action": "Allow",
_191
# "additional_properties": "",
_191
# "description": null,
_191
# "headers": null,
_191
# "ip_address": "AzureDevOps",
_191
# "name": "AzureDevOps",
_191
# "priority": 100,
_191
# "subnet_mask": null,
_191
# "subnet_traffic_tag": null,
_191
# "tag": "ServiceTag",
_191
# "vnet_subnet_resource_id": null,
_191
# "vnet_traffic_tag": null
_191
# },
_191
# {
_191
# "action": "Allow",
_191
# "additional_properties": "",
_191
# "description": null,
_191
# "headers": null,
_191
# "ip_address": "AzureCloud",
_191
# "name": "AzureCloud",
_191
# "priority": 110,
_191
# "subnet_mask": null,
_191
# "subnet_traffic_tag": null,
_191
# "tag": "ServiceTag",
_191
# "vnet_subnet_resource_id": null,
_191
# "vnet_traffic_tag": null
_191
# },
_191
# {
_191
# "action": "Allow",
_191
# "additional_properties": "",
_191
# "description": "Allow all access",
_191
# "headers": null,
_191
# "ip_address": "Any",
_191
# "name": "Allow all",
_191
# "priority": 2147483647,
_191
# "subnet_mask": null,
_191
# "subnet_traffic_tag": null,
_191
# "tag": null,
_191
# "vnet_subnet_resource_id": null,
_191
# "vnet_traffic_tag": null
_191
# }
_191
# ],
_191
# "ipSecurityRestrictionsDefaultAction": "Allow",
_191
# "scmIpSecurityRestrictions": [
_191
# {
_191
# "action": "Allow",
_191
# "additional_properties": "",
_191
# "description": "Allow all access",
_191
# "headers": null,
_191
# "ip_address": "Any",
_191
# "name": "Allow all",
_191
# "priority": 2147483647,
_191
# "subnet_mask": null,
_191
# "subnet_traffic_tag": null,
_191
# "tag": null,
_191
# "vnet_subnet_resource_id": null,
_191
# "vnet_traffic_tag": null
_191
# }
_191
# ],
_191
# "scmIpSecurityRestrictionsDefaultAction": "Allow",
_191
# "scmIpSecurityRestrictionsUseMain": true
_191
# }
_191
_191
Write-Host "Existing App Service IP restrictions (JSON):"
_191
$existingRestrictions | ConvertTo-Json | Write-Host
_191
_191
# Priority min value is 0 and max is 2147483647 -- multiple rules can have the same priority
_191
$priority = 100
_191
_191
# 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
_191
$allowedServiceTags = @("AzureDevOps", "AzureCloud")
_191
foreach ($tag in $allowedServiceTags) {
_191
$existingTag = $existingRestrictions | Where-Object { $_.tag -eq "ServiceTag" -and $_.name -eq $tag }
_191
_191
if ($null -ne $existingTag) {
_191
Write-Output "Service Tag: $tag already exists. Skipping..."
_191
continue
_191
}
_191
_191
Write-Output "Attempting to add Service Tag: $tag"
_191
try {
_191
# Note that there is an Azure CLI limit of 1,200 write operations per hour per subscription
_191
az webapp config access-restriction add `
_191
--resource-group $resourceGroupName `
_191
--name $appName `
_191
--rule-name $tag `
_191
--priority $priority `
_191
--action Allow `
_191
--service-tag $tag | Out-Null
_191
$priority += 10
_191
} catch {
_191
throw "Failed to add Service Tag. Error: $_"
_191
}
_191
}
_191
_191
Write-Host "Calculating which IPs need to be added..."
_191
$allowedIPsToAdd = $allowedIPList | Where-Object {
_191
$ip = $_.IP
_191
_191
if ([string]::IsNullOrWhiteSpace($ip)) {
_191
Write-Host "Skipping empty IP address"
_191
return $false
_191
}
_191
_191
-not ($existingRestrictions | Where-Object {
_191
($_.ip_address -eq $ip -or $_.ip_address -eq "$ip/32") -and $_.tag -ne "ServiceTag"
_191
})
_191
}
_191
_191
if ($allowedIPsToAdd.Count -eq 0) {
_191
Write-Host "All allowed IPs are already in the Azure App Service"
_191
exit
_191
}
_191
_191
Write-Host "$($allowedIPsToAdd.Count) IPs will be added to the Azure App Service"
_191
Write-Host "Allowed IPs to add (JSON):"
_191
$allowedIPsToAdd | ConvertTo-Json | Write-Host
_191
_191
foreach ($allowedIP in $allowedIPsToAdd) {
_191
$allowedIPAddress = $allowedIP.IP
_191
$allowedIPDescription = $allowedIP.Description
_191
_191
$ruleName = $allowedIPDescription
_191
_191
# Use IP address as rule name if no description is provided
_191
if ([string]::IsNullOrWhiteSpace($ruleName)) {
_191
$ruleName = $allowedIPAddress
_191
}
_191
_191
# Note that the rule name is required, and it must not be longer than 32 characters
_191
$ruleName = $ruleName.Substring(0, [Math]::Min(32, $ruleName.Length))
_191
_191
Write-Output "Adding IP: $allowedIPAddress with rule name: $ruleName"
_191
try {
_191
# Note that there is an Azure CLI limit of 1,200 write operations per hour per subscription
_191
az webapp config access-restriction add `
_191
--resource-group $resourceGroupName `
_191
--name $appName `
_191
--rule-name $ruleName `
_191
--description $allowedIPDescription `
_191
--priority $priority `
_191
--action Allow `
_191
--ip-address $allowedIPAddress | Out-Null
_191
_191
$priority += 10
_191
} catch {
_191
throw "Failed to add IP. Error: $_"
_191
}
_191
}

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.

Play smart,

-MG


More Stories

Cover Image for Troubleshooting 502 Responses in Azure App Services

Troubleshooting 502 Responses in Azure App Services

> App Services don't support all libraries

Cover Image for SPE Script Performance & Troubleshooting

SPE Script Performance & Troubleshooting

> Script never ends or runs too slow? Get in here.

Cover Image for How to Run Old Versions of Solr in a Docker Container

How to Run Old Versions of Solr in a Docker Container

> Please don't make me install another version of Solr on my local...

Cover Image for Tips for Forms Implementations

Tips for Forms Implementations

> And other pro tips

Cover Image for Script: Boost SIF Certificate Expiry Days

Script: Boost SIF Certificate Expiry Days

> One simple script that definitely won't delete your system32 folder

Cover Image for Content Editor Search Bar Not Working

Content Editor Search Bar Not Working

> Sometimes it works, sometimes not

Cover Image for NextJS: Unable to Verify the First Certificate

NextJS: Unable to Verify the First Certificate

> UNABLE_TO_VERIFY_LEAF_SIGNATURE

Cover Image for NextJS: Access has been blocked by CORS policy

NextJS: Access has been blocked by CORS policy

> CORS is almost as much of a nuisance as GDPR popups

Cover Image for Don't Ignore the HttpRequestValidationException

Don't Ignore the HttpRequestValidationException

> Doing so could be... potentially dangerous

Cover Image for Ideas For Docker up.ps1 Scripts

Ideas For Docker up.ps1 Scripts

> Because Docker can be brittle

Cover Image for On Mentorship and Community Contributions

On Mentorship and Community Contributions

> Reflections and what I learned as an MVP mentor

Cover Image for JSS: Reducing Bloat in Multilist Field Serialization

JSS: Reducing Bloat in Multilist Field Serialization

> Because: performance, security, and error-avoidance

Cover Image for Early Returns in React Components

Early Returns in React Components

> When and how should you return early in a React component?

Cover Image for Year in Review: 2022

Year in Review: 2022

> Full steam ahead

Cover Image for JSS + TypeScript Sitecore Project Tips

JSS + TypeScript Sitecore Project Tips

> New tech, new challenges

Cover Image for Tips for New Sitecore Developers

Tips for New Sitecore Developers

> If I had more time, I would have written a shorter letter

Cover Image for Super Fast Project Builds with Visual Studio Publish

Super Fast Project Builds with Visual Studio Publish

> For when solution builds take too long

Cover Image for NextJS: Short URL for Viewing Layout Service Response

NextJS: Short URL for Viewing Layout Service Response

> Because the default URL is 2long4me

Cover Image for Symposium 2022 Reflections

Symposium 2022 Reflections

> Sitecore is making big changes

Cover Image for Add TypeScript Type Checks to RouteData fields

Add TypeScript Type Checks to RouteData fields

> Inspired by error: Conversion of type may be a mistake because neither type sufficiently overlaps with the other.

Cover Image for Tips for Applying Cumulative Sitecore XM/XP Patches and Hotfixes

Tips for Applying Cumulative Sitecore XM/XP Patches and Hotfixes

> It's probably time to overhaul your processes

Cover Image for Sitecore Symposium 2022

Sitecore Symposium 2022

> What I'm Watching 👀

Cover Image for Hello World

Hello World

> Welcome to the show

Cover Image for Critical Security Bulletin SC2024-001-619349 Announced

Critical Security Bulletin SC2024-001-619349 Announced

> And other scintillating commentary

Cover Image for Azure PaaS Cache Optimization

Azure PaaS Cache Optimization

> App Services benefit greatly from proper configuration

Cover Image for NextJS/JSS Edit Frames Before JSS v21.1.0

NextJS/JSS Edit Frames Before JSS v21.1.0

> It is possible. We have the technology.

Cover Image for On Sitecore Development

On Sitecore Development

> Broadly speaking

Cover Image for On Sitecore Stack Exchange (SSE)

On Sitecore Stack Exchange (SSE)

> What I've learned, what I see, what I want to see