Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

*=> Add rules to firewall programmatically (using Firewall API): #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions ScreenTask/FirewallConf.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetFwTypeLib;

namespace ScreenTask
{
class FirewallConf
{
public void AddRule(String name, String Description,
NET_FW_ACTION_ Action, NET_FW_RULE_DIRECTION_ Direction, String LocalPort,
bool Enabled = true, int Protocole = 6, String RemoteAdresses = "localsubnet", String ApplicationName = "ScreenTask")
{
Type Policy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false);
INetFwPolicy2 FwPolicy = (INetFwPolicy2)Activator.CreateInstance(Policy2);
INetFwRules rules = FwPolicy.Rules;
//Delete if exist to avoid deplicated rules
DeleteRule(name);
Type RuleType = Type.GetTypeFromProgID("HNetCfg.FWRule");
INetFwRule rule = (INetFwRule)Activator.CreateInstance(RuleType);

rule.Name = name;
rule.Description = Description;
rule.Protocol = Protocole;// TCP/IP
rule.LocalPorts = LocalPort;
rule.RemoteAddresses = RemoteAdresses;
rule.Action = Action;
rule.Direction = Direction;
rule.ApplicationName = ApplicationName;
rule.Enabled = true;
//Add Rule
rules.Add(rule);
}
public void DeleteRule(String RuleName)
{
Type Policy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false);
INetFwPolicy2 FwPolicy = (INetFwPolicy2)Activator.CreateInstance(Policy2);
INetFwRules rules = FwPolicy.Rules;

rules.Remove(RuleName);
}
}
}
12 changes: 12 additions & 0 deletions ScreenTask/ScreenTask.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="FirewallConf.cs" />
<Compile Include="frmMain.cs">
<SubType>Form</SubType>
</Compile>
Expand Down Expand Up @@ -102,6 +103,17 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<COMReference Include="NetFwTypeLib">
<Guid>{58FBCF7C-E7A9-467C-80B3-FC65E8FCCA08}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
Expand Down
20 changes: 20 additions & 0 deletions ScreenTask/ScreenTask.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ScreenTask", "ScreenTask.csproj", "{4C0A04E9-E7C5-4F57-AA86-2551D5136566}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4C0A04E9-E7C5-4F57-AA86-2551D5136566}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4C0A04E9-E7C5-4F57-AA86-2551D5136566}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4C0A04E9-E7C5-4F57-AA86-2551D5136566}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4C0A04E9-E7C5-4F57-AA86-2551D5136566}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
16 changes: 8 additions & 8 deletions ScreenTask/frmMain.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 12 additions & 34 deletions ScreenTask/frmMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using NetFwTypeLib;

namespace ScreenTask
{
Expand Down Expand Up @@ -286,44 +287,21 @@ private Task AddFirewallRule(int port)
{
return Task.Run(() =>
{

string cmd = RunCMD("netsh advfirewall firewall show rule \"Screen Task\"");
if (cmd.StartsWith("\r\nNo rules match the specified criteria."))
{
cmd = RunCMD("netsh advfirewall firewall add rule name=\"Screen Task\" dir=in action=allow remoteip=localsubnet protocol=tcp localport=" + port);
if (cmd.Contains("Ok."))
{
Log("Screen Task Rule added to your firewall");
}
}
else
{
cmd = RunCMD("netsh advfirewall firewall delete rule name=\"Screen Task\"");
cmd = RunCMD("netsh advfirewall firewall add rule name=\"Screen Task\" dir=in action=allow remoteip=localsubnet protocol=tcp localport=" + port);
if (cmd.Contains("Ok."))
{
Log("Screen Task Rule updated to your firewall");
}
FirewallConf cnf = new FirewallConf();

try
{
cnf.AddRule("Screen Task", "Allow incoming network traffic", NET_FW_ACTION_.NET_FW_ACTION_ALLOW,
NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN, port+"");
Log("Screen Task Rule added to your firewall");
}
catch (Exception ex)
{
Log(ex.Message);
}
});

}
private string RunCMD(string cmd)
{
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/C " + cmd;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
string res = proc.StandardOutput.ReadToEnd();
proc.StandardOutput.Close();

proc.Close();
return res;
}
private void Log(string text)
{
txtLog.Text += DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " : " + text + "\r\n";
Expand Down