Exemplo n.º 1
0
 private Task <bool> BlockOrAllowIPAddresses(string ruleNamePrefix, bool block, IEnumerable <string> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default)
 {
     try
     {
         string        prefix          = ruleNamePrefix.TrimEnd('_') + "_";
         int           i               = 0;
         List <string> ipAddressesList = new List <string>();
         foreach (string ipAddress in ipAddresses)
         {
             if (cancelToken.IsCancellationRequested)
             {
                 throw new OperationCanceledException(cancelToken);
             }
             ipAddressesList.Add(ipAddress);
             if (ipAddressesList.Count == MaxIpAddressesPerRule)
             {
                 if (block)
                 {
                     CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts);
                 }
                 else
                 {
                     CreateAllowRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts);
                 }
                 i += MaxIpAddressesPerRule;
                 ipAddressesList.Clear();
             }
         }
         if (cancelToken.IsCancellationRequested)
         {
             throw new OperationCanceledException(cancelToken);
         }
         if (ipAddressesList.Count != 0)
         {
             if (block)
             {
                 CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts);
             }
             else
             {
                 CreateAllowRule(ipAddressesList, 0, MaxIpAddressesPerRule, prefix + i.ToStringInvariant(), allowedPorts);
             }
             i += MaxIpAddressesPerRule;
         }
         DeleteRules(prefix, i);
         return(Task.FromResult(true));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult(false));
     }
 }
Exemplo n.º 2
0
 public virtual Task <bool> AllowIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default)
 {
     try
     {
         return(Task.FromResult(UpdateRule(AllowRuleName, "ACCEPT", ipAddresses, "ip", allowRuleMaxCount, null, cancelToken)));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult(false));
     }
 }
Exemplo n.º 3
0
        private async Task SetNetworkInfo()
        {
            if (string.IsNullOrWhiteSpace(FQDN))
            {
                string serverName = System.Environment.MachineName;
                try
                {
                    FQDN = (await DnsLookup.GetHostEntryAsync(serverName)).HostName;
                }
                catch
                {
                    FQDN = serverName;
                }
            }

            if (string.IsNullOrWhiteSpace(LocalIPAddressString))
            {
                try
                {
                    LocalIPAddressString = (await DnsLookup.GetLocalIPAddresses()).FirstOrDefault()?.ToString();
                    IPBanLog.Info("Local ip address: {0}", LocalIPAddressString);
                }
                catch
                {
                    // sometimes dns will fail, there is nothing that can be done, don't bother logging
                }
            }

            if (string.IsNullOrWhiteSpace(RemoteIPAddressString))
            {
                try
                {
                    IPAddress ipAddress = await ExternalIPAddressLookup.LookupExternalIPAddressAsync(RequestMaker, Config.ExternalIPAddressUrl);

                    RemoteIPAddressString = ipAddress.ToString();
                    IPBanLog.Info("Remote ip address: {0}", RemoteIPAddressString);
                }
                catch
                {
                    // sometimes ip check url will fail, there is nothing that can be done, don't bother logging
                }
            }

            // hit start url if first time, if not first time will be ignored
            await GetUrl(UrlType.Start);

            // send update
            await GetUrl(UrlType.Update);

            // request new config file
            await GetUrl(UrlType.Config);
        }
Exemplo n.º 4
0
        private HashSet <WatchedFile> UpdateWatchedFiles()
        {
            HashSet <WatchedFile> watchedFilesCopy = new HashSet <WatchedFile>();

            try
            {
                // read in existing files that match the mask in the directory being watched
                if (Directory.Exists(directoryToWatch))
                {
                    foreach (string file in Directory.EnumerateFiles(directoryToWatch, fileMask, SearchOption.TopDirectoryOnly))
                    {
                        watchedFilesCopy.Add(new WatchedFile(file, new FileInfo(file).Length));
                    }
                }
            }
            catch
            {
                // nothing to do here, something failed enumerating the directory files
            }

            lock (watchedFiles)
            {
                // remove files that no longer exist
                foreach (WatchedFile existing in watchedFiles.ToArray())
                {
                    if (!watchedFilesCopy.Contains(existing))
                    {
                        IPBanLog.Debug("Removing parsed log file {0}", existing.FileName);
                        watchedFiles.Remove(existing);
                    }
                }

                // add new files
                foreach (WatchedFile newFile in watchedFilesCopy)
                {
                    // add the file, will fail if it already exists
                    if (watchedFiles.Add(newFile))
                    {
                        IPBanLog.Debug("Adding parsed log file {0}", newFile.FileName);
                    }
                }

                // make a copy so we can enumerate outside a lock
                watchedFilesCopy.Clear();
                foreach (WatchedFile file in watchedFiles)
                {
                    watchedFilesCopy.Add(file);
                }
            }

            return(watchedFilesCopy);
        }
Exemplo n.º 5
0
 public virtual Task <bool> BlockIPAddressesDelta(string ruleNamePrefix, IEnumerable <IPBanFirewallIPAddressDelta> deltas, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default)
 {
     try
     {
         string ruleName = (string.IsNullOrWhiteSpace(ruleNamePrefix) ? BlockRuleName : RulePrefix + ruleNamePrefix);
         return(Task.FromResult(UpdateRuleDelta(ruleName, "DROP", deltas, hashTypeSingleIP, blockRuleMaxCount, false, allowedPorts, cancelToken)));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult(false));
     }
 }
Exemplo n.º 6
0
 /// <summary>
 /// Get a value from configuration manager app settings
 /// </summary>
 /// <typeparam name="T">Type of value to get</typeparam>
 /// <param name="key">Key</param>
 /// <param name="defaultValue">Default value if null or not found</param>
 /// <returns>Value</returns>
 public T GetConfig <T>(string key, T defaultValue = default)
 {
     try
     {
         var converter = TypeDescriptor.GetConverter(typeof(T));
         return((T)converter.ConvertFromInvariantString(appSettings[key]));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex, "Error deserializing appSettings key {0}", key);
         return(defaultValue);
     }
 }
Exemplo n.º 7
0
 public virtual Task <bool> AllowIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default)
 {
     try
     {
         ruleNamePrefix.ThrowIfNullOrEmpty();
         return(Task.FromResult(UpdateRule(RulePrefix + ruleNamePrefix, "ACCEPT", ipAddresses.Select(r => r.ToCidrString()), hashTypeCidrMask, blockRuleMaxCount, allowedPorts, cancelToken)));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult(false));
     }
 }
Exemplo n.º 8
0
 public Task <bool> BlockIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default)
 {
     try
     {
         bannedIPAddresses = UpdateRule(blockRuleName, "DROP", ipAddresses, bannedIPAddresses, "ip", blockRuleMaxCount, false, null, cancelToken, out bool result);
         return(Task.FromResult(result));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult(false));
     }
 }
Exemplo n.º 9
0
 public Task <bool> AllowIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default)
 {
     try
     {
         allowedIPAddresses = UpdateRule(allowRuleName, "ACCEPT", ipAddresses, allowedIPAddresses, "ip", allowRuleMaxCount, false, null, cancelToken, out bool result);
         return(Task.FromResult <bool>(result));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult <bool>(false));
     }
 }
Exemplo n.º 10
0
 public virtual Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <string> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default)
 {
     try
     {
         string ruleName = (string.IsNullOrWhiteSpace(ruleNamePrefix) ? BlockRuleName : RulePrefix + ruleNamePrefix);
         return(Task.FromResult(UpdateRule(ruleName, "DROP", ipAddresses, "ip", blockRuleMaxCount, allowedPorts, cancelToken)));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult(false));
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Easy way to execute processes. If the process has not finished after timeoutMilliseconds, it is forced killed.
        /// </summary>
        /// <param name="timeoutMilliseconds">Timeout in milliseconds</param>
        /// <param name="program">Program to run</param>
        /// <param name="args">Arguments</param>
        /// <param name="allowedExitCodes">Allowed exit codes, if null or empty it is not checked, otherwise a mismatch will throw an exception.</param>
        /// <returns>Output</returns>
        /// <exception cref="ApplicationException">Exit code did not match allowed exit codes</exception>
        public static string StartProcessAndWait(int timeoutMilliseconds, string program, string args, params int[] allowedExitCodes)
        {
            IPBanLog.Info($"Executing process {program} {args}...");

            var process = new Process
            {
                StartInfo = new ProcessStartInfo(program, args)
                {
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    Verb = processVerb
                }
            };
            StringBuilder output = new StringBuilder();

            process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                lock (output)
                {
                    output.Append("[OUT]: ");
                    output.AppendLine(e.Data);
                }
            };
            process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                lock (output)
                {
                    output.Append("[ERR]: ");
                    output.AppendLine(e.Data);
                }
            };
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            if (!process.WaitForExit(timeoutMilliseconds))
            {
                lock (output)
                {
                    output.Append("[ERR]: Terminating process due to 60 second timeout");
                }
                process.Kill();
            }
            if (allowedExitCodes.Length != 0 && Array.IndexOf(allowedExitCodes, process.ExitCode) < 0)
            {
                throw new ApplicationException($"Program {program} {args}: failed with exit code {process.ExitCode}, output: {output}");
            }
            return(output.ToString());
        }
Exemplo n.º 12
0
        public Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ranges, IEnumerable <PortRange> allowedPorts, CancellationToken cancelToken = default)
        {
            try
            {
                string prefix = (string.IsNullOrWhiteSpace(ruleNamePrefix) ? RangeRulePrefix : RulePrefix + ruleNamePrefix).TrimEnd('_') + "_";

                // recreate rules
                int           counter = 0;
                int           index   = 0;
                StringBuilder ipList  = new StringBuilder();
                foreach (IPAddressRange range in ranges)
                {
                    if (cancelToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException(cancelToken);
                    }
                    ipList.Append(range.ToCidrString());
                    ipList.Append(',');
                    if (++counter == MaxIpAddressesPerRule)
                    {
                        ipList.Length--; // remove ending comma
                        GetOrCreateRule(prefix + index.ToString(CultureInfo.InvariantCulture), ipList.ToString(), NET_FW_ACTION_.NET_FW_ACTION_BLOCK, allowedPorts);
                        counter = 0;
                        index  += MaxIpAddressesPerRule;
                        ipList.Clear();
                    }
                }
                if (cancelToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException(cancelToken);
                }

                // create rule for any leftover ip addresses
                if (ipList.Length > 1)
                {
                    ipList.Length--; // remove ending comma
                    GetOrCreateRule(prefix + index.ToString(CultureInfo.InvariantCulture), ipList.ToString(), NET_FW_ACTION_.NET_FW_ACTION_BLOCK, allowedPorts);
                    index += MaxIpAddressesPerRule;
                }

                // delete any leftover rules
                DeleteRules(prefix, index);
                return(Task.FromResult(true));
            }
            catch (Exception ex)
            {
                IPBanLog.Error(ex);
                return(Task.FromResult(false));
            }
        }
Exemplo n.º 13
0
        private async Task SetNetworkInfo()
        {
            if (string.IsNullOrWhiteSpace(FQDN))
            {
                string serverName = System.Environment.MachineName;
                try
                {
                    FQDN = System.Net.Dns.GetHostEntry(serverName).HostName;
                }
                catch
                {
                    FQDN = serverName;
                }
            }

            if (string.IsNullOrWhiteSpace(LocalIPAddressString))
            {
                try
                {
                    LocalIPAddressString = DnsLookup.GetLocalIPAddress().Sync()?.ToString();
                    IPBanLog.Info("Local ip address: {0}", LocalIPAddressString);
                }
                catch
                {
                }
            }

            if (string.IsNullOrWhiteSpace(RemoteIPAddressString))
            {
                try
                {
                    IPAddress ipAddress = await ExternalIPAddressLookup.LookupExternalIPAddressAsync(RequestMaker, Config.ExternalIPAddressUrl);

                    RemoteIPAddressString = ipAddress.ToString();
                    IPBanLog.Info("Remote ip address: {0}", RemoteIPAddressString);
                }
                catch
                {
                }
            }

            // hit start url if first time, if not first time will be ignored
            await GetUrl(UrlType.Start);

            // send update
            await GetUrl(UrlType.Update);

            // request new config file
            await GetUrl(UrlType.Config);
        }
Exemplo n.º 14
0
 /// <summary>
 /// Set a field / variable from configuration manager app settings. If null or not found, nothing is changed.
 /// </summary>
 /// <typeparam name="T">Type of value to set</typeparam>
 /// <param name="key">Key</param>
 /// <param name="value">Value</param>
 public void GetConfig <T>(string key, ref T value)
 {
     try
     {
         var converter = TypeDescriptor.GetConverter(typeof(T));
         if (appSettings.ContainsKey(key))
         {
             value = (T)converter.ConvertFromInvariantString(appSettings[key]);
         }
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex, "Error deserializing appSettings key {0}", key);
     }
 }
Exemplo n.º 15
0
        /// <summary>
        /// Process a line, checking for ip addresses
        /// </summary>
        /// <param name="line">Line to process</param>
        /// <returns>True</returns>
        protected override bool OnProcessLine(string line)
        {
            IPBanLog.Debug("Parsing log file line {0}...", line);
            bool result = ParseRegex(regexFailure, line, false);

            if (!result)
            {
                result = ParseRegex(regexSuccess, line, true);
                if (!result)
                {
                    IPBanLog.Debug("No match for line {0}", line);
                }
            }
            return(true);
        }
 /// <summary>
 /// Update - if the text file path exists, all ip addresses from each line will be unbanned
 /// </summary>
 public void Update()
 {
     try
     {
         if (File.Exists(textFilePath))
         {
             UnbanIPAddresses(File.ReadLines(textFilePath));
             File.Delete(textFilePath);
         }
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
     }
 }
Exemplo n.º 17
0
 public static async Task MainService(string[] args, Func <string[], Task> start, Action stop, bool requireAdministrator = true)
 {
     try
     {
         using (IPBanServiceRunner runner = new IPBanServiceRunner(args, start, stop))
         {
             await runner.RunAsync(requireAdministrator);
         }
     }
     catch (Exception ex)
     {
         IPBanExtensionMethods.FileWriteAllTextWithRetry(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "startup_fail.txt"), ex.ToString());
         IPBanLog.Fatal("Fatal error starting service", ex);
     }
 }
Exemplo n.º 18
0
 protected override void OnStart(string[] args)
 {
     base.OnStart(args);
     Task.Run(async() =>
     {
         try
         {
             await runner.start.Invoke(args);
         }
         catch (Exception ex)
         {
             IPBanLog.Error(ex);
         }
     });
 }
Exemplo n.º 19
0
        public void UnblockIPAddresses(IEnumerable <string> ipAddresses)
        {
            try
            {
                lock (policy)
                {
                    for (int i = 0; ; i += MaxIpAddressesPerRule)
                    {
                        string ruleName = RulePrefix + i.ToString(CultureInfo.InvariantCulture);
                        try
                        {
                            INetFwRule rule = policy.Rules.Item(ruleName);
                            if (rule == null)
                            {
                                // no more rules to check
                                break;
                            }
                            string remoteIPs = rule.RemoteAddresses;
                            foreach (string ipAddress in ipAddresses)
                            {
                                remoteIPs = Regex.Replace(remoteIPs, ipAddress.Replace(".", "\\.") + "\\/[^,]+,?", ",", RegexOptions.IgnoreCase);
                                remoteIPs = remoteIPs.Replace(",,", ",");
                                remoteIPs = remoteIPs.Trim().Trim(',', '/', ':', '.', ';', '*').Trim();
                            }

                            // ensure we don't have a block rule with no ip addresses, this will block the entire world (WTF Microsoft)...
                            if (string.IsNullOrWhiteSpace(remoteIPs))
                            {
                                policy.Rules.Remove(rule.Name);
                            }
                            else
                            {
                                rule.RemoteAddresses = remoteIPs;
                            }
                        }
                        catch
                        {
                            // no more rules to check
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                IPBanLog.Error(ex);
            }
        }
Exemplo n.º 20
0
 public static Task <int> MainService(string[] args, Func <string[], Task> start, Action stop, Func <int, bool> stopped, bool requireAdministrator = true)
 {
     try
     {
         using (IPBanServiceRunner runner = new IPBanServiceRunner(args, start, stop, stopped))
         {
             return(runner.RunAsync(requireAdministrator));
         }
     }
     catch (Exception ex)
     {
         System.IO.File.WriteAllText(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "startup_fail.txt"), ex.ToString());
         IPBanLog.Fatal("Fatal error starting service", ex);
         return(Task.FromResult(-1));
     }
 }
Exemplo n.º 21
0
 public Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <string> ipAddresses, CancellationToken cancelToken = default)
 {
     try
     {
         if (string.IsNullOrWhiteSpace(ruleNamePrefix))
         {
             ruleNamePrefix = RulePrefix;
         }
         else
         {
             ruleNamePrefix = RulePrefix + ruleNamePrefix;
         }
         int           i = 0;
         List <string> ipAddressesList = new List <string>();
         foreach (string ipAddress in ipAddresses)
         {
             if (cancelToken.IsCancellationRequested)
             {
                 throw new OperationCanceledException(cancelToken);
             }
             ipAddressesList.Add(ipAddress);
             if (ipAddressesList.Count == MaxIpAddressesPerRule)
             {
                 CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, ruleNamePrefix + i.ToStringInvariant());
                 i += MaxIpAddressesPerRule;
                 ipAddressesList.Clear();
             }
         }
         if (cancelToken.IsCancellationRequested)
         {
             throw new OperationCanceledException(cancelToken);
         }
         if (ipAddressesList.Count != 0)
         {
             CreateBlockRule(ipAddressesList, 0, MaxIpAddressesPerRule, ruleNamePrefix + i.ToStringInvariant());
             i += MaxIpAddressesPerRule;
         }
         DeleteRules(ruleNamePrefix, i);
         return(Task.FromResult(true));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult(false));
     }
 }
Exemplo n.º 22
0
        private void Initialize()
        {
            IPBanLog.Info("Initializing IPBan database at {0}", connString);
            SQLitePCL.Batteries.Init();
            ExecuteNonQuery("PRAGMA auto_vacuum = INCREMENTAL;");
            ExecuteNonQuery("PRAGMA journal_mode = WAL;");
            ExecuteNonQuery("CREATE TABLE IF NOT EXISTS IPAddresses (IPAddress VARBINARY(16) NOT NULL, IPAddressText VARCHAR(64) NOT NULL, LastFailedLogin BIGINT NOT NULL, FailedLoginCount BIGINT NOT NULL, BanDate BIGINT NULL, PRIMARY KEY (IPAddress))");
            ExecuteNonQueryIgnoreExceptions("ALTER TABLE IPAddresses ADD COLUMN State INT NOT NULL DEFAULT 0");
            ExecuteNonQueryIgnoreExceptions("ALTER TABLE IPAddresses ADD COLUMN BanEndDate BIGINT NULL");
            ExecuteNonQuery("CREATE INDEX IF NOT EXISTS IPAddresses_LastFailedLoginDate ON IPAddresses (LastFailedLogin)");
            ExecuteNonQuery("CREATE INDEX IF NOT EXISTS IPAddresses_BanDate ON IPAddresses (BanDate)");
            ExecuteNonQuery("CREATE INDEX IF NOT EXISTS IPAddresses_BanEndDate ON IPAddresses (BanEndDate)");
            ExecuteNonQuery("CREATE INDEX IF NOT EXISTS IPAddresses_State ON IPAddresses (State)");

            // set to failed login state if no ban date
            ExecuteNonQuery("UPDATE IPAddresses SET State = 3 WHERE State IN (0, 1) AND BanDate IS NULL");
        }
Exemplo n.º 23
0
 private bool ParseRegex(Regex regex, string line, bool notifyOnly)
 {
     if (regex != null)
     {
         IPAddressLogEvent info = IPBanService.GetIPAddressInfoFromRegex(dns, regex, line);
         if (info.FoundMatch)
         {
             info.Type   = (notifyOnly ? IPAddressEventType.SuccessfulLogin : IPAddressEventType.FailedLogin);
             info.Source = info.Source ?? Source;
             IPBanLog.Debug("Log file found match, ip: {0}, user: {1}, source: {2}, count: {3}, type: {4}",
                            info.IPAddress, info.UserName, info.Source, info.Count, info.Type);
             loginHandler.AddIPAddressLogEvents(new IPAddressLogEvent[] { info });
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 24
0
        /// <summary>
        /// Get a value from configuration manager app settings
        /// </summary>
        /// <typeparam name="T">Type of value to get</typeparam>
        /// <param name="key">Key</param>
        /// <param name="value">Value to set</param>
        /// <param name="minValue">Min value</param>
        /// <param name="maxValue">Max value</param>
        /// <param name="clampSmallTimeSpan">Whether to clamp small timespan to max value</param>
        /// <returns>Value</returns>
        public void GetConfig <T>(string key, ref T value, T?minValue = null, T?maxValue = null, bool clampSmallTimeSpan = true) where T : struct, IComparable <T>
        {
            try
            {
                var converter = TypeDescriptor.GetConverter(typeof(T));
                value = (T)converter.ConvertFromInvariantString(appSettings[key]);
            }
            catch (Exception ex)
            {
                IPBanLog.Error(ex, "Error deserializing appSettings key {0}", key);
            }

            if (minValue != null && maxValue != null)
            {
                value = value.Clamp(minValue.Value, maxValue.Value, clampSmallTimeSpan);
            }
        }
 /// <summary>
 /// Update - if the text file path exists, all ip addresses from each line will be unbanned
 /// </summary>
 public async Task Update()
 {
     try
     {
         if (File.Exists(textFilePath))
         {
             string[] lines = (await File.ReadAllLinesAsync(textFilePath)).Where(l => IPAddress.TryParse(l, out _)).ToArray();
             IPBanLog.Warn("Queueing {0} ip addresses to unban from {1} file", lines.Length, textFilePath);
             UnblockIPAddresses(lines);
             File.Delete(textFilePath);
         }
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
     }
 }
Exemplo n.º 26
0
        public virtual Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ranges, IEnumerable <PortRange> allowedPorts, CancellationToken cancelToken = default)
        {
            if (string.IsNullOrWhiteSpace(ruleNamePrefix))
            {
                return(Task.FromResult(false));
            }

            try
            {
                string ruleName = RulePrefix + RuleSuffix + ruleNamePrefix;
                return(Task.FromResult(UpdateRule(ruleName, "DROP", ranges.Select(r => r.ToCidrString()), "net", blockRuleRangesMaxCount, allowedPorts, cancelToken)));
            }
            catch (Exception ex)
            {
                IPBanLog.Error(ex);
                return(Task.FromResult(false));
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Process event viewer XML
        /// </summary>
        /// <param name="xml">XML</param>
        public void ProcessEventViewerXml(string xml)
        {
            IPBanLog.Debug("Processing event viewer xml: {0}", xml);

            XmlDocument       doc  = ParseXml(xml);
            IPAddressLogEvent info = ExtractEventViewerXml(doc);

            if (info != null && info.FoundMatch && (info.Type == IPAddressEventType.FailedLogin || info.Type == IPAddressEventType.SuccessfulLogin))
            {
                if (!FindSourceAndUserNameForInfo(info, doc))
                {
                    // bad ip address
                    return;
                }
                service.AddIPAddressLogEvents(new IPAddressLogEvent[] { info });
                IPBanLog.Debug("Event viewer found: {0}, {1}, {2}, {4}", info.IPAddress, info.Source, info.UserName, info.Type);
            }
        }
Exemplo n.º 28
0
 public Task <bool> AllowIPAddresses(IEnumerable <string> ipAddresses, CancellationToken cancelToken = default)
 {
     try
     {
         List <string> ipAddressesList = new List <string>();
         int           i = 0;
         foreach (string ipAddress in ipAddresses)
         {
             if (cancelToken.IsCancellationRequested)
             {
                 throw new OperationCanceledException();
             }
             ipAddressesList.Add(ipAddress);
             if (ipAddressesList.Count == MaxIpAddressesPerRule)
             {
                 string remoteIP = CreateRuleStringForIPAddresses(ipAddressesList, i, MaxIpAddressesPerRule);
                 GetOrCreateRule(AllowRulePrefix + i.ToString(CultureInfo.InvariantCulture), remoteIP, NET_FW_ACTION_.NET_FW_ACTION_ALLOW);
                 i += MaxIpAddressesPerRule;
                 ipAddressesList.Clear();
             }
         }
         if (cancelToken.IsCancellationRequested)
         {
             throw new OperationCanceledException();
         }
         if (ipAddressesList.Count != 0)
         {
             string remoteIP = CreateRuleStringForIPAddresses(ipAddressesList, i, MaxIpAddressesPerRule);
             GetOrCreateRule(AllowRulePrefix + i.ToString(CultureInfo.InvariantCulture), remoteIP, NET_FW_ACTION_.NET_FW_ACTION_ALLOW);
             i += MaxIpAddressesPerRule;
         }
         if (cancelToken.IsCancellationRequested)
         {
             throw new OperationCanceledException();
         }
         DeleteRules(AllowRulePrefix, i);
         return(Task.FromResult <bool>(true));
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
         return(Task.FromResult <bool>(false));
     }
 }
Exemplo n.º 29
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);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Process event viewer XML
        /// </summary>
        /// <param name="xml">XML</param>
        public void ProcessEventViewerXml(string xml)
        {
            IPBanLog.Debug("Processing event viewer xml: {0}", xml);

            XmlDocument       doc  = ParseXml(xml);
            IPAddressLogEvent info = ExtractEventViewerXml(doc);

            if (info != null && info.FoundMatch)
            {
                if (info.Type == IPAddressEventType.FailedLogin && !AddFailedLoginForEventViewerXml(info, doc))
                {
                    // if fail to add the failed login (bad ip, etc.) exit out
                    return;
                }
                System.Diagnostics.Debug.Assert(info.Type == IPAddressEventType.FailedLogin || info.Type == IPAddressEventType.SuccessfulLogin);
                service.AddIPAddressLogEvents(new IPAddressLogEvent[] { info });
                IPBanLog.Debug("Event viewer found: {0}, {1}, {2}, {4}", info.IPAddress, info.Source, info.UserName, info.Type);
            }
        }