how to create a firewall rule in .net standard 2.0 which can Support in linux?

89 views Asked by At

Currently we are using NetFwTypeLib COMReference for adding a firewall rule to out application ,but it working only on Windows

public static bool AddRule(Firewall Rule){
            INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRule.Description = rule.RuleDescription;
            firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            firewallRule.Enabled = true;
            firewallRule.ApplicationName = rule.ApplicationPath;
            firewallRule.RemoteAddresses = "LocalSubnet";
            firewallRule.InterfaceTypes = "All";
            firewallRule.Name = rule.RuleName;

            switch (rule.Protocol)
            {
                case FirewallRule.ProtocolType.TCP:
                    firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; break;
                case FirewallRule.ProtocolType.UDP:
                    firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; break;
                default:
                    throw new ArgumentOutOfRangeException("rule", "The Protocol property of the firewall rule contains an invalid value!");
            }

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

} this peace of code only Supported in Windows so How can I replace this peace of code into other library so our code will work on linux as well .

1

There are 1 answers

1
vatbub On

There is no library to cover all firewall products. As mentioned in the comments, most users on Windows use the built-in Windows Firewall. Some use other products like ZoneAlarm. The same is true for Linux: Ubuntu has ufw, other distros use iptables. And even then, nobody forces you to use ufw on Ubuntu, you could use an entirely different firewall if you wanted to. Each firewall product has a different API and you need to take care of them individually.