[PS SCRIPT]: Restrict Azure App Services network access to Cloudflare

Implementing Cloudflare caching & WAF secures your resources, but Azure App Services can still be accessed directly at each .azurewebsites.net domain, bypassing Cloudflare.

This script sets network restrictions on one or multiple Azure App Services limiting traffic from internet, allowing traffic only from Cloudflare’s static ip ranges. In this example, I’ve also added the Azure DevOps IP range.

Although Cloudflare’s IP ranges don’t change frequently, you could run this script on a recurring basis from an Azure Automation Account, ensuring restrictions are set for current and future app services.

#2024.03.26 - Jeremy Pot

Install-Module Az
Import-Module Az

$sites = get-azwebapp -ResourceGroupName "ResourceGroupName"

$publicranges = @((Invoke-WebRequest -Uri "https://www.cloudflare.com/ips-v4/#" -UseBasicParsing).Content)
$publicranges += (Invoke-WebRequest -Uri "https://www.cloudflare.com/ips-v6/#" -UseBasicParsing).Content
$publicranges += "" #azuredevops
$publicranges = $publicranges -split "`r?`n"

foreach ($site in $sites) {
    $accessrestrictions = (Get-AzWebAppAccessRestrictionConfig -ResourceGroupName $site.ResourceGroup -Name $site.Name)
    $i = [int]($accessrestrictions.MainSiteAccessRestrictions | select-object Priority | Sort-Object Priority -Descending)[1].Priority

    foreach ($publicrange in $publicranges) {
        if (!($publicrange.Contains("."))) {
        if (!($accessrestrictions.MainSiteAccessRestrictions.RuleName.Contains($publicrange))) {
            $i = $i + 5
            Add-AzWebAppAccessRestrictionRule -ResourceGroupName $site.ResourceGroup -WebAppName $site.Name -Name $publicrange -Action Allow -IpAddress $publicrange -Priority $i

    if ($accessrestrictions.MainSiteAccessRestrictions.RuleName.Contains("Allow all")) {
        $webapp = Get-AzResource -ResourceType Microsoft.Web/sites -ResourceGroupName $site.ResourceGroup -ResourceName $site.Name
        $webapp.Properties.siteConfig.ipSecurityRestrictionsDefaultAction = "Deny"
        $webapp.Properties.publicNetworkAccess = "Enabled"
        $webapp | Set-AzResource -Force
    Update-AzWebAppAccessRestrictionConfig -ResourceGroupName $site.ResourceGroup -Name $site.Name -ScmSiteUseMainSiteRestrictionConfig


No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *