/// <inheritdoc />
        /// <summary>
        ///     Creates a rule about an executable file (application) to be registered to a firewall profile
        /// </summary>
        /// <param name="profile">The profile that the rule belongs to</param>
        /// <param name="name">Name of the rule</param>
        /// <param name="action">Action of the rule</param>
        /// <param name="filename">Address of the executable file that the rule applies to</param>
        /// <param name="protocol">Protocol that the rule applies to</param>
        /// <returns>Returns the newly created rule object implementing <see cref="T:WindowsFirewallHelper.IRule" /> interface</returns>
        /// <exception cref="T:System.NotSupportedException">This class is not supported on this machine</exception>
        /// <exception cref="T:WindowsFirewallHelper.FirewallAPIv1.FirewallAPIv1NotSupportedException">
        ///     The asked setting is not
        ///     supported with this class
        /// </exception>
        // ReSharper disable once TooManyArguments
        public IRule CreateApplicationRule(
            FirewallProfiles profile,
            string name,
            // ReSharper disable once FlagArgument
            FirewallAction action,
            string filename,
            FirewallProtocol protocol)
        {
            if (!IsSupported)
            {
                throw new NotSupportedException();
            }

            if (!protocol.Equals(FirewallProtocol.Any))
            {
                throw new FirewallAPIv1NotSupportedException();
            }

            if (action != FirewallAction.Allow)
            {
                throw new FirewallAPIv1NotSupportedException();
            }

            return(new ApplicationRule(name, filename, profile));
        }
Exemple #2
0
 /// <summary>
 ///     Creates a new application rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 public StandardRuleWin7(string name, FirewallAction action, FirewallDirection direction,
                         FirewallProfiles profiles) : base(name, action, direction, profiles)
 {
     if (UnderlyingObjectV2 == null)
     {
         throw new FirewallAPIv2NotSupportedException();
     }
 }
 /// <inheritdoc />
 /// <summary>
 ///     Creates a new port rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="port">Port number of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRuleWin8(
     string name,
     ushort port,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles) : base(name, port, action, direction, profiles)
 {
 }
 /// <inheritdoc />
 /// <summary>
 ///     Creates a rule about an executable file (application) to be registered to a firewall profile
 /// </summary>
 /// <param name="profiles">The profile or profiles that the rule belongs to</param>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action of the rule</param>
 /// <param name="filename">Address of the executable file that the rule applies to</param>
 /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns>
 /// <exception cref="NotSupportedException">This class is not supported on this machine</exception>
 // ReSharper disable once TooManyArguments
 public IRule CreateApplicationRule(
     FirewallProfiles profiles,
     string name,
     FirewallAction action,
     string filename)
 {
     return(CreateApplicationRule(profiles, name, action, filename, FirewallProtocol.Any));
 }
 /// <summary>
 ///     Creates a new general rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRuleWin7(
     string name,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles) :
     base(name, action, direction, profiles)
 {
 }
 /// <summary>
 ///     Creates a new application rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="filename">Address of the executable file</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRule(
     string name,
     string filename,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles) : this(name, action, direction, profiles)
 {
     ApplicationName = filename;
 }
 /// <summary>
 ///     Creates a new general rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRule(
     string name,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles
     ) :
     this(name, action, direction, profiles, new COMTypeResolver())
 {
 }
 /// <summary>
 ///     Creates a new application rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 public StandardRule(string name, FirewallAction action, FirewallDirection direction, FirewallProfiles profiles)
 {
     UnderlyingObject = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID(@"HNetCfg.FWRule"));
     Name             = name;
     Action           = action;
     Direction        = direction;
     IsEnable         = true;
     Profiles         = profiles;
 }
Exemple #9
0
 /// <summary>
 ///     Creates a new port rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="port">Port number of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 public StandardRuleWin8(string name, ushort port, FirewallAction action, FirewallDirection direction,
                         FirewallProfiles profiles)
     : base(name, port, action, direction, profiles)
 {
     UnderlyingObjectV3 = UnderlyingObject as INetFwRule3;
     if (UnderlyingObjectV3 == null)
     {
         throw new FirewallAPIv2NotSupportedException();
     }
 }
 /// <summary>
 ///     Creates a new application rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="filename">Address of the executable file</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 /// <param name="typeResolver">The COM+ object resolver</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRuleWin7(
     string name,
     string filename,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles,
     COMTypeResolver typeResolver
     ) : base(name, filename, action, direction, profiles, typeResolver)
 {
 }
 /// <summary>
 ///     Creates a new port rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="port">Port number of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRule(
     string name,
     ushort port,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles) : this(name, action, direction, profiles)
 {
     Protocol   = FirewallProtocol.TCP;
     LocalPorts = new[] { port };
 }
Exemple #12
0
 /// <summary>
 ///     Creates a new port rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="port">Port number of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 /// <param name="typeResolver">The COM+ object resolver</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRuleWin8(
     string name,
     ushort port,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles,
     COMTypeResolver typeResolver
     ) : base(name, port, action, direction, profiles, typeResolver)
 {
 }
 /// <summary>
 ///     Creates a new application rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="filename">Address of the executable file</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 /// <param name="typeResolver">The COM+ object resolver</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRule(
     string name,
     string filename,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles,
     COMTypeResolver typeResolver
     ) : this(name, action, direction, profiles, typeResolver)
 {
     ApplicationName = filename;
 }
 /// <summary>
 ///     Creates a rule about a port to be registered to a firewall profile
 /// </summary>
 /// <param name="profiles">The profile or profiles that the rule belongs to</param>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action of the rule</param>
 /// <param name="portNumber">Port number that the rule applies to</param>
 /// <param name="protocol">Protocol that the rule applies to</param>
 /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns>
 /// <exception cref="NotSupportedException">This class is not supported on this machine</exception>
 public IRule CreatePortRule(FirewallProfiles profiles, string name, FirewallAction action, ushort portNumber,
                             FirewallProtocol protocol)
 {
     if (!IsSupported)
     {
         throw new NotSupportedException();
     }
     return(new StandardRule(name, portNumber, action, FirewallDirection.Inbound, profiles)
     {
         Protocol = protocol
     });
 }
Exemple #15
0
 /// <summary>
 ///     Creates a rule about an executable file (application) to be registered to a firewall profile
 /// </summary>
 /// <param name="profiles">The profile or profiles that the rule belongs to</param>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action of the rule</param>
 /// <param name="filename">Address of the executable file that the rule applies to</param>
 /// <param name="protocol">Protocol that the rule applies to</param>
 /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns>
 /// <exception cref="NotSupportedException">This class is not supported on this machine</exception>
 public IRule CreateApplicationRule(FirewallProfiles profiles, string name, FirewallAction action,
                                    string filename, FirewallProtocol protocol)
 {
     if (!IsSupported)
     {
         throw new NotSupportedException();
     }
     return(new StandardRule(name, filename, action, FirewallDirection.Inbound, profiles)
     {
         Protocol = protocol
     });
 }
 /// <summary>
 ///     Creates a new general rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRule(
     string name,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles) :
     this(ComHelper.CreateInstance <INetFwRule>())
 {
     Name      = name;
     Action    = action;
     Direction = direction;
     IsEnable  = true;
     Profiles  = profiles;
 }
 /// <summary>
 ///     Creates a new general rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 /// <param name="typeResolver">The COM+ object resolver</param>
 // ReSharper disable once TooManyDependencies
 public FirewallWASRule(
     string name,
     FirewallAction action,
     FirewallDirection direction,
     FirewallProfiles profiles,
     COMTypeResolver typeResolver
     ) :
     this(typeResolver.CreateInstance <INetFwRule>())
 {
     Name      = name;
     Action    = action;
     Direction = direction;
     IsEnable  = true;
     Profiles  = profiles;
 }
 /// <summary>
 ///     Creates a rule about a port to be registered to a firewall profile
 /// </summary>
 /// <param name="profile">The profile that the rule belongs to</param>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action of the rule</param>
 /// <param name="portNumber">Port number that the rule applies to</param>
 /// <param name="protocol">Protocol that the rule applies to</param>
 /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns>
 /// <exception cref="NotSupportedException">This class is not supported on this machine</exception>
 /// <exception cref="FirewallAPIv1NotSupportedException">The asked setting is not supported with this class</exception>
 public IRule CreatePortRule(FirewallProfiles profile, string name, FirewallAction action, ushort portNumber,
                             FirewallProtocol protocol)
 {
     if (!IsSupported)
     {
         throw new NotSupportedException();
     }
     if (action != FirewallAction.Allow)
     {
         throw new FirewallAPIv1NotSupportedException();
     }
     return(new PortRule(name, portNumber, profile)
     {
         Protocol = protocol
     });
 }
Exemple #19
0
 /// <summary>
 ///     Creates a rule about a port to be registered to a firewall profile
 /// </summary>
 /// <param name="profiles">The profile or profiles that the rule belongs to</param>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action of the rule</param>
 /// <param name="portNumber">Port number that the rule applies to</param>
 /// <param name="protocol">Protocol that the rule applies to</param>
 /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns>
 /// <exception cref="NotSupportedException">This class is not supported on this machine</exception>
 public IRule CreatePortRule(FirewallProfiles profiles, string name, FirewallAction action, ushort portNumber,
                             FirewallProtocol protocol)
 {
     if (!IsSupported)
     {
         throw new NotSupportedException();
     }
     if (!protocol.Equals(FirewallProtocol.TCP) && protocol.Equals(FirewallProtocol.UDP))
     {
         throw new FirewallAPIv2InvalidProtocolException(
                   "Invalid protocol selected; rule's protocol should be TCP or UDP.");
     }
     return(new StandardRule(name, portNumber, action, FirewallDirection.Inbound, profiles)
     {
         Protocol = protocol
     });
 }
 /// <summary>
 ///     Creates a new port rule for Windows Firewall with Advanced Security
 /// </summary>
 /// <param name="name">Name of the rule</param>
 /// <param name="port">Port number of the rule</param>
 /// <param name="action">Action that this rule defines</param>
 /// <param name="direction">Data direction in which this rule applies to</param>
 /// <param name="profiles">The profile that this rule belongs to</param>
 public StandardRule(string name, ushort port, FirewallAction action, FirewallDirection direction,
                     FirewallProfiles profiles)
 {
     UnderlyingObject = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID(@"HNetCfg.FWRule"));
     Name             = name;
     Action           = action;
     Direction        = direction;
     Protocol         = FirewallProtocol.TCP;
     IsEnable         = true;
     Profiles         = profiles;
     if (direction == FirewallDirection.Inbound)
     {
         LocalPorts = new[] { port };
     }
     else
     {
         RemotePorts = new[] { port };
     }
 }
        public static void AddRule(String name, FirewallAction action, FirewallProtocol protocol, FirewallDirection direction
                                   , Int32[] localPorts, Int32[] remotePorts, String serviceName = null)
        {
            //Don't add if it already exists
            var policy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

            if (policy.Rules.Cast <INetFwRule3>().Any(rule => rule.Name == name))
            {
                return;
            }

            //Add new rule
            var newRule = (INetFwRule3)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            newRule.Enabled  = true;
            newRule.Action   = (NET_FW_ACTION_)action;
            newRule.Protocol = (Int32)protocol;
            if (localPorts != null)
            {
                newRule.LocalPorts = String.Join(",", localPorts);
            }
            if (remotePorts != null)
            {
                newRule.RemotePorts = String.Join(",", remotePorts);
            }
            newRule.Direction = (NET_FW_RULE_DIRECTION_)direction;
            if (serviceName != null)
            {
                newRule.serviceName = serviceName;
            }
            newRule.Name = name;
            //newRule.Grouping = group;
            newRule.Profiles = (Int32)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;

            policy.Rules.Add(newRule);
        }
Exemple #22
0
        private static void Main()
        {
            ConsoleWriter.Default.PrintMessage("Firewall Control");

            // Информация о версии  брандмауэра
            ConsoleWriter.Default.PrintMessage($"Firewall Version: {FirewallManager.Version}");

            // Экземпляр ('пульт') управления брандмауэром
            var firewallInstance = FirewallManager.Instance;

            ConsoleWriter.Default.PrintMessage($"Type of control: {firewallInstance.Name}");

            // Если версия брандмауэра неизвестная или недействительна
            if (FirewallManager.Version == FirewallAPIVersion.None)
            {
                ConsoleWriter.Default.PrintMessage("Press any key to exit.");
                Console.ReadKey();

                // То выход
                return;
            }

            // Панель навигации
            // Генеральная консоль
            ConsoleNavigation.Default.PrintNavigation(new[]
            {
                // Консоль для профилей
                new ConsoleNavigationItem("Profiles", (i, item) =>
                {
                    // Консоль подпунктов профилей
                    ConsoleNavigation.Default.PrintNavigation(

                        // Объект кладем в массив
                        firewallInstance.Profiles.ToArray(), (i1, profile) =>

                    {       // Выводим данные о конкретном профиле
                        ConsoleWriter.Default.WriteObject(profile);
                        ConsoleWriter.Default.PrintMessage("Press any key to get one step back.");

                        // Возврат
                        Console.ReadKey();
                    },
                        "Select a profile to view its settings."
                        );
                }),

                // Консоль для правил
                new ConsoleNavigationItem("Rules", (i, item) =>
                {
                    // Консоль всех правил
                    ConsoleNavigation.Default.PrintNavigation(

                        // Сортируем правила в алфавитном порядке
                        // Каждое правило (объект) кладем в массив
                        firewallInstance.Rules.OrderBy((rule) => rule.FriendlyName).ToArray(), (i1, rule) =>
                    {
                        // Вывод правила
                        ConsoleWriter.Default.WriteObject(rule);
                        ConsoleWriter.Default.PrintMessage("Press any key to get one step back.");

                        // Возврат
                        Console.ReadKey();
                    },
                        "Select a rule to view its settings."
                        );
                }),

                new ConsoleNavigationItem("Create rule", (i, item) => {
                    // Задание правилу профиля
                    string profile = ConsoleWriter.Default.PrintQuestion("Enter type of profile");
                    if (profile.ToUpper() == "PUBLIC" || profile.ToUpper() == "DOMAIN" || profile.ToUpper() == "PRIVATE")
                    {
                        FirewallProfiles firewallProfile = FirewallProfiles.Public;
                        if (profile.ToUpper() == "PUBLIC")
                        {
                            firewallProfile = FirewallProfiles.Public;
                        }

                        if (profile.ToUpper() == "DOMAIN")
                        {
                            firewallProfile = FirewallProfiles.Domain;
                        }

                        if (profile.ToUpper() == "PRIVATE")
                        {
                            firewallProfile = FirewallProfiles.Private;
                        }

                        // Имя правила
                        string name = ConsoleWriter.Default.PrintQuestion("Enter name of rule");
                        if (name != "")
                        {
                            // Тип доступа
                            FirewallAction firewallaction = FirewallAction.Block;
                            string action = ConsoleWriter.Default.PrintQuestion("Enter type of acces");
                            if (action.ToUpper() == "ALLOW" || action.ToUpper() == "BLOCK")
                            {
                                if (action.ToUpper() == "ALLOW")
                                {
                                    firewallaction = FirewallAction.Allow;
                                }
                                if (action.ToUpper() == "BLOCK")
                                {
                                    firewallaction = FirewallAction.Block;
                                }

                                string fullPath = ConsoleWriter.Default.PrintQuestion("Enter full path of exe file");

                                var rule = firewallInstance.CreateApplicationRule(
                                    firewallProfile,
                                    @$ "{name}",
                                    firewallaction,
                                    @$ "{fullPath}"
                                    );
                                rule.Direction = FirewallDirection.Outbound;
                                firewallInstance.Rules.Add(rule);
                                ConsoleWriter.Default.PrintSuccess("Rule successfully aded");
                            }
                            else
                            {
                                ConsoleWriter.Default.PrintError("This type of acces is invalid");
                            }
                        }
                        else
                        {
                            ConsoleWriter.Default.PrintError("This name of rule is invalid");
                        }
                    }
                    else
                    {
                        ConsoleWriter.Default.PrintError("This profile name is invalid");
                    }

                    ConsoleWriter.Default.PrintMessage("Press any key to get one step back.");

                    // Вsозврат
                    Console.ReadKey();
                }),
                new ConsoleNavigationItem("Create port rule", (i, item) => {
                    string name = ConsoleWriter.Default.PrintQuestion("Enter name of port rule");
                    if (name != "")
                    {
                        string action = ConsoleWriter.Default.PrintQuestion("Enter type of access");
                        FirewallAction firewallAction = FirewallAction.Block;

                        if (action.ToUpper() == "ALLOW" || action.ToUpper() == "BLOCK")
                        {
                            if (action.ToUpper() == "ALLOW")
                            {
                                firewallAction = FirewallAction.Allow;
                            }

                            if (action.ToUpper() == "BLOCK")
                            {
                                firewallAction = FirewallAction.Block;
                            }

                            string port        = ConsoleWriter.Default.PrintQuestion("Enter port");
                            ushort finallyPort = Convert.ToUInt16(port);
                            string protocol    = ConsoleWriter.Default.PrintQuestion("Enter protocol");
                            FirewallProtocol firewallProtocol = FirewallProtocol.TCP;

                            if (protocol.ToUpper() == "UDP" || protocol.ToUpper() == "TCP")
                            {
                                if (protocol.ToUpper() == "UDP")
                                {
                                    firewallProtocol = FirewallProtocol.UDP;
                                }

                                if (protocol.ToUpper() == "TCP")
                                {
                                    firewallProtocol = FirewallProtocol.TCP;
                                }
                                var rule = firewallInstance.CreatePortRule(
                                    @$ "{name}",
                                    firewallAction,
                                    finallyPort,
                                    firewallProtocol
                                    );
                                firewallInstance.Rules.Add(rule);
                                ConsoleWriter.Default.PrintSuccess("Protocol rule successfully aded");
                            }
                            else
                            {
                                ConsoleWriter.Default.PrintError("This protocol is invalid");
                            }
                        }
                        else
                        {
                            ConsoleWriter.Default.PrintError("This type of acces is invalid");
                        }
                    }
                    else
                    {
                        ConsoleWriter.Default.PrintError("This name of port rule is invalid");
                    }

                    // Возврат
                    Console.ReadKey();
                }),
                new ConsoleNavigationItem("Delete rule", (i, item) => {
                    string deleted = ConsoleWriter.Default.PrintQuestion("Enter name of rule");
                    var rule       = firewallInstance.Rules.SingleOrDefault(r => r.Name == deleted);
                    if (rule != null)
                    {
                        firewallInstance.Rules.Remove(rule);
                        ConsoleWriter.Default.PrintSuccess("Rule was successfully deleted");
                    }
                    else
                    {
                        ConsoleWriter.Default.PrintError("This name rule is invalid");
                    }
                })
            }, "Select an execution path.");
        }
        public static void AddRuleVista(string name, string description = null, FirewallAction action = FirewallAction.Allow, string applicationPath = null, Protocol protocol = Protocol.IPv4, string localPorts = null, string remotePorts = null, string localAddresses = null, string remoteAddresses = null, InterfaceTypeFlags interfaceType = InterfaceTypeFlags.All, bool enable = true, Direction direction = Direction.Inbound, bool edgeTraversal = false)
        {
            INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            firewallRule.Name            = name;
            firewallRule.Description     = description;
            firewallRule.ApplicationName = applicationPath;
            firewallRule.Enabled         = enable;

            firewallRule.Protocol = (int)protocol;

            if (localPorts != null)
            {
                firewallRule.LocalPorts = localPorts;
            }
            if (remotePorts != null)
            {
                firewallRule.RemotePorts = remotePorts;
            }

            if (localAddresses != null)
            {
                firewallRule.LocalAddresses = localAddresses;
            }
            if (remoteAddresses != null)
            {
                firewallRule.RemoteAddresses = remoteAddresses;
            }

            switch (direction)
            {
            case Direction.Inbound:
                firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                break;

            default:
                firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
                break;
            }

            firewallRule.EdgeTraversal = edgeTraversal;

            if (interfaceType == InterfaceTypeFlags.All)
            {
                firewallRule.InterfaceTypes = "All";
            }
            else
            {
                string interfaceTypeString = "";

                if ((interfaceType & InterfaceTypeFlags.Lan) > 0)
                {
                    interfaceTypeString += ",Lan";
                }

                if ((interfaceType & InterfaceTypeFlags.Wireless) > 0)
                {
                    interfaceTypeString += ",Wireless";
                }

                if ((interfaceType & InterfaceTypeFlags.RemoteAccess) > 0)
                {
                    interfaceTypeString += ",RemoteAccess";
                }

                if (interfaceTypeString.Length > 0)
                {
                    firewallRule.InterfaceTypes = interfaceTypeString.Substring(1);
                }
            }

            switch (action)
            {
            case FirewallAction.Allow:
                firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                break;

            default:
                firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                break;
            }

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

            firewallPolicy.Rules.Add(firewallRule);
        }
Exemple #24
0
 private IEnumerable <IFirewallRule> GetFirewallUDPRuleByAction(ushort PortNumber, FirewallAction RuleAction) =>
 this.FindMatchingFirewallRules(PortNumber, FirewallProtocol.UDP).Where(
     Rule => Rule.IsEnable && Rule.Action.Equals(RuleAction)
     );
 /// <summary>
 /// Constructs a new FirewallResponse with the given action.
 /// </summary>
 /// <param name="action">
 /// The action to take.
 /// </param>
 /// <param name="encryptHint">
 /// Optional encryption hint. This enables the client to provide a hint to the filtering
 /// engine as to whether or not some application on some non-standard port is using HTTPS
 /// encryption. If this is set to a non-null value, and the flow is on a non-standard port,
 /// then the engine will handle the flow according to this value.
 /// </param>
 public FirewallResponse(FirewallAction action, bool?encryptHint = null)
 {
     Action        = action;
     EncryptedHint = encryptHint;
 }
Exemple #26
0
 /// <summary>
 ///     Creates a rule about a port to be registered to a firewall profile
 /// </summary>
 /// <param name="profiles">The profile or profiles that the rule belongs to</param>
 /// <param name="name">Name of the rule</param>
 /// <param name="action">Action of the rule</param>
 /// <param name="portNumber">Port number that the rule applies to</param>
 /// <returns>Returns the newly created rule object implementing <see cref="IRule" /> interface</returns>
 /// <exception cref="NotSupportedException">This class is not supported on this machine</exception>
 public IRule CreatePortRule(FirewallProfiles profiles, string name, FirewallAction action, ushort portNumber)
 {
     return(CreatePortRule(profiles, name, action, portNumber, FirewallProtocol.TCP));
 }