Justin Tolchin
Justin Tolchin

Reputation: 463

Dynamically block IP address to azure cloud service

We have an Azure cloud service (classic) that is our web app. How can we tell the service to block specific IP's on all instances?

I know we can block using IIS 8+ Dynamic IP Restrictions (DIPR), when set through the web.config file. Configuring Dynamic IP Restrictions

2 problems with this is that 1) We cannot add to the always block list from within the app and 2) Even if I could get that working, it would only be on that instance.

Is there no way to block/IP Filter traffic from the portal? And can it be set from within our Cloud Service?

Upvotes: 1

Views: 1289

Answers (1)

Joey Cai
Joey Cai

Reputation: 20127

Is there no way to block/IP Filter traffic from the portal? And can it be set from within our Cloud Service?

Each time your instance starts it will look at the endpoints which have been configured for the Role and open the required ports in the Firewall. What we'll do in our code is simply disable these rules and create new rules which are restricted to a few IP addresses / IP address ranges.

The core of this solution is the IPAddressRestrictionManager.cs class, that parses settings from the ServiceConfiguration.cscfg (which you can modify while the application is deployed) and modifies the Firewall on each instance.

First you need to install the NuGet package:

PM> Install-Package WindowsAzure.IPAddressRestriction

If you want to link the IPAddressRestrictionManager to your ServiceConfiguration you'll need to add the following settings to your Role:

enter image description here

The syntax for the settings isn't too hard to understand:

IPAddressRestriction.Enabled = true or false

IPAddressRestriction.Settings = = or =- (delimiter between ports is ";")

Finally you need to hook everything up in your WebRole/WorkerRoler.cs

public class WebRole : RoleEntryPoint  
{
    private IPAddressRestrictionManager restrictionManager;

    public override bool OnStart()
    {
        RoleEnvironment.Changing += OnRoleEnvironmentChanging;
        ConfigureIPAddressRestrictions();
        return base.OnStart();
    }

    private void ConfigureIPAddressRestrictions()
    {
        if (restrictionManager == null)
            restrictionManager = new IPAddressRestrictionManager();

        restrictionManager.RemoveRestrictions();
        if (restrictionManager.IsEnabledInConfiguration())
            restrictionManager.ApplyFromConfiguration();
    }

    /// <summary>
    /// Force restart of the instance.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void OnRoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
    {
        if (e.Changes.Any(o => o is RoleEnvironmentChange))
            e.Cancel = true;
    }
}

For more details, you could refer to this article.

Upvotes: 1

Related Questions