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

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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); 

回答1:

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.



回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!