Exemple #1
0
        /// <summary>
        /// Creates a Firewall rule. Use parameters to control name, port, direction and protocol.
        /// </summary>
        /// <param name="ruleName">Name of the rule.</param>
        /// <param name="portValue">Single port: "222". Range: "222-444".</param>
        /// <param name="isOut">true = outbound rule. False = inbound rule.</param>
        /// <param name="isUDP">true = UDP. False = TCP.</param>
        public static void CreateFWRule(string ruleName = "Firewall testing via C#", string portValue = "8000-8005", bool isOut = true, bool isUDP = true)
        {
            Type          tNetFwPolicy2   = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2       = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
            var           currentProfiles = fwPolicy2.CurrentProfileTypes;

            // Let's create a new FW rule.
            INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            // Block it through firewall
            inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;

            // Quick description for the rule.
            inboundRule.Description = "Used by the program Solo Enabler. Its use is to enable solo play in Destiny 2.";

            // Set the direction.
            inboundRule.Direction = isOut ? NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT : NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;

            // Make sure rule is enabled.
            inboundRule.Enabled = true;

            // Set the name of the FW rule
            inboundRule.Name = ruleName;

            // Make sure to set the protocol before the ports. TCP = 6. UDP = 17.
            inboundRule.Protocol = (int)(isUDP ? NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP : NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP);

            // Set the ports.
            inboundRule.RemotePorts = portValue;

            // Add the rule itself
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            firewallPolicy.Rules.Add(inboundRule);
        }
Exemple #2
0
        public static void BlockMatchmakingPorts()
        {
            //going to try out binding to socket manually without firewalls and seeing if that works



            //creating new rules
            INetFwRule2 OutBoundUDP = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            INetFwRule2 OutBoundTCP = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            INetFwRule2 InBoundUDP  = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            INetFwRule2 InBoundTCP  = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            //names
            OutBoundUDP.Name = OUT_UDP_NAME;
            OutBoundTCP.Name = OUT_TCP_NAME;
            InBoundUDP.Name  = IN_UDP_NAME;
            InBoundTCP.Name  = IN_TCP_NAME;

            //enabling
            OutBoundUDP.Enabled = true;
            OutBoundTCP.Enabled = true;
            InBoundUDP.Enabled  = true;
            InBoundTCP.Enabled  = true;

            //specifying block as action
            OutBoundUDP.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            OutBoundTCP.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            InBoundUDP.Action  = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            InBoundTCP.Action  = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;

            //setting UDP/TCP
            OutBoundUDP.Protocol = 17;
            OutBoundTCP.Protocol = 6;
            InBoundUDP.Protocol  = 17;
            InBoundTCP.Protocol  = 6;

            //specifying ports to block
            OutBoundUDP.RemotePorts = "27000-27100";
            OutBoundTCP.RemotePorts = "27000-27100";
            InBoundUDP.RemotePorts  = "27000-27100";
            InBoundTCP.RemotePorts  = "27000-27100";

            //direction
            OutBoundUDP.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            OutBoundTCP.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            InBoundUDP.Direction  = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            InBoundTCP.Direction  = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;

            //fetching firewall policy
            INetFwPolicy2 currentFWPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            //adding new rules
            currentFWPolicy.Rules.Add(OutBoundUDP);
            currentFWPolicy.Rules.Add(OutBoundTCP);
            currentFWPolicy.Rules.Add(InBoundUDP);
            currentFWPolicy.Rules.Add(InBoundTCP);

            MainPageViewModel.getInstance().SoloEnabled = true;
        }
Exemple #3
0
        // If BanIp = true then method add Block rule for ip address
        public static void AddFirewallRule(string ipaddress = "255.255.255.255", string RuleName = "BreakermindCom", bool BanIP = false)
        {
            string IP     = ipaddress;
            string IPName = RuleName + "_Allow_" + IP;

            if (BanIP)
            {
                IPName = RuleName + "_Ban_" + IP;
            }

            try
            {
                Type          tNetFwPolicy2   = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
                INetFwPolicy2 fwPolicy2       = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
                var           currentProfiles = fwPolicy2.CurrentProfileTypes;

                // Let's create a new rule
                INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                inboundRule.Enabled = true;
                //Allow through firewall
                inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                if (BanIP)
                {
                    inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                }
                //Using protocol TCP
                inboundRule.Protocol = 6;
                //Port 5555
                inboundRule.LocalPorts = "5555";
                //Name of rule
                inboundRule.Name = IPName;
                // profil
                inboundRule.Profiles = currentProfiles;
                // ip
                inboundRule.RemoteAddresses = IP;

                // Now add the rule
                INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
                firewallPolicy.Rules.Add(inboundRule);
                //firewallPolicy.Rules.Remove(IPName);

                if (BanIP)
                {
                    Console.WriteLine(IP + " Firewall Update Ban IP ... " + DateTime.UtcNow);
                }
                else
                {
                    Console.WriteLine(IP + " Firewall Update Allowed IP ... " + DateTime.UtcNow);
                }
            }
            catch (Exception r)
            {
                Console.WriteLine("Firewall error " + r);
            }
        }
Exemple #4
0
        public static void AddRule(string name, string address)
        {
            INetFwRule2 rule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            rule.Enabled         = true;
            rule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            rule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            rule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            rule.RemotePorts     = "80,443";
            rule.RemoteAddresses = address;
            rule.Name            = name;
            rule.Description     = "Removeo rule for blocking unwanted content.";
            firewallPolicy.Rules.Add(rule);
        }
Exemple #5
0
        public void Open(ushort port, string name)
        {
            INetFwRule2 firewallRule = getComObject <INetFwRule2>(INetFwRuleProgID);

            firewallRule.Description    = name;
            firewallRule.Name           = name;
            firewallRule.Action         = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRule.Enabled        = true;
            firewallRule.InterfaceTypes = "All";
            firewallRule.Protocol       = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            firewallRule.LocalPorts     = port.ToString();

            INetFwPolicy2 firewallPolicy = getComObject <INetFwPolicy2>(INetFwPolicy2ProgID);

            firewallPolicy.Rules.Add(firewallRule);
        }
Exemple #6
0
        public static void AddFirewallRuleIn(string ruleName, string ipRange)
        {
            Type          tNetFwPolicy2   = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2       = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
            var           currentProfiles = fwPolicy2.CurrentProfileTypes;
            INetFwRule2   inboundRule     = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            inboundRule.Enabled         = true;
            inboundRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            inboundRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            inboundRule.RemoteAddresses = ipRange;
            inboundRule.Name            = ruleName;
            inboundRule.Profiles        = currentProfiles;
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            firewallPolicy.Rules.Add(inboundRule);
        }
Exemple #7
0
 /// <summary>
 /// 防火墙放行
 /// </summary>
 /// <param name="name"></param>
 /// <param name="port"></param>
 /// <param name="protocol"></param>
 public static void NetFwAddPorts()
 {
     try
     {
         CmdRun("netsh firewall set portopening TCP 3389 ENABLE");
     }catch (Exception)
     {
         INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
         inboundRule.Enabled    = true;
         inboundRule.Action     = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
         inboundRule.Protocol   = 6;
         inboundRule.LocalPorts = "3389";
         inboundRule.Name       = "Access 3389";
         INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
         firewallPolicy.Rules.Add(inboundRule);
     }
 }
        private void MakeRule(string str, int protNumber, NET_FW_RULE_DIRECTION_ ruleDirection, string ruleName)
        {
            Type          tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2     = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);

            // Let's create a new rule
            INetFwRule2 Rule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            Rule.Enabled = true;


            NET_FW_RULE_DIRECTION_ direction = ruleDirection;

            Rule.Direction = direction; //Inbound
            Rule.Action    = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;

            Rule.Protocol = protNumber; // ANY/TCP/UDP

            try
            {
                Rule.RemoteAddresses = str;
            }
            catch (Exception)
            {
                MessageBox.Show("Can't add Rules. Maybe a Format failure?", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            //Rule.LocalPorts = "81"; //Port 81

            //Name of rule
            Rule.Name = ruleName;
            // ...//
            //Rule.Profiles = (int)NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_TYPE_MAX;

            // Now add the rule
            //INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            try
            {
                firewallPolicy.Rules.Add(Rule);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #9
0
        private static void SetFirewall()
        {
            Type          fwRule        = Type.GetTypeFromProgID("HNetCfg.FWRule");
            Type          tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2     = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);

            foreach (INetFwRule rule in fwPolicy2.Rules)
            {
                if (rule.Name == "ASinc")
                {
                    return;
                }
            }

            // create a new rule
            INetFwRule2 inboundTCPRule = (INetFwRule2)Activator.CreateInstance(fwRule);

            inboundTCPRule.Enabled = true;
            //Allow through firewall
            inboundTCPRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            //Using protocol TCP
            inboundTCPRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;

            inboundTCPRule.LocalPorts = "9528";
            inboundTCPRule.Name       = "ASinc";
            inboundTCPRule.Profiles   = fwPolicy2.CurrentProfileTypes;

            // create a new rule
            INetFwRule2 inboundUDPRule = (INetFwRule2)Activator.CreateInstance(fwRule);

            inboundUDPRule.Enabled = true;
            //Allow through firewall
            inboundUDPRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            //Using protocol UDP
            inboundUDPRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;;

            inboundUDPRule.LocalPorts = "9527";
            inboundUDPRule.Name       = "ASinc";
            inboundUDPRule.Profiles   = fwPolicy2.CurrentProfileTypes;

            // add the rule

            fwPolicy2.Rules.Add(inboundTCPRule);
            fwPolicy2.Rules.Add(inboundUDPRule);
        }
        public void addRule(string path, RuleAction ruleAction, RuleDirection ruleDir, RuleProtocol ruleProtoc)
        {
            string      appName     = path;
            INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            inboundRule.Enabled         = true;
            inboundRule.ApplicationName = appName;

            inboundRule.Protocol  = (int)ruleProtoc;
            inboundRule.Direction = (NET_FW_RULE_DIRECTION_)ruleDir;
            inboundRule.Profiles  = 7;
            inboundRule.Name      = "_BM_FW_" + ((int)ruleDir).ToString() + ((int)ruleAction).ToString() + ((int)ruleProtoc).ToString() + "_" + appName.Substring(appName.LastIndexOf(@"\") + 1, appName.Length - appName.LastIndexOf(@"\") - 5);
            inboundRule.Action    = (NET_FW_ACTION_)ruleAction;

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

            firewallPolicy.Rules.Add(inboundRule);
        }
Exemple #11
0
        internal static void AddRule(string Name, string Description, string Path)
        {
            Type          NetFwPolicy = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 FwPolicy    = (INetFwPolicy2)Activator.CreateInstance(NetFwPolicy);
            Type          NetFwRule   = Type.GetTypeFromProgID("HNetCfg.FwRule");
            INetFwRule2   FwRule      = (INetFwRule2)Activator.CreateInstance(NetFwRule);

            FwRule.Enabled         = true;
            FwRule.Name            = Name;
            FwRule.Description     = Description;
            FwRule.ApplicationName = Path;
            FwRule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
            FwRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            FwRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            FwRule.Profiles        = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
            FwRule.EdgeTraversal   = false;
            FwPolicy.Rules.Add(FwRule);
        }
Exemple #12
0
        public void CreateFirewallRule()
        {
            INetFwRule2 firewallRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            firewallRule.Action         = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRule.Description    = "Used to allow clients to connect to Island Server";
            firewallRule.Direction      = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            firewallRule.Enabled        = true;
            firewallRule.Protocol       = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            firewallRule.LocalPorts     = HostPort;
            firewallRule.Profiles       = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
            firewallRule.InterfaceTypes = "All";
            firewallRule.Name           = "Island Server";

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

            firewallPolicy.Rules.Add(firewallRule);
        }
Exemple #13
0
        public bool RemoveRule(INetFwRule2 entry)
        {
            try
            {
                // Note: if this is not set to null renam may fail as well as other sets :/
                entry.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY;

                // Note: the removal is done byname, howeever multiple rules may have the same name, WTF, so we set a temporary unique name
                entry.Name = "***_to_be_deleted_***";

                mFirewallPolicy.Rules.Remove(entry.Name);
            }
            catch (Exception err)
            {
                AppLog.Line("Failed to Remove rule: " + err.Message);
                return(false);
            }
            return(true);
        }
Exemple #14
0
        public static void BlockIPInFirewall(string sourceIP)
        {
            const string ruleName = "Block Malicious IP";

            string blockRange;

            if (sourceIP.Contains("."))
            {
                blockRange = sourceIP.Substring(0, sourceIP.LastIndexOf('.')) + ".0/24";
            }
            else
            {
                blockRange = sourceIP.Substring(0, sourceIP.LastIndexOf(':')) + ":0/112";
            }



            var firewallRule = GetFirewallRule(ruleName);

            if (firewallRule == null)
            {
                INetFwPolicy2 fwPolicy2       = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
                var           currentProfiles = fwPolicy2.CurrentProfileTypes;

                // Let's create a new rule

                INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                inboundRule.Name            = ruleName;
                inboundRule.Enabled         = true;
                inboundRule.Protocol        = 6; // TCP
                inboundRule.RemoteAddresses = blockRange;
                inboundRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;

                inboundRule.Profiles = currentProfiles;


                fwPolicy2.Rules.Add(inboundRule);
            }
            else
            {
                firewallRule.RemoteAddresses += "," + blockRange;
            }
        }
        // 参考链接:
        // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366418(v=vs.85).aspx
        // https://stackoverflow.com/questions/15409790/adding-an-application-firewall-rule-to-both-private-and-public-networks-via-win7
        // bing: hnetcfg.fwpolicy2 c#

        /// <summary>
        /// 添加一个应用程序完整路径到Windows防火墙的“受信”列表中
        /// </summary>
        /// <param name="path"></param>
        public static void AllowApplication(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (File.Exists(path) == false)
            {
                throw new FileNotFoundException("File not found: " + path);
            }

            string ruleName = Path.GetFileNameWithoutExtension(path);

            Type          tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2     = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);

            try {
                // 检查规则是否已存在
                if (fwPolicy2.Rules.Item(ruleName) != null)
                {
                    return;
                }
            }
            catch {// 如果规则不存在,会抛出异常,这里就直接吃掉异常
            }

            // 创建一个入站规则实例
            INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            inboundRule.Enabled = true;
            //设置为允许
            inboundRule.Action = NET_FW_ACTION.NET_FW_ACTION_ALLOW;
            //指定使用TCP协议
            inboundRule.ApplicationName = path;
            //规则名称
            inboundRule.Name = ruleName;
            // 规则影响范围(配置文件)
            inboundRule.Profiles = (int)NET_FW_PROFILE_TYPE2.NET_FW_PROFILE2_ALL;

            // 添加规则到防火墙
            fwPolicy2.Rules.Add(inboundRule);
        }
Exemple #16
0
        private void SetupFirewall()
        {
            INetFwPolicy2 p = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            try
            {
                INetFwRule2 pp = (INetFwRule2)p.Rules.Item("HHT Realtime Services");
            }
            catch (FileNotFoundException ex)
            {
                INetFwRule2 firewallRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRule.Action     = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                firewallRule.Direction  = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                firewallRule.Enabled    = true;
                firewallRule.Protocol   = 6;
                firewallRule.LocalPorts = "15267";
                firewallRule.Name       = "HHT Realtime Services";
                p.Rules.Add(firewallRule);
            }
        }
Exemple #17
0
        private static void AddFirewallRule()
        {
            Type          tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2     = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);

            List <INetFwRule> RuleList = new List <INetFwRule>();

            var currentProfiles = fwPolicy2.CurrentProfileTypes;

            foreach (INetFwRule rule in fwPolicy2.Rules)
            {
                if (rule.Name.IndexOf(_firewallRule) != -1)
                {
                    if (rule.LocalPorts == _port && rule.Profiles == currentProfiles)
                    {
                        rule.Enabled = true;
                        return;
                    }
                }
            }

            // Let's create a new rule
            INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            inboundRule.Enabled = true;
            //Allow through firewall
            inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            //Using protocol TCP
            inboundRule.Protocol = 6; // TCP
                                      //Port 81
            inboundRule.LocalPorts = _port;
            //Name of rule
            inboundRule.Name = _firewallRule;
            // ...//
            inboundRule.Profiles = currentProfiles;

            // Now add the rule
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            firewallPolicy.Rules.Add(inboundRule);
        }
Exemple #18
0
        /// <summary>
        /// Adds a rule to the firewall
        /// </summary>
        /// <param name="ruleName">The name of the rule to add</param>
        /// <param name="ruleGroup">The group under which the rule is added</param>
        /// <param name="protocol">The desired rule protocol</param>
        /// <param name="localPorts">The desired rule port</param>
        /// <param name="action">The desired rule action, to allow or block communications</param>
        /// <param name="profiles">The desired rule profile</param>
        public static void Add(string ruleName, string ruleGroup, int protocol = 6, string localPorts = "80", EFirewallRuleAction action = EFirewallRuleAction.Allowed, EFirewallProfiles profiles = EFirewallProfiles.All)
        {
            if (Exists(ruleName))
            {
                return;
            }
            Type          tNetFwPolicy2   = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2       = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
            var           currentProfiles = fwPolicy2.CurrentProfileTypes;

            // Let's create a new rule
            INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            inboundRule.Enabled = true;
            //Allow through firewall

            if (action == EFirewallRuleAction.Allowed)
            {
                inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            }
            else
            {
                inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            }
            //Using protocol TCP
            inboundRule.Protocol = 6; // TCP
                                      //Port 81
            inboundRule.LocalPorts = localPorts;
            //Name of rule
            inboundRule.Name = ruleName;
            // ...//
            inboundRule.Grouping = ruleGroup;
            inboundRule.Profiles = (int)profiles;

            // Now add the rule
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            firewallPolicy.Rules.Add(inboundRule);
        }
Exemple #19
0
        /// <summary>
        /// Add a rule in the windows firewall
        /// </summary>
        /// <param name="ipAddress"></param>
        public void AddRule(string ipAddress)
        {
            // Create rule
            INetFwRule2 rule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            rule.Name            = $"Firestar Access Block {ipAddress}";
            rule.Description     = "Block Incoming Connections from IP Address.";
            rule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            rule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            rule.Enabled         = true;
            rule.InterfaceTypes  = "All";
            rule.RemoteAddresses = ipAddress;

            // Add rule in the firewall
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            firewallPolicy.Rules.Add(rule);

            String msg = $"IP Address {ipAddress} Blocked Successfully!";

            Console.WriteLine(msg);
        }
Exemple #20
0
        // Add a rule at FireWall
        public static void ConfigureFirewall()
        {
            INetFwMgr icfMgr = null;

            try
            {
                Type TicfMgr = Type.GetTypeFromProgID("HNetCfg.FwMgr");
                icfMgr = (INetFwMgr)Activator.CreateInstance(TicfMgr);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Eroare");
            }

            try
            {
                Type          tNetFwPolicy2   = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
                INetFwPolicy2 fwPolicy2       = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
                var           currentProfiles = fwPolicy2.CurrentProfileTypes;

                INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                inboundRule.Enabled    = true;
                inboundRule.Action     = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                inboundRule.Protocol   = 6;
                inboundRule.LocalPorts = "12831";
                inboundRule.Name       = "Trojan_Final";
                inboundRule.Profiles   = currentProfiles;

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

                Console.WriteLine("Succes!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #21
0
        static bool BlockThisIP(string IpAddress, string Description)
        {
            try
            {
                //ipaddress is:
                Console.WriteLine("Range to be added to Firewall:{0}", IpAddress);

                Type          tNetFwPolicy2   = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
                INetFwPolicy2 fwPolicy2       = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
                var           currentProfiles = fwPolicy2.CurrentProfileTypes;

                // Let's create a new rule
                INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                inboundRule.Enabled = true;
                //Allow through firewall
                inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                //Using protocol ANY
                inboundRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
                //Name of rule
                inboundRule.Name            = Description + "_" + IpAddress;
                inboundRule.RemoteAddresses = IpAddress;                                                        //"255.255.255.255-255.255.255.255" for a range or single IP
                inboundRule.InterfaceTypes  = "ALL";
                inboundRule.Description     = Description + " " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); //Blocked from this date
                // inboundRule.Profiles = currentProfiles;

                // Now add the rule
                INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
                firewallPolicy.Rules.Add(inboundRule);

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Err:" + ex.Message);
                return(false);
            }
        }
        private static void FirewallActions(ToastArguments args, string fileName, string ruleNameComponent)
        {
            var           buttonSelection = args.First().Value;
            INetFwRule2   firewallRule    = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            INetFwPolicy2 operatePolicy   = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            var           existRule       = filteredRules.Any(x => x.Name.EndsWith(ruleNameComponent + " 出站连接"));

            if (existRule == false)
            {
                if (buttonSelection == "AllowConnection")
                {
                    var currentProfiles = fwPolicy2.CurrentProfileTypes;
                    firewallRule.Enabled         = true;
                    firewallRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
                    firewallRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                    firewallRule.ApplicationName = fileName;
                    firewallRule.Name            = "允许 " + ruleNameComponent + " 出站连接";
                    firewallRule.Profiles        = currentProfiles;
                    operatePolicy.Rules.Add(firewallRule);
                }
                else
                {
                    var currentProfiles = fwPolicy2.CurrentProfileTypes;
                    firewallRule.Enabled         = true;
                    firewallRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
                    firewallRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                    firewallRule.ApplicationName = fileName;
                    firewallRule.Name            = "阻止 " + ruleNameComponent + " 出站连接";
                    firewallRule.Profiles        = currentProfiles;
                    operatePolicy.Rules.Add(firewallRule);
                }
            }
            ReadAllFirewallRules();
            displayNotification = true;
            ToastNotificationManagerCompat.History.Clear();
        }
Exemple #23
0
        /// <summary>Returns the rule as a string using the same format as the group policy rules that are found in the registry</summary>
        public override string ToString()
        {
            //todo: rule.Interfaces
            //todo: rule.InterfaceTypes
            INetFwRule2 rule = this.rule;

            string rs = "v2.10";

            var aorder = new List <string> {
                "Action", "Active", "Dir", "Protocol", "Profile", "ICMP4", "ICMP6", "LPort", "LPort2_10", "RPort", "RPort2_10", "LA4", "LA6", "RA4", "RA6", "App", "Svc", "Name", "Desc", "EmbedCtxt", "Edge", "Defer"
            };
            var attributes   = new Dictionary <string, List <string> >();
            var strAddresses = new List <string> {
                "LocalSubnet", "DHCP", "DNS", "WINS", "DefaultGateway"
            };
            IPAddress address;
            var       curA = "";

            //required: if not present then "All"
            curA = "Profile";
            var fwProfiles = Enum.GetValues(typeof(NET_FW_PROFILE_TYPE2_));

            foreach (NET_FW_PROFILE_TYPE2_ fwProfile in fwProfiles)
            {
                if (((NET_FW_PROFILE_TYPE2_)rule.Profiles & fwProfile) == fwProfile)
                {
                    if (!attributes.ContainsKey(curA))
                    {
                        attributes.Add(curA, new List <string>());
                    }
                    attributes[curA].Add(curA + "=" + MSFirewall.getProfileName(fwProfile));
                }
            }
            if ((NET_FW_PROFILE_TYPE2_)rule.Profiles == NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL)
            {
                attributes.Remove(curA);
            }

            //optional
            if (rule.Grouping != null)
            {
                curA = "EmbedCtxt";
                attributes.Add(curA, new List <string> {
                    curA + "=" + rule.Grouping
                });
            }

            //required
            curA = "Name";
            attributes.Add(curA, new List <string> {
                curA + "=" + rule.Name
            });

            //required
            curA = "Action";
            attributes.Add(curA, new List <string> {
                curA + "=" + MSFirewall.getActionName(rule.Action)
            });

            //optional
            if (rule.Description != null)
            {
                curA = "Desc";
                attributes.Add(curA, new List <string> {
                    curA + "=" + rule.Description
                });
            }

            //required
            curA = "Dir";
            attributes.Add(curA, new List <string> {
                curA + "=" + MSFirewall.getDirectionName(rule.Direction)
            });

            if (rule.ApplicationName != null)
            {
                curA = "App";
                if (!attributes.ContainsKey(curA))
                {
                    attributes.Add(curA, new List <string>());
                }
                attributes[curA].Add(curA + "=" + rule.ApplicationName);
            }

            if (rule.serviceName != null)
            {
                curA = "Svc";
                if (!attributes.ContainsKey(curA))
                {
                    attributes.Add(curA, new List <string>());
                }
                attributes[curA].Add(curA + "=" + rule.serviceName);
            }

            if (rule.LocalPorts != "*" && rule.LocalPorts != null)
            {
                foreach (string r in rule.LocalPorts.Split(','))
                {
                    if (r == "IPHTTPS")
                    {
                        curA = "LPort2_10";
                        if (rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN)
                        {
                            attributes.Add(curA, new List <string>());
                            attributes[curA].Add(curA + "=IPTLSIn");
                            attributes[curA].Add(curA + "=IPHTTPSIn");
                        }
                        else
                        {
                            attributes.Add(curA, new List <string>());
                            attributes[curA].Add(curA + "=IPTLSOut");
                            attributes[curA].Add(curA + "=IPHTTPSOut");
                        }
                    }
                    else
                    {
                        curA = "LPort";
                        if (!attributes.ContainsKey(curA))
                        {
                            attributes.Add(curA, new List <string>());
                        }
                        attributes[curA].Add(curA + "=" + r);
                    }
                }
            }

            if (rule.LocalAddresses != null && rule.LocalAddresses != "*")
            {
                var ra = rule.LocalAddresses.Split(',');
                foreach (string r in ra)
                {
                    curA = "";
                    if (strAddresses.Contains(r))
                    {
                        curA = "LA4,LA6";
                    }
                    else if (IPAddress.TryParse(r, out address))
                    {
                        switch (address.AddressFamily)
                        {
                        case System.Net.Sockets.AddressFamily.InterNetwork:
                            curA = "LA4";
                            break;

                        case System.Net.Sockets.AddressFamily.InterNetworkV6:
                            curA = "LA6";
                            break;

                        default:
                            throw new Exception("Unknown remote address: {0}" + r);
                        }
                    }
                    else if (r.Contains(':'))
                    {
                        curA = "LA6";
                    }
                    else
                    {
                        curA = "LA4";
                    }

                    if (curA != "")
                    {
                        foreach (string a in curA.Split(','))
                        {
                            if (!attributes.ContainsKey(a))
                            {
                                attributes.Add(a, new List <string>());
                            }

                            var sub = false;
                            if (r.Contains('-'))
                            {
                                var rtest = r.Split('-');
                                if (rtest[0] == rtest[1])
                                {
                                    attributes[a].Add(a + "=" + rtest[0]);
                                    sub = true;
                                }
                            }
                            else if (r.Contains("/255.255.255.255"))
                            {
                                var rtest = r.Split('/');
                                attributes[a].Add(a + "=" + rtest[0]);
                                sub = true;
                            }

                            if (!sub)
                            {
                                attributes[a].Add(a + "=" + r);
                            }
                        }
                    }
                }
            }

            if (rule.RemotePorts != "*" && rule.RemotePorts != null)
            {
                foreach (string r in rule.RemotePorts.Split(','))
                {
                    if (r == "IPHTTPS")
                    {
                        curA = "RPort2_10";
                        if (rule.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN)
                        {
                            attributes.Add(curA, new List <string>());
                            attributes[curA].Add(curA + "=IPTLSIn");
                            attributes[curA].Add(curA + "=IPHTTPSIn");
                        }
                        else
                        {
                            attributes.Add(curA, new List <string>());
                            attributes[curA].Add(curA + "=IPTLSOut");
                            attributes[curA].Add(curA + "=IPHTTPSOut");
                        }
                    }
                    else
                    {
                        curA = "RPort";
                        if (!attributes.ContainsKey(curA))
                        {
                            attributes.Add(curA, new List <string>());
                        }
                        attributes[curA].Add(curA + "=" + r);
                    }
                }
            }

            //if any, not present
            if (rule.RemoteAddresses != null && rule.RemoteAddresses != "*")
            {
                var ra = rule.RemoteAddresses.Split(',');
                foreach (string r in ra)
                {
                    curA = "";
                    if (strAddresses.Contains(r))
                    {
                        curA = "RA4,RA6";
                    }
                    else if (IPAddress.TryParse(r, out address))
                    {
                        switch (address.AddressFamily)
                        {
                        case System.Net.Sockets.AddressFamily.InterNetwork:
                            curA = "RA4";
                            break;

                        case System.Net.Sockets.AddressFamily.InterNetworkV6:
                            curA = "RA6";
                            break;

                        default:
                            throw new Exception("Unknown remote address: {0}" + r);
                        }
                    }
                    else if (r.Contains(':'))
                    {
                        curA = "RA6";
                    }
                    else
                    {
                        curA = "RA4";
                    }

                    if (curA != "")
                    {
                        foreach (string a in curA.Split(','))
                        {
                            if (!attributes.ContainsKey(a))
                            {
                                attributes.Add(a, new List <string>());
                            }

                            var sub = false;
                            if (r.Contains('-'))
                            {
                                var rtest = r.Split('-');
                                if (rtest[0] == rtest[1])
                                {
                                    attributes[a].Add(a + "=" + rtest[0]);
                                    sub = true;
                                }
                            }
                            else if (r.Contains("/255.255.255.255"))
                            {
                                var rtest = r.Split('/');
                                attributes[a].Add(a + "=" + rtest[0]);
                                sub = true;
                            }

                            if (!sub)
                            {
                                attributes[a].Add(a + "=" + r);
                            }
                        }
                    }
                }
            }

            //if any, then no setting
            if (rule.Protocol != 256) //any
            {
                curA = "Protocol";
                if (!attributes.ContainsKey(curA))
                {
                    attributes.Add(curA, new List <string>());
                }
                attributes[curA].Add(curA + "=" + rule.Protocol);
            }

            //required
            curA = "Active";
            if (rule.Enabled)
            {
                attributes.Add(curA, new List <string> {
                    curA + "=TRUE"
                });
            }
            else
            {
                attributes.Add(curA, new List <string> {
                    curA + "=FALSE"
                });
            }

            //if not present, then false
            if (rule.EdgeTraversal)
            {
                curA = "Edge";
                attributes.Add(curA, new List <string> {
                    curA + "=TRUE"
                });
            }

            //if any, then no setting
            curA = "Defer";
            if (rule.EdgeTraversalOptions > 0)
            {
                if (rule.EdgeTraversalOptions == (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_APP)
                {
                    if (!attributes.ContainsKey(curA))
                    {
                        attributes.Add(curA, new List <string>());
                    }
                    attributes[curA].Add(curA + "=App");
                }
                else if (rule.EdgeTraversalOptions == (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_ALLOW)
                {
                    //do nothing because rule.EdgeTraversal should be set to true already
                }
                else
                {
                    if (!attributes.ContainsKey(curA))
                    {
                        attributes.Add(curA, new List <string>());
                    }
                    attributes[curA].Add(curA + "=" + rule.EdgeTraversalOptions);
                }
            }

            if (rule.IcmpTypesAndCodes != null)
            {
                if (rule.Protocol == 1)
                {
                    curA = "ICMP4";
                }
                else if (rule.Protocol == 58)
                {
                    curA = "ICMP6";
                }
                if (!attributes.ContainsKey(curA))
                {
                    attributes.Add(curA, new List <string>());
                }
                attributes[curA].Add(curA + "=" + rule.IcmpTypesAndCodes);
            }

            //ICMPv6 shouldn't have v4 local addresses and vice versa
            // TODO: add 41,43,44,59,60 (test first)
            if (rule.Protocol == 58 && attributes.ContainsKey("LA4"))
            {
                attributes.Remove("LA4");
            }
            else if (rule.Protocol == 1 && attributes.ContainsKey("LA6"))
            {
                attributes.Remove("LA6");
            }

            //ICMPv6 shouldn't have v4 remote addresses and vice versa
            // TODO: add 41,43,44,59,60 (test first)
            if (rule.Protocol == 58 && attributes.ContainsKey("RA4"))
            {
                attributes.Remove("RA4");
            }
            else if (rule.Protocol == 1 && attributes.ContainsKey("RA6"))
            {
                attributes.Remove("RA6");
            }

            //preserve order of keys
            foreach (var a in aorder)
            {
                if (attributes.ContainsKey(a))
                {
                    rs = rs + "|" + String.Join("|", attributes[a]);
                }
            }
            rs = rs + "|";
            return(rs);
        }
Exemple #24
0
    public bool CreateRockstarRule(int RuleType, string Range)
    {
        try {
            #region Rules buffer
            INetFwRule2   outUDP         = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            INetFwRule2   inUDP          = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            // =============== Out UDP ================ \\

            outUDP.Name            = _RockstarGamesRulesName + "OutUDP";
            outUDP.Description     = "Blocks certain ports from connecting to block anyone from matchmaking in Destiny 2";
            outUDP.Profiles        = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
            outUDP.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            outUDP.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            outUDP.Protocol        = PortProtocol.UDP;
            outUDP.LocalPorts      = _RockstarGamesPorts;
            outUDP.RemoteAddresses = Range;
            outUDP.InterfaceTypes  = "All";
            outUDP.Enabled         = true;
            Console.WriteLine("Rockstar OutUDP created");

            // =============== In  UDP ================ \\

            inUDP.Name            = _RockstarGamesRulesName + "InUDP";
            inUDP.Description     = "Blocks certain ports from connecting to block anyone from matchmaking in Destiny 2";
            inUDP.Profiles        = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
            inUDP.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            inUDP.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            inUDP.Protocol        = PortProtocol.UDP;
            inUDP.LocalPorts      = _RockstarGamesPorts;
            inUDP.RemoteAddresses = Range;
            inUDP.InterfaceTypes  = "All";
            inUDP.Enabled         = true;
            Console.WriteLine("Rockstar InUDP created");
            #endregion

            switch (RuleType)
            {
            case -1:     // All
                firewallPolicy.Rules.Add(outUDP);
                _RockstarGamesOutUDPRuleCreated = true;
                _RockstarGamesOutUDPEnabled     = true;
                Console.WriteLine("Rockstar added OutUDP to the firewall");
                firewallPolicy.Rules.Add(inUDP);
                _RockstarGamesInUDPRuleCreated = true;
                _RockstarGamesInUDPEnabled     = true;
                Console.WriteLine("Rockstar added InUDP to the firewall");
                _RockstarGamesRulesActivated = true;
                return(true);

            case 0:     //outUDP
                firewallPolicy.Rules.Add(outUDP);
                _RockstarGamesOutUDPRuleCreated = true;
                _RockstarGamesOutUDPEnabled     = true;
                Console.WriteLine("Rockstar added OutUDP to the firewall");
                _RockstarGamesRulesActivated = true;
                return(true);

            case 1:     //inUDP
                firewallPolicy.Rules.Add(inUDP);
                _RockstarGamesInUDPRuleCreated = true;
                _RockstarGamesInUDPEnabled     = true;
                Console.WriteLine("Rockstar added InUDP to the firewall");
                _RockstarGamesRulesActivated = true;
                return(true);

            default:
                return(false);
            }
        }
        catch (Exception ex) { throw ex; }
    }
Exemple #25
0
        public static bool SaveRule(FirewallRule rule, INetFwRule2 entry)
        {
            try
            {
                entry.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY;

                INetFwRule3 entry3 = entry as INetFwRule3;

                entry.ApplicationName = rule.BinaryPath;
                entry.serviceName     = rule.ServiceTag;
                if (entry3 != null)
                {
                    entry3.LocalAppPackageId = rule.AppSID;
                }

                /*
                 * switch (rule.ProgID.Type)
                 * {
                 *  case ProgramID.Types.Global:
                 *      entry.ApplicationName = null;
                 *      break;
                 *  case ProgramID.Types.System:
                 *      entry.ApplicationName = "System";
                 *      break;
                 *  default:
                 *      if (rule.ProgID.Path != null && rule.ProgID.Path.Length > 0)
                 *          entry.ApplicationName = rule.ProgID.Path;
                 *      break;
                 * }
                 *
                 * if (rule.ProgID.Type == ProgramID.Types.App)
                 *  entry3.LocalAppPackageId = rule.ProgID.GetPackageSID();
                 * else
                 *  entry3.LocalAppPackageId = null;
                 *
                 * if (rule.ProgID.Type == ProgramID.Types.Service)
                 *  entry.serviceName = rule.ProgID.GetServiceId();
                 * else
                 *  entry.serviceName = null;
                 */

                entry.Name        = rule.Name;
                entry.Grouping    = rule.Grouping;
                entry.Description = rule.Description;

                entry.Enabled = rule.Enabled;

                switch (rule.Direction)
                {
                case FirewallRule.Directions.Inbound: entry.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; break;

                case FirewallRule.Directions.Outboun: entry.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT; break;
                }

                switch (rule.Action)
                {
                case FirewallRule.Actions.Allow: entry.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; break;

                case FirewallRule.Actions.Block: entry.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; break;
                }

                entry.Profiles = rule.Profile;

                if (rule.Interface == (int)FirewallRule.Interfaces.All)
                {
                    entry.InterfaceTypes = "All";
                }
                else
                {
                    List <string> interfaces = new List <string>();
                    if ((rule.Interface & (int)FirewallRule.Interfaces.Lan) != 0)
                    {
                        interfaces.Add("Lan");
                    }
                    if ((rule.Interface & (int)FirewallRule.Interfaces.Wireless) != 0)
                    {
                        interfaces.Add("Wireless");
                    }
                    if ((rule.Interface & (int)FirewallRule.Interfaces.RemoteAccess) != 0)
                    {
                        interfaces.Add("RemoteAccess");
                    }
                    entry.InterfaceTypes = string.Join(",", interfaces.ToArray().Reverse());
                }

                // Note: if this is not cleared protocol change may trigger an exception
                if (entry.LocalPorts != null)
                {
                    entry.LocalPorts = null;
                }
                if (entry.RemotePorts != null)
                {
                    entry.RemotePorts = null;
                }
                if (entry.IcmpTypesAndCodes != null)
                {
                    entry.IcmpTypesAndCodes = null;
                }

                // Note: protocol must be set early enough or other sets will cause errors!
                entry.Protocol = rule.Protocol;

                switch (rule.Protocol)
                {
                case (int)FirewallRule.KnownProtocols.ICMP:
                case (int)FirewallRule.KnownProtocols.ICMPv6:
                    entry.IcmpTypesAndCodes = rule.GetIcmpTypesAndCodes();
                    break;

                case (int)FirewallRule.KnownProtocols.TCP:
                case (int)FirewallRule.KnownProtocols.UDP:
                    entry.LocalPorts  = rule.LocalPorts;
                    entry.RemotePorts = rule.RemotePorts;
                    break;
                }

                if (rule.EdgeTraversal != (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_USER)
                {
                    entry.LocalAddresses  = rule.LocalAddresses;
                    entry.RemoteAddresses = rule.RemoteAddresses;
                }

                entry.EdgeTraversalOptions = rule.EdgeTraversal;


                if (entry3 != null)
                {
                    /*
                     * string s0 = entry3.LocalAppPackageId // 8
                     * string s1 = entry3.RemoteUserAuthorizedList; // 7
                     * string s2 = entry3.RemoteMachineAuthorizedList; // 7
                     * string s3 = entry3.LocalUserAuthorizedList; // 8
                     * string s4 = entry3.LocalUserOwner; // 8
                     * int i1 = entry3.SecureFlags; // ??
                     */
                }
            }
            catch (Exception err)
            {
                Priv10Logger.LogError("Firewall Rule Commit failed {0}", err.ToString());
                return(false);
            }
            return(true);
        }
Exemple #26
0
        public static bool LoadRule(FirewallRule rule, INetFwRule2 entry)
        {
            try
            {
                INetFwRule3 entry3 = entry as INetFwRule3;

                rule.BinaryPath = entry.ApplicationName;
                rule.ServiceTag = entry.serviceName;
                if (entry3 != null)
                {
                    rule.AppSID = entry3.LocalAppPackageId;
                }

                // Note: while LocalAppPackageId and serviceName can be set at the same timea universall App can not be started as a service
                ProgramID progID;
                if (entry.ApplicationName != null && entry.ApplicationName.Equals("System", StringComparison.OrdinalIgnoreCase))
                {
                    progID = ProgramID.NewID(ProgramID.Types.System);
                }
                // Win10
                else if (entry3 != null && entry3.LocalAppPackageId != null)
                {
                    if (entry.serviceName != null)
                    {
                        throw new ArgumentException("Firewall paremeter conflict");
                    }
                    progID = ProgramID.NewAppID(entry3.LocalAppPackageId, entry.ApplicationName);
                }
                //
                else if (entry.serviceName != null)
                {
                    progID = ProgramID.NewSvcID(entry.serviceName, entry.ApplicationName);
                }
                else if (entry.ApplicationName != null)
                {
                    progID = ProgramID.NewProgID(entry.ApplicationName);
                }
                else // if nothing is configured than its a global roule
                {
                    progID = ProgramID.NewID(ProgramID.Types.Global);
                }

                rule.ProgID = Priv10Engine.AdjustProgID(progID);

                // https://docs.microsoft.com/en-us/windows/desktop/api/netfw/nn-netfw-inetfwrule

                rule.Name        = entry.Name;
                rule.Grouping    = entry.Grouping;
                rule.Description = entry.Description;

                //rule.ProgramPath = entry.ApplicationName;
                //rule.ServiceName = entry.serviceName;

                rule.Enabled = entry.Enabled;

                switch (entry.Direction)
                {
                case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN: rule.Direction = FirewallRule.Directions.Inbound; break;

                case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT: rule.Direction = FirewallRule.Directions.Outboun; break;
                }

                switch (entry.Action)
                {
                case NET_FW_ACTION_.NET_FW_ACTION_ALLOW: rule.Action = FirewallRule.Actions.Allow; break;

                case NET_FW_ACTION_.NET_FW_ACTION_BLOCK: rule.Action = FirewallRule.Actions.Block; break;
                }

                rule.Profile = entry.Profiles;

                if (entry.InterfaceTypes.Equals("All", StringComparison.OrdinalIgnoreCase))
                {
                    rule.Interface = (int)FirewallRule.Interfaces.All;
                }
                else
                {
                    rule.Interface = 0;
                    if (entry.InterfaceTypes.IndexOf("Lan", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.Lan;
                    }
                    if (entry.InterfaceTypes.IndexOf("Wireless", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.Wireless;
                    }
                    if (entry.InterfaceTypes.IndexOf("RemoteAccess", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.RemoteAccess;
                    }
                }

                rule.Protocol = entry.Protocol;

                /*The localAddrs parameter consists of one or more comma-delimited tokens specifying the local addresses from which the application can listen for traffic. "*" is the default value. Valid tokens include:
                 *
                 * "*" indicates any local address. If present, this must be the only token included.
                 * "Defaultgateway"
                 * "DHCP"
                 * "WINS"
                 * "LocalSubnet" indicates any local address on the local subnet. This token is not case-sensitive.
                 * A subnet can be specified using either the subnet mask or network prefix notation. If neither a subnet mask not a network prefix is specified, the subnet mask defaults to 255.255.255.255.
                 * A valid IPv6 address.
                 * An IPv4 address range in the format of "start address - end address" with no spaces included.
                 * An IPv6 address range in the format of "start address - end address" with no spaces included.*/

                switch (rule.Protocol)
                {
                case (int)FirewallRule.KnownProtocols.ICMP:
                case (int)FirewallRule.KnownProtocols.ICMPv6:
                    rule.SetIcmpTypesAndCodes(entry.IcmpTypesAndCodes);
                    break;

                case (int)FirewallRule.KnownProtocols.TCP:
                case (int)FirewallRule.KnownProtocols.UDP:
                    // , separated number or range 123-456
                    rule.LocalPorts  = entry.LocalPorts;
                    rule.RemotePorts = entry.RemotePorts;
                    break;
                }

                rule.LocalAddresses  = entry.LocalAddresses;
                rule.RemoteAddresses = entry.RemoteAddresses;

                // https://docs.microsoft.com/de-de/windows/desktop/api/icftypes/ne-icftypes-net_fw_edge_traversal_type_
                //EdgeTraversal = (int)(Entry.EdgeTraversal ? NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_ALLOW : NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY);
                rule.EdgeTraversal = entry.EdgeTraversalOptions;

                if (entry3 != null)
                {
                    /*
                     * string s0 = entry3.LocalAppPackageId // 8
                     * string s1 = entry3.RemoteUserAuthorizedList; // 7
                     * string s2 = entry3.RemoteMachineAuthorizedList; // 7
                     * string s3 = entry3.LocalUserAuthorizedList; // 8
                     * string s4 = entry3.LocalUserOwner; // 8
                     * int i1 = entry3.SecureFlags; // ??
                     */
                }
            }
            catch (Exception err)
            {
                Priv10Logger.LogError("Reading Firewall Rule failed {0}", err.ToString());
                return(false);
            }
            return(true);
        }
 // ReSharper disable once SuggestBaseTypeForParameter
 internal FirewallWASRuleWin7(INetFwRule2 rule) : base(rule)
 {
 }
Exemple #28
0
 /// <summary>
 /// Constructor: Input is a "serialized" fw rule string like one found in
 /// "Software\Policies\Microsoft\WindowsFirewall\FirewallRules"</summary>
 /// <remarks>Allows variable substitution for key/values by providing
 /// a dictionary of substitute information.
 /// This is necessary since the registry rules store name/description
 /// information in separate key/values.
 /// See more details in the <see cref="parseRule"/> method</remarks>
 public MSFirewallRule(string rulestr, Dictionary <string, string> info)
 {
     this.rule = this.parseRule(rulestr, info);
 }
Exemple #29
0
 /// <summary>
 /// Constructor: takes in INetFwRule2.</summary>
 public MSFirewallRule(INetFwRule2 rule)
 {
     this.rule = rule;
 }
Exemple #30
0
        /// <summary>Parses a rule str to make a INetFwRule2</summary>
        /// <remarks>This rule string is found in group policy rules and is undocumented,
        /// as far as I can tell. I've done my best to document my findings here.
        ///
        /// Field                 : rule Mapping             : Values                : Example
        ///"Action"               : rule.Action              : Allow,Block           : Action=Allow
        ///"App"                  : rule.ApplicationName     : Text                  : App=onenote.exe
        ///"Desc"                 : rule.Description         : Text                  : Desc=My rule description
        ///"Dir"                  : rule.Direction           : In,Out                : Dir=In
        ///"Edge"                 : rule.EdgeTraversal       : Bool                  : Edge=TRUE
        ///"Defer"                : rule.EdgeTraversalOption : App,?                 : Defer=App
        ///"Active"               : rule.Enabled             : Bool                  : Active=TRUE
        ///"EmbedCtxt"            : rule.Grouping            : Text                  : EmbedCtxt=Core Networking
        ///"ICMP4","ICMP6"        : rule.IcmpTypesAndCodes   :                       :
        ///?????????????????????  : rule.Interfaces          : ???                   :
        ///?????????????????????  : rule.InterfaceTypes      : ???                   :
        ///"LA4","LA6"            : rule.LocalAddresses      : IP(s) or Enum         : LA4=10.10.10.10 or LocalSubnet or ?
        ///"LPort","LPort2_10"    : rule.LocalPorts          : Port(s) or Enum       : LPort=4500 or ?
        ///"Name"                 : rule.Name                : Text                  : Name=My rule name
        ///"Profile"              : rule.Profiles            : Domain,Private,Public : Profile=Domain
        ///"Protocol"             : rule.Protocol            : ProtocolType          : Protocol=6
        ///"RA4", "RA6"           : rule.RemoteAddresses     : IP(s) or Enum         : RA4=10.10.10.10 or LocalSubnet or ?
        ///"RPort","RPort2_10"    : rule.RemotePorts         : Port(s) or Enum       : RPort=4500 or ?
        ///"Svc"                  : rule.serviceName         : Text                  : Svc=upnphost
        ///
        /// Additional notes on fields:
        ///
        /// All lists are comma-delimited
        /// If not present, booleans are FALSE and normally restrictive fields allow all
        /// "Action"    : required. Will be "Allow" or "Block"
        /// "App"       : optional. Will be a complete path to an executable. Will be a complete path to svchost.exe if using "Svc" field
        /// "Desc"      : optional. Variable substitution needed for rules from registry.
        /// "Dir"       : required. Will be "In" or "Out"
        /// "Edge"      : optional. Will be "TRUE". Default is "FALSE"
        /// "Defer"     : optional. See enum NET_FW_EDGE_TRAVERSAL_TYPE_ for values. Only appears if "Edge" is TRUE and only used for DEFER_TO_APP and DEFER_TO_USER
        /// "Active"    : required. Will be "TRUE" or "FALSE"
        /// "EmbedCtxt" : optional. Variable substitution needed for rules from registry.
        /// "ICMP4"     : optional. If Protocol is "Icmp", then list of allowed ICMP (v4) types and codes
        /// "ICMP6"     : optional. If Protocol is "IcmpV6", then list of allowed ICMP (v6) types and codes
        /// "LA4"       : optional. IPv4 Addresses (single, range, or subnet). Not allowed if "ICMP6" is defined.
        /// "LA6"       : optional. IPv6 Addresses (single, range, or subnet). Not allowed if "ICMP4" is defined.
        /// "LPort"     : optional. Port or port range.
        /// TODO: complete field documentation
        /// </remarks>
        public INetFwRule2 parseRule(string rulestr, Dictionary <string, string> info)
        {
            INetFwRule2 rule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            string[] ruleAttribs = rulestr.Split('|');
            foreach (string ra in ruleAttribs)
            {
                var kv = ra.Split('=');
                switch (kv[0])
                {
                case "":
                case "v2.10":
                    //version ignore
                    break;

                case "Action":
                    kv[1] = kv[1].ToLower();
                    if (kv[1] == "allow")
                    {
                        rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                    }
                    else if (kv[1] == "block")
                    {
                        rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                    }
                    else if (kv[1] == "max")
                    {
                        rule.Action = NET_FW_ACTION_.NET_FW_ACTION_MAX;
                    }
                    else
                    {
                        throw new Exception("parseRule: Unknown action in rule: " + kv[1]);
                    }
                    break;

                case "Active":
                    kv[1] = kv[1].ToLower();
                    if (kv[1] == "true")
                    {
                        rule.Enabled = true;
                    }
                    else
                    {
                        rule.Enabled = false;
                    }
                    break;

                case "App":
                    rule.ApplicationName = kv[1];
                    break;

                case "Defer":
                    kv[1] = kv[1].ToLower();
                    if (kv[1] == "app")
                    {
                        rule.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_APP;
                    }
                    else
                    {
                        throw new Exception("Uknown defer: {0}" + kv[1]);
                    }
                    break;

                case "Desc":
                    if (info.ContainsKey(kv[1]))
                    {
                        rule.Description = info[kv[1]];
                    }
                    else
                    {
                        rule.Description = kv[1];
                    }
                    break;

                case "Dir":
                    kv[1] = kv[1].ToLower();
                    if (kv[1] == "in")
                    {
                        rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                    }
                    else if (kv[1] == "out")
                    {
                        rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
                    }
                    else if (kv[1] == "max")
                    {
                        rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_MAX;
                    }
                    else
                    {
                        throw new Exception("parseRule: Unknown direction in rule: " + kv[1]);
                    }
                    break;

                case "Edge":
                    kv[1] = kv[1].ToLower();
                    if (kv[1] == "true")
                    {
                        rule.EdgeTraversal = true;
                    }
                    else
                    {
                        rule.EdgeTraversal = false;
                    }
                    break;

                case "EmbedCtxt":
                    if (info.ContainsKey(kv[1]))
                    {
                        rule.Grouping = info[kv[1]];
                    }
                    else
                    {
                        rule.Grouping = kv[1];
                    }
                    break;

                case "ICMP4":
                case "ICMP6":
                    if (rule.IcmpTypesAndCodes == "*")
                    {
                        rule.IcmpTypesAndCodes = kv[1];
                    }
                    else
                    {
                        //Console.WriteLine(rule.IcmpTypesAndCodes + " " + kv[1]);
                        rule.IcmpTypesAndCodes += "," + kv[1];
                    }
                    break;

                case "LA4":
                case "LA6":
                    if (rule.LocalAddresses == "*")
                    {
                        rule.LocalAddresses = kv[1];
                    }
                    else if (!rule.LocalAddresses.Contains(kv[1]))
                    {
                        rule.LocalAddresses += "," + kv[1];
                    }
                    break;

                case "LPort":
                    if (rule.LocalPorts == "*")
                    {
                        //Console.WriteLine("init:" + kv[1]);
                        rule.LocalPorts = kv[1];
                    }
                    else
                    {
                        //Console.WriteLine("append: '" + rule.LocalPorts.ToString() + "'" + ":" + kv[1]);
                        rule.LocalPorts = rule.LocalPorts.ToString() + "," + kv[1];
                    }
                    break;

                case "LPort2_10":
                    //todo:IPHTTPS maps to IPHTTPSIn AND IPTLSIn
                    //warning: unknown if correct; no example yet
                    rule.LocalPorts = kv[1];
                    break;

                case "Name":
                    if (info.ContainsKey(kv[1]))
                    {
                        rule.Name = info[kv[1]];
                    }
                    else
                    {
                        rule.Name = kv[1];
                    }
                    break;

                case "Profile":
                    if (rule.Profiles == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL)
                    {
                        switch (kv[1])
                        {
                        case "Domain":
                            rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN;
                            break;

                        case "Private":
                            rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE;
                            break;

                        case "Public":
                            rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC;
                            break;
                        }
                    }
                    else
                    {
                        switch (kv[1])
                        {
                        case "Domain":
                            rule.Profiles = rule.Profiles | (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN;
                            break;

                        case "Private":
                            rule.Profiles = rule.Profiles | (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE;
                            break;

                        case "Public":
                            rule.Profiles = rule.Profiles | (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC;
                            break;
                        }
                    }
                    break;

                case "Protocol":
                    rule.Protocol = Int32.Parse(kv[1]);
                    break;

                case "RA4":
                case "RA6":
                    if (rule.RemoteAddresses == "*")
                    {
                        rule.RemoteAddresses = kv[1];
                    }
                    else if (!rule.RemoteAddresses.Contains(kv[1]))
                    {
                        rule.RemoteAddresses += "," + kv[1];
                    }
                    //Console.WriteLine(rule.RemoteAddresses + " + " + kv[1]);
                    //Console.WriteLine(rule.RemoteAddresses);
                    break;

                case "RPort":
                    if (rule.RemotePorts == "*")
                    {
                        //Console.WriteLine("init:" + kv[1]);
                        rule.RemotePorts = kv[1];
                    }
                    else
                    {
                        //Console.WriteLine("append: '" + rule.RemotePorts.ToString() + "'" + ":" + kv[1]);
                        rule.RemotePorts += "," + kv[1];
                    }
                    break;

                case "RPort2_10":
                    //does IPHTTPS maps to IPHTTPSOut AND IPTLSOut ????
                    //warning: unknown if correct; no example yet
                    rule.RemotePorts = kv[1];
                    break;

                case "Svc":
                    rule.serviceName = kv[1];
                    break;

                default:
                    throw new Exception("Uknown firewall rule type:" + kv[0]);
                }
            }
            if (((rule.Profiles & (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN) == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN) &&
                ((rule.Profiles & (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE) == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE) &&
                ((rule.Profiles & (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC) == (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC)
                )
            {
                rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
            }

            return(rule);
        }