Adam Heeg
Adam Heeg

Reputation: 1714

How to edit Firewall rules in code successfully on a Worker Role Instance?

I'm trying some code that works locally but it doesn't work on my cloud instance. I assume it may be permissions related, but I'm unable to fix it yet. Here is what I have which works when I debug my worker role locally, but nothing happens when it is published (on staging right now).

string strCmdText = string.Format("advfirewall firewall add rule name=\"BlockU\" protocol=any dir=in action=block remoteip={0}", ip);

ProcessStartInfo psi = new ProcessStartInfo("netsh.exe", strCmdText);
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
try
{
    Process.Start(psi);
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
}

I have also tried using the

psi.Verb = "runas"; 

but that did not help either.

Finally I tried the firewall api like so. This also worked locally, but threw an access denied error on the last line.

INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
 inboundRule.Enabled = true;
 inboundRule.RemoteAddresses = ip;
 inboundRule.InterfaceTypes = "All";
 inboundRule.Protocol = (int)NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
 inboundRule.Name = "BlockU Part 2";
 //inboundRule.Profiles = currentProfiles;
 inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
 // Now add the rule

 INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
 firewallPolicy.Rules.Add(inboundRule);

Upvotes: 2

Views: 1263

Answers (2)

Adam Heeg
Adam Heeg

Reputation: 1714

I found over on the azure forums that I need to enable my Worker Role to run with elevated privileges. This can be done in the ServiceDefinition.csdef file by adding the following attribute to the WorkerRole element

<WorkerRole name="CloudService.Worker" vmsize="ExtraSmall"
            enableNativeCodeExecution="true">

and also by adding a

<Runtime executionContext="elevated" />

element inside the WorkerRole element.

Both sets of code ran successfully with the configuration changes.

Upvotes: 2

Mouad Cherkaoui
Mouad Cherkaoui

Reputation: 78

I've found an interesting post in msdn blogs that uses a library which simplify the configuration of firewall rule, may be it will resolve your issue,

http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx

on a

Upvotes: 0

Related Questions