Beispiel #1
1
        public static void FirewallCreateBlockall()
        {
            //outbound rule
            INetFwRule blockout = (INetFwRule)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FWRule"));

            blockout.Action         = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            blockout.Description    = "BLOCKING THE PORT 6672 WHEN OUTBOUND";
            blockout.Direction      = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            blockout.Enabled        = true;
            blockout.InterfaceTypes = "All";
            blockout.Name           = "SafeKeeperbyDigitalArc-BLOCKOUT";
            blockout.Protocol       = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
            blockout.LocalPorts     = "6672";
            if (whitelistEnabled)
            {
                string range = createRange();
                Console.WriteLine(range);
                blockout.RemoteAddresses = range;
                //blockout.RemoteAddresses
            }
            //inbound rule
            INetFwRule blockin = (INetFwRule)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FWRule"));

            blockin.Action         = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            blockin.Description    = "BLOCKING THE PORT 6672 WHEN INBOUND";
            blockin.Direction      = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            blockin.Enabled        = true;
            blockin.InterfaceTypes = "All";
            blockin.Name           = "SafeKeeperbyDigitalArc-BLOCKIN";
            blockin.Protocol       = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
            blockin.LocalPorts     = "6672";
            if (whitelistEnabled)
            {
                blockin.RemoteAddresses = createRange();
            }
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            firewallPolicy.Rules.Add(blockout);
            firewallPolicy.Rules.Add(blockin);
            blockEnabled = true;
        }
        public static void GetFirewallRules(NET_FW_RULE_DIRECTION_ direction, IList <Rule> rules)
        {
            // Clear list
            rules.Clear();

            // Get firewall info
            INetFwPolicy2 fwPolicy = GetFirewallPolicy();

            // Get firewall rules
            INetFwRules fwRules = fwPolicy.Rules;

            // Get rule enumerator
            IEnumerator enumerator = fwRules.GetEnumerator();

            // For each firewall rule
            while (enumerator.MoveNext())
            {
                INetFwRule fwRule = (INetFwRule)enumerator.Current;

                // If rule is not the direction we're looking for, skip
                if (fwRule.Direction != direction)
                {
                    continue;
                }

                Rule rule = new Rule(fwRule.Name)
                {
                    Description     = checkString(fwRule.Description),
                    ApplicationName = checkString(fwRule.ApplicationName),
                    ServiceName     = checkString(fwRule.serviceName),
                    intProtocol     = fwRule.Protocol,
                    LocalPorts      = checkString(fwRule.LocalPorts),
                    RemotePorts     = checkString(fwRule.RemotePorts),
                    LocalAddresses  = checkString(fwRule.LocalAddresses),
                    RemoteAddresses = checkString(fwRule.RemoteAddresses),
                    Enabled         = fwRule.Enabled,
                    Group           = checkString(fwRule.Grouping),
                    Profile         = (NET_FW_PROFILE_TYPE2_)fwRule.Profiles,
                    Action          = fwRule.Action,
                };

                rules.Add(rule);
            }
        }
        public static bool CreateRule(NET_FW_RULE_DIRECTION_ richting, string name, string description, int profileValue, bool enabled,
                                      NET_FW_ACTION_ typeOfRule, string application, string localAdresses, string remoteAdresses, string localPorts, string remotePorts,
                                      int protocolValue)
        {
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            INetFwRule    firewallRule   = firewallPolicy.Rules.OfType <INetFwRule>().Where(x => x.Name == name).FirstOrDefault();

            if (firewallRule != null)
            {
                firewallPolicy.Rules.Remove(firewallRule.Name);
            }
            try
            {
                firewallRule      = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRule.Name = name;
                firewallPolicy.Rules.Add(firewallRule);
                firewallRule.Description     = description;
                firewallRule.Grouping        = "testomgeving .Net";
                firewallRule.Profiles        = profileValue;
                firewallRule.Protocol        = protocolValue; // moet gezet worden vooraleer de poorten gezet worden
                firewallRule.Direction       = richting;
                firewallRule.Action          = typeOfRule;
                firewallRule.ApplicationName = application;
                firewallRule.LocalAddresses  = localAdresses;
                if (localPorts != "")
                {
                    firewallRule.LocalPorts = localPorts;
                }
                firewallRule.RemoteAddresses = remoteAdresses;
                if (remotePorts != "")
                {
                    firewallRule.RemotePorts = remotePorts;
                }
                firewallRule.Enabled = enabled;
            }
            catch (Exception fout)
            {
                return(false);
            }



            return(true);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start Application");

            #region Win32 Sample
            Console.WriteLine("Start Win32 Sample");

            SYSTEM_INFO pSI = new SYSTEM_INFO();
            GetSystemInfo(ref pSI);

            Console.WriteLine($"dwProcessorLevel: {pSI.dwProcessorLevel}");

            Console.WriteLine("End Win32 Sample");
            #endregion

            Console.WriteLine();

            #region COM Sample
            Console.WriteLine("Start COM Sample");

            // COM Registration
            Console.WriteLine("COM Registation");
            RegistarDlls("Interop.NetFwTypeLib.dll");

            const string  guidFWPolicy2 = "{E2B3C97F-6AE1-41AC-817A-F6F92166D7DD}";
            const string  guidRWRule    = "{2C5BC43E-3369-4C33-AB0C-BE9469677AF4}";
            Type          typeFWPolicy2 = Type.GetTypeFromCLSID(new Guid(guidFWPolicy2));
            Type          typeFWRule    = Type.GetTypeFromCLSID(new Guid(guidRWRule));
            INetFwPolicy2 fwPolicy2     = (INetFwPolicy2)Activator.CreateInstance(typeFWPolicy2);
            INetFwRule    newRule       = (INetFwRule)Activator.CreateInstance(typeFWRule);
            newRule.Name        = "MabuAsTcpLocker_OutBound_Rule";
            newRule.Description = "Block outbound traffic  over TCP port 80";
            newRule.Protocol    = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            newRule.RemotePorts = "8888";
            newRule.Direction   = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            newRule.Enabled     = true;
            newRule.Profiles    = 6;
            newRule.Action      = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;

            Console.WriteLine("End COM Sample");
            #endregion

            Console.WriteLine("End Application");
        }
Beispiel #5
0
        public static bool AddInboudRule(string name, string programFullPath)
        {
            if (IsInboundRuleExist(name, programFullPath) == true)
            {
                return(true);
            }

            INetFwRule newRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            newRule.Name            = name;
            newRule.ApplicationName = programFullPath;
            newRule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
            newRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            newRule.Enabled         = true;
            newRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            _firewallPolicy.Rules.Add(newRule);

            return(IsInboundRuleExist(name, programFullPath));
        }
        private void AddFirewallRule(string p)
        {
            INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FWRule"));

            firewallRule.Action         = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRule.Description    = "Used to allow Samana Monitor access.";
            firewallRule.Direction      = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            firewallRule.Enabled        = true;
            firewallRule.InterfaceTypes = "All";
            firewallRule.Protocol       = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            firewallRule.LocalPorts     = p;
            firewallRule.Name           = "SamanaMonitor";

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

            firewallPolicy.Rules.Add(firewallRule);
        }
        /// <summary>
        /// Add a ports/protocol exception rule for all profiles for Vista or later firewall
        /// </summary>
        /// <param name="ruleName"></param>
        /// <param name="appPath"></param>
        /// <returns>false if the firewall type isn't available, true for successful completion.</returns>
        public static bool AddPortExceptionToVistaFirewall(string ruleName, string ports, NET_FW_IP_PROTOCOL_ protocol)
        {
            Type fwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");

            if (fwPolicy2Type == null)
            {
                return(false);
            }

            INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)System.Activator.CreateInstance(fwPolicy2Type);
            INetFwRule    fwRule    = (INetFwRule)System.Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwRule"));

            fwRule.Name       = ruleName;
            fwRule.Protocol   = (int)protocol;
            fwRule.LocalPorts = ports;
            fwRule.Enabled    = true;
            fwPolicy2.Rules.Add(fwRule);
            return(true);
        }
Beispiel #8
0
        // Searches all existing firewall rules with the given name
        private static INetFwRule FindRule(string name, int port)
        {
            lock (s_portLock)
            {
                // Match on our special naming pattern and port
                HashSet <string> ruleSet = new HashSet <string>();
                foreach (var r in NetFwPolicy2.Rules)
                {
                    INetFwRule rule = (INetFwRule)r;
                    if (String.Equals(name, rule.Name, StringComparison.OrdinalIgnoreCase) &&
                        String.Equals(rule.LocalPorts, port.ToString(), StringComparison.Ordinal))
                    {
                        return(rule);
                    }
                }

                return(null);
            }
        }
Beispiel #9
0
        public bool IsIPAddressBlocked(string ipAddress, out string ruleName, int port = -1)
        {
            ruleName = null;

            try
            {
                lock (policy)
                {
                    for (int i = 0; ; i += MaxIpAddressesPerRule)
                    {
                        string firewallRuleName = BlockRulePrefix + i.ToString(CultureInfo.InvariantCulture);
                        try
                        {
                            INetFwRule rule = policy.Rules.Item(firewallRuleName);
                            if (rule == null)
                            {
                                // no more rules to check
                                break;
                            }
                            else
                            {
                                HashSet <string> set = new HashSet <string>(rule.RemoteAddresses.Split(',').Select(i2 => IPAddressRange.Parse(i2).Begin.ToString()));
                                if (set.Contains(ipAddress))
                                {
                                    ruleName = firewallRuleName;
                                    return(true);
                                }
                            }
                        }
                        catch
                        {
                            // no more rules to check
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                IPBanLog.Error(ex);
            }
            return(false);
        }
Beispiel #10
0
        public static void SetRule(string applicationName, string path, bool allow)
        {
            INetFwRule firewallRuleOUT = GetNewRule();
            INetFwRule firewallRuleIN  = GetNewRule();

            firewallRuleOUT.Action         = firewallRuleIN.Action = allow ? NET_FW_ACTION_.NET_FW_ACTION_ALLOW : NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            firewallRuleOUT.Direction      = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            firewallRuleIN.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            firewallRuleOUT.Enabled        = firewallRuleIN.Enabled = true;
            firewallRuleOUT.InterfaceTypes = firewallRuleIN.InterfaceTypes = "All";
            firewallRuleOUT.Profiles       = firewallRuleIN.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
            firewallRuleOUT.Grouping       = firewallRuleIN.Grouping = "Argon";

            firewallRuleOUT.Name            = firewallRuleIN.Name = applicationName + "__" + path;
            firewallRuleOUT.ApplicationName = firewallRuleIN.ApplicationName = path;

            FirewallPolicy.Rules.Add(firewallRuleOUT);
            FirewallPolicy.Rules.Add(firewallRuleIN);
        }
        /// <summary>
        /// Open a certain port, name of the rule includes timeout of opening port.
        /// </summary>
        /// <param name="tcpPort"></param>
        /// <param name="endpoint"></param>
        /// <param name="dateTime"></param>
        public void OpenPortWithTimeout(int tcpPort, IPEndPoint endpoint, DateTime dateTime)
        {
            var           ruleName = $"{Constants.TcpRulePrefix}{dateTime.ToString("yyyyMMddHHmm")}_{Guid.NewGuid().ToString()}";
            INetFwPolicy2 fwPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            firewallRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRule.Description     = "Created by StupidFirewallManager";
            firewallRule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            firewallRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; // inbound
            firewallRule.Enabled         = true;
            firewallRule.InterfaceTypes  = "All";
            firewallRule.RemoteAddresses = endpoint.Address.ToString();
            firewallRule.LocalAddresses  = "*";
            firewallRule.Name            = ruleName;
            firewallRule.LocalPorts      = tcpPort.ToString();
            fwPolicy.Rules.Add(firewallRule);
        }
Beispiel #12
0
        public void TcpHttpHttpsBlock()
        {
            INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            firewallRule.Action         = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            firewallRule.Description    = "TCP Based HTTP, HTTPS Protocol Block";
            firewallRule.Direction      = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            firewallRule.Protocol       = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            firewallRule.RemotePorts    = "80,443";
            firewallRule.Enabled        = true;
            firewallRule.InterfaceTypes = "All";
            firewallRule.Name           = TCP_HTTP_HTTPS_BLOCK_RULENAME;

            // 설정하기 위한 룰을 만드는 작업

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

            firewallPolicy.Rules.Add(firewallRule);
        }
Beispiel #13
0
        public static bool AddInboudRule(string name, Protocol protocol, int port)
        {
            if (IsInboundRuleExist(name, protocol, port) == true)
            {
                return(true);
            }

            INetFwRule newRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            newRule.Name       = name;
            newRule.Protocol   = (int)protocol;
            newRule.LocalPorts = port.ToString();
            newRule.Direction  = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            newRule.Enabled    = true;
            newRule.Action     = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            _firewallPolicy.Rules.Add(newRule);

            return(IsInboundRuleExist(name, protocol, port));
        }
Beispiel #14
0
        /// <summary>
        /// Removes CodeSwine Inbound & Outbound firewall rules at program startup.
        /// </summary>
        public static void DeleteRules()
        {
            try {
                INetFwRule firewallRuleInbound = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleInbound.Name = "GTA5 CodeSwine - Private Public Lobby Inbound";

                INetFwRule firewallRuleOutbound = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleOutbound.Name = "GTA5 CodeSwine - Private Public Lobby Outbound";

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

                firewallPolicy.Rules.Remove(firewallRuleInbound.Name);
                firewallPolicy.Rules.Remove(firewallRuleOutbound.Name);
            } catch (Exception e)
            {
                ErrorLogger.LogException(e);
                MessageBox.Show("프로그램을 관리자 권한으로 실행해주세요.", "경고", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Beispiel #15
0
 public static void EnableInboundPort(NET_FW_IP_PROTOCOL_ protocol, int port, string description)
 {
     try
     {
         INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
         firewallRule.Action         = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
         firewallRule.Name           = description;
         firewallRule.Direction      = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
         firewallRule.Protocol       = (int)protocol;
         firewallRule.LocalPorts     = port.ToString();
         firewallRule.Enabled        = true;
         firewallRule.InterfaceTypes = "All";
         INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
         firewallPolicy.Rules.Add(firewallRule);
     }
     catch (Exception)
     {
     }
 }
Beispiel #16
0
        public void Add(INetFwRule rule)
        {
            if (String.IsNullOrEmpty(rule.LocalPorts) || rule.LocalPorts.Equals("0"))
            {
                return;
            }

            NetFwRule netFwRule = (NetFwRule)rule;

#if DotNetCoreClrLinux
            var addCommand  = netFwRule.AddCommand();
            int returnvalue = NativeHelper.system(addCommand);
            if (returnvalue != 0)
            {
                throw new Exception(String.Format("Error encountered in executing command {0} with return value {1}", addCommand, returnvalue));
            }
#endif
            _rules.Add(rule.Name, rule.Clone());
        }
Beispiel #17
0
        /// <summary>
        /// Removes CodeSwine Inbound & Outbound firewall rules at program startup.
        /// </summary>
        public static void DeleteRules()
        {
            try {
                INetFwRule firewallRuleInbound = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleInbound.Name = "GTA5 CodeSwine - Private Public Lobby Inbound";

                INetFwRule firewallRuleOutbound = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleOutbound.Name = "GTA5 CodeSwine - Private Public Lobby Outbound";

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

                firewallPolicy.Rules.Remove(firewallRuleInbound.Name);
                firewallPolicy.Rules.Remove(firewallRuleOutbound.Name);
            } catch (Exception e)
            {
                ErrorLogger.LogException(e);
                MessageBox.Show("Run this program as administrator!");
            }
        }
        public void Setup()
        {
            Type          typeFWPolicy2 = Type.GetTypeFromCLSID(new Guid(guidFWPolicy2));
            Type          typeFWRule    = Type.GetTypeFromCLSID(new Guid(guidRWRule));
            INetFwPolicy2 fwPolicy2     = (INetFwPolicy2)Activator.CreateInstance(typeFWPolicy2);
            INetFwRule    newRule       = (INetFwRule)Activator.CreateInstance(typeFWRule);

            newRule.Name          = "InBound_Rule";
            newRule.Description   = "Block inbound traffic from 192.168.0.2 over TCP port 4000";
            newRule.Protocol      = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            newRule.LocalPorts    = "4000";
            newRule.RemoteAddress = "192.168.0.2";
            newRule.Direction     = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            newRule.Enabled       = true;
            newRule.Grouping      = "@firewallapi.dll,-23255";
            newRule.Profiles      = fwPolicy2.CurrentProfileTypes;
            newRule.Action        = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            fwPolicy2.Rules.Add(newRule);
        }
Beispiel #19
0
        public static void firewallDo(int port)
        {
            firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            fwMgr        = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWMgr"));
            firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));



            firewallRule.Action         = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            firewallRule.Enabled        = true;
            firewallRule.InterfaceTypes = "All";
            firewallRule.Name           = "Auto_Deny_" + port.ToString();
            firewallRule.Description    = "Cyberscript " + DateTime.Now.ToString("HH:mm:ss tt");
            firewallRule.Protocol       = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            firewallRule.LocalPorts     = port.ToString();
            firewallPolicy.Rules.Add(firewallRule);
        }
Beispiel #20
0
        private static void AddNewFirewallRule(int port)
        {
            lock (s_portLock)
            {
                if (s_AddedRulesByPort.ContainsKey(port))
                {
                    return;
                }

                // If we add any rules, register to delete them at process exit.
                RegisterForProcessExit();

                // Create the FwPolicy2 object.
                Type          netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false);
                INetFwPolicy2 fwPolicy2        = (INetFwPolicy2)Activator.CreateInstance(netFwPolicy2Type);

                // Get the Rules object
                INetFwRules rulesObject = fwPolicy2.Rules;

                int CurrentProfiles = fwPolicy2.CurrentProfileTypes;

                // Create a Rule Object.
                Type       netFwRuleType = Type.GetTypeFromProgID("HNetCfg.FWRule", false);
                INetFwRule newRule       = (INetFwRule)Activator.CreateInstance(netFwRuleType);

                newRule.Name        = String.Format(s_PortNameFormat, port);
                newRule.Description = String.Format("Rule added for Bridge use of port {0}", port);
                newRule.Protocol    = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                newRule.LocalPorts  = port.ToString();
                newRule.Direction   = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                newRule.Enabled     = true;
                newRule.Profiles    = CurrentProfiles;
                newRule.Action      = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;

                // Add a new rule
                rulesObject.Add(newRule);

                Trace.WriteLine(String.Format("Added firewall rule {0}", newRule.Name),
                                typeof(PortManager).Name);

                s_AddedRulesByPort[port] = newRule.Name;
            }
        }
Beispiel #21
0
        /// <summary>
        /// Sets, Removes or Toggles Inbound firewall rules.
        /// </summary>
        /// <param name="addresses">Scope to block.</param>
        /// <param name="enabled">True to enable, false to disable the rule.</param>
        /// <param name="toggle">True to prevent adding or removing the rule again.</param>
        public static bool CreateInbound(string addresses, Game game, bool enabled, bool toggle)
        {
            try
            {
                INetFwRule firewallRuleTCP = createFWRule(addresses, game, enabled, false, RuleProtocol.eRuleProtoTCP);
                INetFwRule firewallRuleUDP = createFWRule(addresses, game, enabled, false, RuleProtocol.eRuleProtoUDP);

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

                if (!toggle)
                {
                    if (game.TcpPorts.Length > 0)
                    {
                        firewallPolicy.Rules.Add(firewallRuleTCP);
                    }
                    if (game.UdpPorts.Length > 0)
                    {
                        firewallPolicy.Rules.Add(firewallRuleUDP);
                    }
                }
                else
                {
                    if (game.TcpPorts.Length > 0)
                    {
                        firewallPolicy.Rules.Remove(firewallRuleTCP.Name);
                        firewallPolicy.Rules.Add(firewallRuleTCP);
                    }
                    if (game.UdpPorts.Length > 0)
                    {
                        firewallPolicy.Rules.Remove(firewallRuleUDP.Name);
                        firewallPolicy.Rules.Add(firewallRuleUDP);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLogger.LogException(e);
                return(false);
            }

            return(true);
        }
Beispiel #22
0
        /// <summary>
        /// Removes Inbound & Outbound firewall rules at program startup.
        /// </summary>
        public static void DeleteRules(Game game)
        {
            try {
                INetFwRule firewallRuleInboundTCP = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleInboundTCP.Name = game.GetTCPRuleName("Inbound");

                INetFwRule firewallRuleInboundUDP = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleInboundUDP.Name = game.GetUDPRuleName("Inbound");

                INetFwRule firewallRuleOutboundTCP = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleOutboundTCP.Name = game.GetTCPRuleName("Outbound");

                INetFwRule firewallRuleOutboundUDP = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRuleOutboundUDP.Name = game.GetUDPRuleName("Outbound");


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

                if (game.TcpPorts.Length > 0)
                {
                    firewallPolicy.Rules.Remove(firewallRuleInboundTCP.Name);
                    firewallPolicy.Rules.Remove(firewallRuleOutboundTCP.Name);
                }

                if (game.UdpPorts.Length > 0)
                {
                    firewallPolicy.Rules.Remove(firewallRuleInboundUDP.Name);
                    firewallPolicy.Rules.Remove(firewallRuleOutboundUDP.Name);
                }
            } catch (Exception e)
            {
                ErrorLogger.LogException(e);
                if (lblAdmin != null)
                {
                    lblAdmin.Visibility = Visibility.Visible;
                }
                else
                {
                    MessageBox.Show("Run this program as administrator!");
                }
            }
        }
        /// <summary>
        /// This is slightly different from <see cref="ApplyUdpRules(FirewallRule[])"/> but it
        /// could be made equal.
        /// should be expired.
        /// </summary>
        /// <param name="rules"></param>
        public void ApplyBasicTcpRules(FirewallRule[] rules)
        {
            var ports      = rules.Select(r => r.TcpPort).ToArray();
            var portRanges = PortRangeHelper.GetRangeExclusive(ports);
            //now get already existing rules.
            var allStaticTcpRule = SearchFirewallRules()
                                   .Where(r => r.Name.StartsWith(Constants.TcpStaticPrefix));

            INetFwPolicy2 fwPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            //we need to create other rules, and be 100% sure that only new rules for udp are created
            var newRules = portRanges
                           .Select(range => new
            {
                Name  = $"{Constants.TcpStaticPrefix}_{range.LowerPortInclusive}_{range.UpperPortInclusive}",
                Range = range
            })
                           .ToList();

            var rulesToRemove = allStaticTcpRule.Where(r => !newRules.Any(nr => nr.Name == r.Name)).ToList();

            foreach (var ruleToRemove in rulesToRemove)
            {
                fwPolicy.Rules.Remove(ruleToRemove.Name);
            }
            var rulesToAdd = newRules.Where(r => !allStaticTcpRule.Any(ur => ur.Name == r.Name)).ToList();

            foreach (var ruleToAdd in rulesToAdd)
            {
                INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                firewallRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                firewallRule.Description     = "Created by StupidFirewallManager";
                firewallRule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                firewallRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; // inbound
                firewallRule.Enabled         = true;
                firewallRule.InterfaceTypes  = "All";
                firewallRule.RemoteAddresses = "*"; // add more blocks comma separated
                firewallRule.LocalAddresses  = "*";
                firewallRule.Name            = ruleToAdd.Name;
                firewallRule.LocalPorts      = $"{ruleToAdd.Range.LowerPortInclusive}-{ruleToAdd.Range.UpperPortInclusive}";
                fwPolicy.Rules.Add(firewallRule);
            }
        }
        public string fwApplicationRule(string ruleName, string filePath, NET_FW_ACTION_ fwAction, NET_FW_RULE_DIRECTION_ fwDirection, bool isAddRule)
        {
            if (isAddRule)
            {
                if (isApplicationRuleExists(filePath, fwAction, true))
                {
                    return("Exclude");
                }
                if (isApplicationRuleExists(filePath, fwAction))
                {
                    return(fwAction.ToString().Replace("NET_FW_ACTION_", string.Empty));
                }
            }
            try
            {
                INetFwRule fwRule = (INetFwRule)Activator.CreateInstance(
                    Type.GetTypeFromProgID("HNetCfg.FWRule"));
                fwRule.Action          = fwAction;
                fwRule.Enabled         = true;
                fwRule.InterfaceTypes  = "All";
                fwRule.Name            = ruleName.ToLower();
                fwRule.ApplicationName = filePath.ToLower();
                INetFwPolicy2 fwPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
                fwRule.Direction = fwDirection;


                if (isAddRule)
                {
                    fwPolicy.Rules.Add(fwRule);
                    return(fwRule.Action.ToString().Replace("NET_FW_ACTION_", string.Empty));
                }
                else
                {
                    fwPolicy.Rules.Remove(fwRule.Name);
                    return("success");
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Beispiel #25
0
        public static List <string> GetBannedIPs()
        {
            List <string> currentlyBannedIPs = new List <string>();

            INetFwRule fwRule = GetFwRule();

            if (fwRule.Enabled)
            {
                string remoteAddresses = fwRule.RemoteAddresses;
                if (remoteAddresses != null)
                {
                    foreach (string s in remoteAddresses.Split(','))
                    {
                        currentlyBannedIPs.Add(s);
                    }
                }
            }

            return(currentlyBannedIPs);
        }
Beispiel #26
0
#pragma warning restore CS8600,CS8601,CS8604

        public static bool AddRule(INetFwRule rule)
        {
            try
            {
                LogHelper.Debug("Adding rule to firewall...");
                firewallPolicy.Rules.Add(rule);

                return(true);
            }
            catch (UnauthorizedAccessException)
            {
                throw;
            }
            catch (Exception e)
            {
                LogHelper.Error("Unable to add the rule to the Windows Firewall", e);
            }

            return(false);
        }
Beispiel #27
0
        public static bool AddInboudRuleIPBlock(string name, Protocol protocol, string ip)
        {
            if (IsInboundRuleExist(name) == true)
            {
                return(true);
            }

            INetFwRule newRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            newRule.Name            = name;
            newRule.Protocol        = (int)protocol;
            newRule.InterfaceTypes  = "All";
            newRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            newRule.Enabled         = true;
            newRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            newRule.RemoteAddresses = ip;
            _firewallPolicy.Rules.Add(newRule);

            return(IsInboundRuleExist(name));
        }
Beispiel #28
0
        public void React(IpV4Address scanner)
        {
            try
            {
                INetFwPolicy2 fwPolicy = GetNetFwPolicy();
                if (ExistsBlockingRuleFor(scanner, fwPolicy))
                {
                    return;
                }

                Console.WriteLine("Adding firewall rule...");
                INetFwRule newRule = SetupNetFwRule(scanner);
                newRule.Profiles = fwPolicy.CurrentProfileTypes;
                fwPolicy.Rules.Add(newRule);
            }
            catch (UnauthorizedAccessException exception)
            {
                throw new InvalidOperationException("You don't have rights for changing firewall rules without administrator rights.", exception);
            }
        }
Beispiel #29
0
        public static void BlockIP(params string[] remoteAddresses)
        {
            string ruleName = "Block3389";

            Type typeFWPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            Type typeFWRule    = Type.GetTypeFromProgID("HNetCfg.FwRule");

            try
            {
                INetFwPolicy2 fwPolicy2    = (INetFwPolicy2)Activator.CreateInstance(typeFWPolicy2);
                var           rules        = fwPolicy2.Rules.Cast <INetFwRule>();
                var           rule         = rules.FirstOrDefault(x => x.Name == ruleName);
                string        newAddresses = string.Join(',', remoteAddresses);
                if (rule is null)
                {
                    INetFwRule newRule = (INetFwRule)Activator.CreateInstance(typeFWRule);
                    newRule.Name            = ruleName;
                    newRule.Description     = "Block inbound traffic over TCP port 3389";
                    newRule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                    newRule.LocalPorts      = "3389";
                    newRule.RemoteAddresses = newAddresses;
                    newRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                    newRule.Enabled         = true;
                    newRule.Grouping        = "@firewallapi.dll,-23255";
                    newRule.Profiles        = fwPolicy2.CurrentProfileTypes;
                    newRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                    fwPolicy2.Rules.Add(newRule);
                }
                else
                {
                    rule.RemoteAddresses += $",{newAddresses}";
                }
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Blocked! IP : {newAddresses}");
                Console.ResetColor();
            }
            catch (COMException ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #30
0
        private void firewallRule_Click(object sender, EventArgs e)
        {
            INetFwPolicy2 policy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            INetFwRule    rule   = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwRule"));

            try
            {
                rule.Name       = "Dynamic Firewall Creation";
                rule.Direction  = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                rule.Protocol   = (int)ProtocolType.Tcp;
                rule.LocalPorts = Server.PORT.ToString();
                rule.Action     = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                rule.Enabled    = true;
                policy.Rules.Add(rule);
                MessageBox.Show("Succesfuly created Firewall Rule", "Success", MessageBoxButtons.OK);
            }
            catch (Exception err)
            {
                MessageBox.Show($"Couldn't create new Firewall rule\nError Message: {err.Message}", "Error", MessageBoxButtons.OK);
            }
        }
Beispiel #31
-1
        public void CreateNewRule(FirewallRuleEntry entry)
        {
            _rule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromCLSID(netFwRuleUuid));
            _rule.Action = (NET_FW_ACTION_)((int)entry.RuleAction);//NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            _rule.ApplicationName = entry.ApplicationPath;
            _rule.Description = entry.Description;
            _rule.Direction = (NET_FW_RULE_DIRECTION_)((int)entry.Direction);//NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            _rule.EdgeTraversal = entry.EdgeTraversal;
            _rule.Enabled = entry.Enabled;
            _rule.Grouping = entry.GroupName;
            _rule.Name = entry.RuleName;
            _rule.Protocol = (int)entry.Protocol;

            _policy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromCLSID(netFwPolicy2Uuid));
            _policy.Rules.Add(_rule);
        }
Beispiel #32
-2
        /// <summary>
        /// 
        /// </summary>
        /// <param name="instanceName">Name of the firewall rule</param>
        /// <param name="description">Description of the firewall rule</param>
        public FWBanManager(string instanceName, string description)
        {
            banList = new ConcurrentDictionary<string, int>();

            try
            {
                firewall = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWPolicy2"));
                rule = FindFWRule(instanceName);

                if (rule == null)
                {
                    rule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HnetCfg.FWRule"));
                    rule.Name = instanceName;
                    if (description != null && description.Length > 0)
                        rule.Description = description;
                    rule.Enabled = true;
                    rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                    rule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                    rule.RemoteAddresses = "255.255.255.255-255.255.255.255";
                    firewall.Rules.Add(rule);
                }
                else
                {
                    rule.Enabled = true;
                    LoadFirewallList();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #33
-5
        public FwOutRule(INetFwRule fwRule)
            : this(FwRuleText.Empty)
        {
            ApplicationName = fwRule.ApplicationName;
            Name = fwRule.Name;
            Description = fwRule.Description;

            _remoteAddresses = fwRule.RemoteAddresses.Split(',')[0];

            SetMaskFromRemoteAddresses();

            Text = new FwRuleText(IPStr);
        }