Restrict the Assignment of Public IPs on Azure VMs

In this Microsoft Azure blog post, we will show how to restrict the assignment of Public IPs on Azure VMs.

Exposing virtual machines directly to the internet via public IP can open the door to many unnecessary security vulnerabilities.

In this post, we will show how you could prevent the assignment of IPs to VMs using Azure Policy.

Azure Policy allows us to apply built-in and out-of-the-box compliance policies to Azure resources. We can also create custom policies for more advanced compliance requirements.

This post will focus on applying a built-in policy that restricts the assignment of public IPs to VMs in a specific subscription.

Restrict the Assignment of Public IPs on Azure VMs

To create a policy, Open the Azure Policy console

Click on Definitions

In the search box, paste the following text “Network interfaces should not have public IPs” and click on the policy in the search results window.

Azure Policy Definitions screen

From the policy page, Click on Assign

Select the scope and complete the policy configuration.

Block public ips using Azure policy

Under the Remediation tab, please tick the box to create a system-managed identity to allow Azure policy to tag resources with their compliance status.

Add an informative message about non-compliance if someone tries creating a public IP.

message

Finish the configuration steps and deploy the policy.

Azure Policy Code

The following PowerShell code will do the same as using the Azure Policy console.

# Login to Azure
Connect-AzAccount

# Select your subscription
Select-AzSubscription -SubscriptionId <Your-Subscription-Id>

# Define the policy
$policyDefinition = New-AzPolicyDefinition -Name "restrict-public-ip" -DisplayName "Restrict Public IP Addresses" -description "This policy restricts the assignment of public IPs to Network Interfaces" 
-Policy '{
    "if": {
        "allOf": [
            {
                "field": "type",
                "equals": "Microsoft.Network/networkInterfaces"
            },
            {
                "field": "Microsoft.Network/networkInterfaces/ipConfigurations[*].publicIpAddress.id",
                "exists": true
            }
        ]
    },
    "then": {
        "effect": "deny"
    }
}'

# Assign the policy to a scope
New-AzPolicyAssignment -Name "restrict-public-ip-assignment" -Scope "/subscriptions/<Your-Subscription-Id>" -PolicyDefinition $policyDefinition

Conclusion

In this post, we discussed how to add extra security to your Azure environment using Azure Policy and block the assignment of external IPs.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.