Пример #1
0
 public void ExecuteWindows()
 {
     foreach (IFirewallRule rule in FirewallManager.Instance.Rules.ToArray())
     {
         try
         {
             var obj = new FirewallObject()
             {
                 Action          = rule.Action,
                 ApplicationName = rule.ApplicationName,
                 Direction       = rule.Direction,
                 FriendlyName    = rule.FriendlyName,
                 IsEnable        = rule.IsEnable,
                 LocalPortType   = rule.LocalPortType,
                 Name            = rule.Name,
                 Profiles        = rule.Profiles,
                 Protocol        = rule.Protocol.ProtocolNumber.ToString(CultureInfo.InvariantCulture),
                 Scope           = rule.Scope,
                 ServiceName     = rule.ServiceName
             };
             obj.LocalAddresses.AddRange(rule.LocalAddresses.ToList().ConvertAll(address => address.ToString()));
             obj.LocalPorts.AddRange(rule.LocalPorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture)));
             obj.RemoteAddresses.AddRange(rule.RemoteAddresses.ToList().ConvertAll(address => address.ToString()));
             obj.RemotePorts.AddRange(rule.RemotePorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture)));
             DatabaseManager.Write(obj, RunId);
         }
         catch (Exception e)
         {
             Log.Debug(e, "Exception hit while processing Firewall rules");
             Dictionary <string, string> ExceptionEvent = new Dictionary <string, string>();
             ExceptionEvent.Add("Exception Type", e.GetType().ToString());
             AsaTelemetry.TrackEvent("WindowsFirewallObjectCreationException", ExceptionEvent);
         }
     }
 }
 /// <summary>
 /// Uses a library to access the Windows Firewall.
 /// </summary>
 public void ExecuteWindows()
 {
     foreach (IFirewallRule rule in FirewallManager.Instance.Rules.ToArray())
     {
         var obj = new FirewallObject()
         {
             Action          = rule.Action,
             ApplicationName = rule.ApplicationName,
             Direction       = rule.Direction,
             FriendlyName    = rule.FriendlyName,
             IsEnable        = rule.IsEnable,
             LocalAddresses  = rule.LocalAddresses.ToList().ConvertAll(address => address.ToString()),
             LocalPorts      = rule.LocalPorts.ToList().ConvertAll(port => port.ToString()),
             LocalPortType   = rule.LocalPortType,
             Name            = rule.Name,
             Profiles        = rule.Profiles,
             Protocol        = rule.Protocol.ProtocolNumber.ToString(),
             RemoteAddresses = rule.RemoteAddresses.ToList().ConvertAll(address => address.ToString()),
             RemotePorts     = rule.RemotePorts.ToList().ConvertAll(port => port.ToString()),
             Scope           = rule.Scope,
             ServiceName     = rule.ServiceName
         };
         DatabaseManager.Write(obj, runId);
     }
 }
 /// <summary>
 /// Uses a library to access the Windows Firewall.
 /// </summary>
 public void ExecuteWindows()
 {
     foreach (IFirewallRule rule in FirewallManager.Instance.Rules.ToArray())
     {
         try
         {
             var obj = new FirewallObject()
             {
                 Action          = rule.Action,
                 ApplicationName = rule.ApplicationName,
                 Direction       = rule.Direction,
                 FriendlyName    = rule.FriendlyName,
                 IsEnable        = rule.IsEnable,
                 LocalPortType   = rule.LocalPortType,
                 Name            = rule.Name,
                 Profiles        = rule.Profiles,
                 Protocol        = rule.Protocol.ProtocolNumber.ToString(CultureInfo.InvariantCulture),
                 Scope           = rule.Scope,
                 ServiceName     = rule.ServiceName
             };
             obj.LocalAddresses.AddRange(rule.LocalAddresses.ToList().ConvertAll(address => address.ToString()));
             obj.LocalPorts.AddRange(rule.LocalPorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture)));
             obj.RemoteAddresses.AddRange(rule.RemoteAddresses.ToList().ConvertAll(address => address.ToString()));
             obj.RemotePorts.AddRange(rule.RemotePorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture)));
             DatabaseManager.Write(obj, RunId);
         }
         catch (Exception e)
         {
             Log.Debug(e, rule.FriendlyName);
         }
     }
 }
Пример #4
0
        internal void ExecuteWindows(CancellationToken cancellationToken)
        {
            try
            {
                foreach (IFirewallRule rule in FirewallManager.Instance.Rules)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    try
                    {
                        var obj = new FirewallObject(rule.Name)
                        {
                            Action          = rule.Action,
                            ApplicationName = rule.ApplicationName,
                            Direction       = rule.Direction,
                            FriendlyName    = rule.FriendlyName,
                            IsEnable        = rule.IsEnable,
                            LocalPortType   = rule.LocalPortType,
                            Profiles        = rule.Profiles,
                            Protocol        = rule.Protocol.ProtocolNumber.ToString(CultureInfo.InvariantCulture),
                            Scope           = rule.Scope,
                            ServiceName     = rule.ServiceName
                        };
                        obj.LocalAddresses  = rule.LocalAddresses.ToList().ConvertAll(address => address.ToString());
                        obj.LocalPorts      = rule.LocalPorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture));
                        obj.RemoteAddresses = rule.RemoteAddresses.ToList().ConvertAll(address => address.ToString());
                        obj.RemotePorts     = rule.RemotePorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture));
                        HandleChange(obj);
                    }
                    catch (Exception e)
                    {
                        Log.Debug(e, "Exception hit while processing Firewall rules");
                        Dictionary <string, string> ExceptionEvent = new Dictionary <string, string>();
                        ExceptionEvent.Add("Exception Type", e.GetType().ToString());
                        AsaTelemetry.TrackEvent("WindowsFirewallObjectCreationException", ExceptionEvent);
                    }
                }
            }
            catch (Exception e) when(
                e is COMException ||
                e is NotSupportedException)
            {
                Log.Warning(Strings.Get("CollectorNotSupportedOnPlatform"), GetType().ToString());
            }
        }
Пример #5
0
        /// <summary>
        ///     Dumps from iptables.
        /// </summary>
        internal void ExecuteLinux(CancellationToken cancellationToken)
        {
            if (ExternalCommandRunner.RunExternalCommand("iptables", "-S", out string result, out string _) == 0)
            {
                var lines = new List <string>(result.Split('\n'));

                Dictionary <string, FirewallAction> defaultPolicies = new Dictionary <string, FirewallAction>();

                foreach (var line in lines)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    if (line.StartsWith("-P"))
                    {
                        var chainName = line.Split(' ')[1];
                        defaultPolicies.Add(chainName, line.Contains("ACCEPT") ? FirewallAction.Allow : FirewallAction.Block);
                        var obj = new FirewallObject($"Default {chainName} policy")
                        {
                            Action       = defaultPolicies[chainName],
                            FriendlyName = $"Default {chainName} policy",
                            Scope        = FirewallScope.All
                        };
                        if (!chainName.Equals("FORWARD"))
                        {
                            obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound;
                        }

                        HandleChange(obj);
                    }
                    else if (line.StartsWith("-A"))
                    {
                        var splits    = line.Split(' ');
                        var chainName = splits[1];

                        var obj = new FirewallObject(line)
                        {
                            Action       = (splits[Array.IndexOf(splits, "-j") + 1] == "ACCEPT") ? FirewallAction.Allow : FirewallAction.Block,
                            FriendlyName = line,
                            Scope        = FirewallScope.All,
                            Protocol     = splits[Array.IndexOf(splits, "-p") + 1]
                        };

                        if (Array.IndexOf(splits, "--dport") > 0)
                        {
                            obj.RemotePorts = splits[Array.IndexOf(splits, "--dport") + 1].OfType <string>().ToList();
                        }

                        if (Array.IndexOf(splits, "-d") > 0)
                        {
                            obj.RemoteAddresses = splits[Array.IndexOf(splits, "-d") + 1].OfType <string>().ToList();
                        }

                        if (Array.IndexOf(splits, "-s") > 0)
                        {
                            obj.LocalAddresses = splits[Array.IndexOf(splits, "-s") + 1].OfType <string>().ToList();
                        }

                        if (Array.IndexOf(splits, "--sport") > 0)
                        {
                            obj.LocalPorts = splits[Array.IndexOf(splits, "--sport") + 1].OfType <string>().ToList();
                        }

                        if (!chainName.Equals("FORWARD"))
                        {
                            obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound;
                        }

                        HandleChange(obj);
                    }
                }
            }
        }
Пример #6
0
        /// <summary>
        ///     Talks to socketfilterfw
        /// </summary>
        internal void ExecuteMacOs(CancellationToken cancellationToken)
        {
            // Example output: "Firewall is enabled. (State = 1)"
            var result  = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate");
            var enabled = result.Contains("1");
            var obj     = new FirewallObject("Firewall Enabled")
            {
                Action       = FirewallAction.Block,
                Direction    = FirewallDirection.Inbound,
                IsEnable     = enabled,
                FriendlyName = "Firewall Enabled",
                Scope        = FirewallScope.All
            };

            HandleChange(obj);

            // Example output: "Stealth mode disabled"
            result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate");
            obj    = new FirewallObject("Stealth Mode")
            {
                Action       = FirewallAction.Block,
                Direction    = FirewallDirection.Inbound,
                IsEnable     = result.Contains("enabled"),
                FriendlyName = "Stealth Mode",
                Scope        = FirewallScope.All
            };
            HandleChange(obj);

            /* Example Output:
             * Automatically allow signed built-in software ENABLED
             * Automatically allow downloaded signed software ENABLED */
            result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getallowsigned");
            obj    = new FirewallObject("Allow signed built-in software")
            {
                Action       = FirewallAction.Allow,
                Direction    = FirewallDirection.Inbound,
                IsEnable     = result.Split('\n')[0].Contains("ENABLED"),
                FriendlyName = "Allow signed built-in software",
                Scope        = FirewallScope.All
            };
            HandleChange(obj);

            obj = new FirewallObject("Allow downloaded signed software")
            {
                Action       = FirewallAction.Allow,
                Direction    = FirewallDirection.Inbound,
                IsEnable     = result.Split('\n')[1].Contains("ENABLED"),
                FriendlyName = "Allow downloaded signed software",
                Scope        = FirewallScope.All
            };
            HandleChange(obj);

            /* Example Output:
             * ALF: total number of apps = 2
             *
             * 1 :  /Applications/AppName.app
             * ( Allow incoming connections )
             *
             * 2 :  /Applications/AppName2.app
             * ( Block incoming connections ) */
            result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--listapps");
            string appName          = "";
            Regex  startsWithNumber = new Regex("^[1-9]");
            var    lines            = new List <string>(result.Split('\n'));

            if (lines.Any())
            {
                lines = lines.Skip(2).ToList();
                foreach (var line in lines)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    if (startsWithNumber.IsMatch(line))
                    {
                        appName = line.Substring(line.IndexOf('/'));
                    }
                    else if (line.Contains("incoming connections"))
                    {
                        obj = new FirewallObject(appName)
                        {
                            Action       = (line.Contains("Allow")) ? FirewallAction.Allow : FirewallAction.Block,
                            Direction    = FirewallDirection.Inbound,
                            FriendlyName = appName,
                            Scope        = FirewallScope.All
                        };
                        HandleChange(obj);
                    }
                }
            }
        }
        public void TestSerializeAndDeserializeFirewallObject()
        {
            var fwo = new FirewallObject("Test");

            Assert.IsTrue(fwo.RowKey.Equals(JsonUtils.Hydrate(JsonUtils.Dehydrate(fwo), RESULT_TYPE.FIREWALL)?.RowKey));
        }
        /// <summary>
        /// Dumps from iptables.
        /// </summary>
        public void ExecuteLinux()
        {
            var result = ExternalCommandRunner.RunExternalCommand("iptables", "-S");

            var lines = new List <string>(result.Split('\n'));

            Dictionary <string, FirewallAction> defaultPolicies = new Dictionary <string, FirewallAction>();

            foreach (var line in lines)
            {
                if (line.StartsWith("-P"))
                {
                    var chainName = line.Split(' ')[1];
                    defaultPolicies.Add(chainName, line.Contains("ACCEPT") ? FirewallAction.Allow : FirewallAction.Block);
                    var obj = new FirewallObject()
                    {
                        Action       = defaultPolicies[chainName],
                        FriendlyName = $"Default {chainName} policy",
                        Name         = $"Default {chainName} policy",
                        Scope        = FirewallScope.All
                    };
                    if (!chainName.Equals("FORWARD"))
                    {
                        obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound;
                    }

                    DatabaseManager.Write(obj, RunId);
                }
                else if (line.StartsWith("-A"))
                {
                    var splits    = line.Split(' ');
                    var chainName = splits[1];


                    var obj = new FirewallObject()
                    {
                        Action       = (splits[Array.IndexOf(splits, "-j") + 1] == "ACCEPT") ? FirewallAction.Allow : FirewallAction.Block,
                        FriendlyName = line,
                        Name         = line,
                        Scope        = FirewallScope.All,
                        Protocol     = splits[Array.IndexOf(splits, "-p") + 1]
                    };

                    if (Array.IndexOf(splits, "--dport") > 0)
                    {
                        obj.RemotePorts.Add(splits[Array.IndexOf(splits, "--dport") + 1]);
                    }

                    if (Array.IndexOf(splits, "-d") > 0)
                    {
                        obj.RemoteAddresses.Add(splits[Array.IndexOf(splits, "-d") + 1]);
                    }

                    if (Array.IndexOf(splits, "-s") > 0)
                    {
                        obj.LocalAddresses.Add(splits[Array.IndexOf(splits, "-s") + 1]);
                    }

                    if (Array.IndexOf(splits, "--sport") > 0)
                    {
                        obj.LocalPorts.Add(splits[Array.IndexOf(splits, "--sport") + 1]);
                    }

                    if (!chainName.Equals("FORWARD"))
                    {
                        obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound;
                    }

                    DatabaseManager.Write(obj, RunId);
                }
            }
        }
Пример #9
0
        public override void Execute()
        {
            if (!CanRunOnPlatform())
            {
                return;
            }

            Start();
            _ = DatabaseManager.Transaction;


            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                foreach (IFirewallRule rule in FirewallManager.Instance.Rules.ToArray())
                {
                    var obj = new FirewallObject()
                    {
                        Action          = rule.Action,
                        ApplicationName = rule.ApplicationName,
                        Direction       = rule.Direction,
                        FriendlyName    = rule.FriendlyName,
                        IsEnable        = rule.IsEnable,
                        LocalAddresses  = rule.LocalAddresses.ToList().ConvertAll(address => address.ToString()),
                        LocalPorts      = rule.LocalPorts.ToList().ConvertAll(port => port.ToString()),
                        LocalPortType   = rule.LocalPortType,
                        Name            = rule.Name,
                        Profiles        = rule.Profiles,
                        Protocol        = rule.Protocol.ProtocolNumber.ToString(),
                        RemoteAddresses = rule.RemoteAddresses.ToList().ConvertAll(address => address.ToString()),
                        RemotePorts     = rule.RemotePorts.ToList().ConvertAll(port => port.ToString()),
                        Scope           = rule.Scope,
                        ServiceName     = rule.ServiceName
                    };
                    DatabaseManager.Write(obj, runId);
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // Example output: "Firewall is enabled. (State = 1)"
                var result  = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate");
                var enabled = result.Contains("1");
                var obj     = new FirewallObject()
                {
                    Action       = FirewallAction.Block,
                    Direction    = FirewallDirection.Inbound,
                    IsEnable     = enabled,
                    FriendlyName = "Firewall Enabled",
                    Name         = "Firewall Enabled",
                    Scope        = FirewallScope.All
                };
                DatabaseManager.Write(obj, runId);

                // Example output: "Stealth mode disabled"
                result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate");
                obj    = new FirewallObject()
                {
                    Action       = FirewallAction.Block,
                    Direction    = FirewallDirection.Inbound,
                    IsEnable     = result.Contains("enabled"),
                    FriendlyName = "Stealth Mode",
                    Name         = "Stealth Mode",
                    Scope        = FirewallScope.All
                };
                DatabaseManager.Write(obj, runId);

                /* Example Output:
                 * Automatically allow signed built-in software ENABLED
                 * Automatically allow downloaded signed software ENABLED */
                result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getallowsigned");
                obj    = new FirewallObject()
                {
                    Action       = FirewallAction.Allow,
                    Direction    = FirewallDirection.Inbound,
                    IsEnable     = result.Split('\n')[0].Contains("ENABLED"),
                    FriendlyName = "Allow signed built-in software",
                    Name         = "Allow signed built-in software",
                    Scope        = FirewallScope.All
                };
                DatabaseManager.Write(obj, runId);

                obj = new FirewallObject()
                {
                    Action       = FirewallAction.Allow,
                    Direction    = FirewallDirection.Inbound,
                    IsEnable     = result.Split('\n')[1].Contains("ENABLED"),
                    FriendlyName = "Allow downloaded signed software",
                    Name         = "Allow downloaded signed software",
                    Scope        = FirewallScope.All
                };
                DatabaseManager.Write(obj, runId);

                /* Example Output:
                 * ALF: total number of apps = 2
                 *
                 * 1 :  /Applications/AppName.app
                 * ( Allow incoming connections )
                 *
                 * 2 :  /Applications/AppName2.app
                 * ( Block incoming connections ) */
                result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--listapps");
                string appName          = "";
                Regex  startsWithNumber = new Regex("^[1-9]");
                var    lines            = new List <string>(result.Split('\n'));
                if (lines.Count() > 0)
                {
                    lines = lines.Skip(2).ToList();
                    foreach (var line in lines)
                    {
                        if (startsWithNumber.IsMatch(line))
                        {
                            appName = line.Substring(line.IndexOf('/'));
                        }
                        else if (line.Contains("incoming connections"))
                        {
                            obj = new FirewallObject()
                            {
                                Action       = (line.Contains("Allow"))?FirewallAction.Allow:FirewallAction.Block,
                                Direction    = FirewallDirection.Inbound,
                                FriendlyName = appName,
                                Name         = appName,
                                Scope        = FirewallScope.All
                            };
                            DatabaseManager.Write(obj, runId);
                        }
                    }
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var result = ExternalCommandRunner.RunExternalCommand("iptables", "-S");

                var lines = new List <string>(result.Split('\n'));

                Dictionary <string, FirewallAction> defaultPolicies = new Dictionary <string, FirewallAction>();

                foreach (var line in lines)
                {
                    if (line.StartsWith("-P"))
                    {
                        var chainName = line.Split(' ')[1];
                        defaultPolicies.Add(chainName, line.Contains("ACCEPT") ? FirewallAction.Allow : FirewallAction.Block);
                        var obj = new FirewallObject()
                        {
                            Action       = defaultPolicies[chainName],
                            FriendlyName = string.Format("Default {0} policy", chainName),
                            Name         = string.Format("Default {0} policy", chainName),
                            Scope        = FirewallScope.All
                        };
                        if (!chainName.Equals("FORWARD"))
                        {
                            obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound;
                        }

                        DatabaseManager.Write(obj, runId);
                    }
                    else if (line.StartsWith("-A"))
                    {
                        var splits    = line.Split(' ');
                        var chainName = splits[1];


                        var obj = new FirewallObject()
                        {
                            Action       = (splits[Array.IndexOf(splits, "-j") + 1] == "ACCEPT") ? FirewallAction.Allow : FirewallAction.Block,
                            FriendlyName = line,
                            Name         = line,
                            Scope        = FirewallScope.All,
                            Protocol     = splits[Array.IndexOf(splits, "-p") + 1]
                        };

                        if (Array.IndexOf(splits, "--dport") > 0)
                        {
                            obj.RemotePorts = new List <string>()
                            {
                                splits[Array.IndexOf(splits, "--dport") + 1]
                            };
                        }

                        if (Array.IndexOf(splits, "-d") > 0)
                        {
                            obj.RemoteAddresses = new List <string>()
                            {
                                splits[Array.IndexOf(splits, "-d") + 1]
                            };
                        }

                        if (Array.IndexOf(splits, "-s") > 0)
                        {
                            obj.LocalAddresses = new List <string>()
                            {
                                splits[Array.IndexOf(splits, "-s") + 1]
                            };
                        }

                        if (Array.IndexOf(splits, "--sport") > 0)
                        {
                            obj.LocalPorts = new List <string>()
                            {
                                splits[Array.IndexOf(splits, "--sport") + 1]
                            };
                        }

                        if (!chainName.Equals("FORWARD"))
                        {
                            obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound;
                        }

                        DatabaseManager.Write(obj, runId);
                    }
                }
            }

            DatabaseManager.Commit();
            Stop();
        }
 public ICommand <ApiResponseWithMessage> CreateSet(FirewallObject firewallObject) =>
 new Command <ApiResponseWithMessage>(
     apiUriFactory.Create(),
     apiPostKeyValuePairFactory.CreateSet(firewallObject));