示例#1
0
 private static void CreateService()
 {
     if (service != null)
     {
         service.Dispose();
     }
     service = IPBanService.CreateService <IPBanService>();
     service.Start();
 }
示例#2
0
        /// <summary>
        /// Create a test IPBanService
        /// </summary>
        /// <param name="directory">Root directory</param>
        /// <param name="configFileName">Config file name</param>
        /// <param name="configFileModifier">Change config file (param are file text, returns new file text)</param>
        /// <returns>Service</returns>
        public static T CreateAndStartIPBanTestService <T>(string directory = null, string configFileName = null,
                                                           Func <string, string> configFileModifier = null) where T : IPBanService
        {
            DefaultHttpRequestMaker.DisableLiveRequests = true;

            // cleanup any db, set or tbl files
            foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set")
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sqlite*"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*journal*")))
            {
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        File.Delete(file);
                        break;
                    }
                    catch
                    {
                        Thread.Sleep(1000);
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = Path.GetDirectoryName(IPBanAssembly.Location);
            }
            if (string.IsNullOrWhiteSpace(configFileName))
            {
                configFileName = IPBanService.ConfigFileName;
            }
            string configFilePath = Path.Combine(directory, configFileName);
            string configFileText = File.ReadAllText(configFilePath);

            configFilePath += ".tmp";
            if (configFileModifier != null)
            {
                configFileText = configFileModifier(configFileText);
            }
            File.WriteAllText(configFilePath, configFileText);
            T service = IPBanService.CreateService <T>() as T;

            service.ExternalIPAddressLookup = LocalMachineExternalIPAddressLookupTest.Instance;
            service.ConfigFilePath          = configFilePath;
            service.MultiThreaded           = false;
            service.ManualCycle             = true;
            service.BannedIPAddressHandler  = service;
            service.Version = "1.1.1.1";
            service.StartAsync().Sync();
            service.DB.Truncate(true);
            service.Firewall.Truncate();
            return(service);
        }
示例#3
0
 /// <summary>
 /// Dispose of an IPBanService created with CreateAndStartIPBanTestService
 /// </summary>
 /// <param name="service">Service to dispose</param>
 public static void DisposeIPBanTestService(IPBanService service)
 {
     if (service != null)
     {
         service.Firewall.Truncate();
         service.RunCycle().Sync();
         service.Dispose();
         IPBanService.UtcNow = default;
     }
 }
示例#4
0
        public static void MacMain(string[] args)
        {
            IPBanService service = IPBanService.CreateService <IPBanService>();

            service.Start();
            IPBanLog.Warn("IPBan Mac Service Running, Press Ctrl-C to quit.");
            ManualResetEvent wait = new ManualResetEvent(false);

            wait.WaitOne();
        }
示例#5
0
        public static Task <int> MainService <T>(string[] args, out T service) where T : IPBanService
        {
            T _service = IPBanService.CreateService <T>();

            service = _service;
            return(MainService(args, (_args) =>
            {
                _service.Start();
            }, () =>
            {
                _service.Stop();
            }, (_timeout) =>
            {
                return _service.Wait(_timeout);
            }));
        }
示例#6
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);
 }
示例#7
0
        public static Task <int> MainService <T>(string[] args, out T service) where T : IPBanService
        {
            T _service = IPBanService.CreateService <T>();

            service = _service;
            return(MainService(args, (_args) =>
            {
                // kick off start in background thread, make sure service starts up in a timely manner
                return Task.Run(() => _service.Start());
            }, () =>
            {
                _service.Stop();
            }, (_timeout) =>
            {
                return _service.Wait(_timeout);
            }));
        }
示例#8
0
        public static async Task MainService <T>(string[] args, Action started = null) where T : IPBanService
        {
            T _service = IPBanService.CreateService <T>();

            await MainService(args, async (_args) =>
            {
                // kick off start in background thread, make sure service starts up in a timely manner
                await _service.StartAsync();
                started?.Invoke();

                // wait for service to end
                await _service.WaitAsync(Timeout.Infinite);
            }, () =>
            {
                // stop the service, will cause any WaitAsync to exit
                _service.Stop();
            });
        }
示例#9
0
        /// <summary>
        /// IPBan main method
        /// </summary>
        /// <param name="args">Args</param>
        /// <returns>Task</returns>
        public static async Task Main(string[] args)
        {
            if (args.Length != 0 && (args[0].Equals("info", StringComparison.OrdinalIgnoreCase) ||
                                     args[0].Equals("-info", StringComparison.OrdinalIgnoreCase)))
            {
                Logger.Warn("System info: {0}", OSUtility.OSString());
                return;
            }

            IPBanService service = null;
            await IPBanServiceRunner.MainService(args, (CancellationToken cancelToken) =>
            {
                service = IPBanService.CreateService <IPBanService>();
                return(service.RunAsync(cancelToken));
            }, (CancellationToken cancelToken) =>
            {
                service?.Dispose();
                return(Task.CompletedTask);
            });
        }
示例#10
0
        /// <summary>
        /// IPBan main method
        /// </summary>
        /// <param name="args">Args</param>
        /// <returns>Task</returns>
        public static async Task Main(string[] args)
        {
            if (ProcessCommandLine(args))
            {
                return;
            }

            IPBanService service = null;
            await IPBanServiceRunner.MainService(args, (CancellationToken cancelToken) =>
            {
                service = IPBanService.CreateService <IPBanService>();
                Logger.Warn("IPBan is free software created and refined over many years.");
                Logger.Warn("Please consider upgrading to the pro version for more advanced functions, shared ban lists and much more.");
                Logger.Warn("Learn more at https://ipban.com");
                return(service.RunAsync(cancelToken));
            }, (CancellationToken cancelToken) =>
            {
                service?.Dispose();
                return(Task.CompletedTask);
            });
        }
示例#11
0
        /// <summary>
        /// IPBan main method
        /// </summary>
        /// <param name="args">Args</param>
        /// <returns>Task</returns>
        public static async Task Main(string[] args)
        {
            if (args.Length != 0 && (args[0].Equals("info", StringComparison.OrdinalIgnoreCase) ||
                                     args[0].Equals("-info", StringComparison.OrdinalIgnoreCase)))
            {
                Logger.Warn("System info: {0}", OSUtility.OSString());
                return;
            }

            IPBanService service = null;
            await IPBanServiceRunner.MainService(args, (CancellationToken cancelToken) =>
            {
                service = IPBanService.CreateService <IPBanService>();
                Logger.Warn("IPBan is free software created and refined over many years.");
                Logger.Warn("Please consider upgrading to the pro version for more advanced functions, shared ban lists and much more.");
                Logger.Warn("Learn more at https://ipban.com");
                return(service.RunAsync(cancelToken));
            }, (CancellationToken cancelToken) =>
            {
                service?.Dispose();
                return(Task.CompletedTask);
            });
        }
示例#12
0
        private IPAddressLogEvent ExtractEventViewerXml(XmlDocument doc)
        {
            XmlNode keywordsNode = doc.SelectSingleNode("//Keywords");
            string  keywordsText = keywordsNode.InnerText;

            if (keywordsText.StartsWith("0x"))
            {
                keywordsText = keywordsText.Substring(2);
            }
            ulong             keywordsULONG = ulong.Parse(keywordsText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
            IPAddressLogEvent info          = null;
            bool foundNotifyOnly            = false;

            if (keywordsNode != null)
            {
                // we must match on keywords
                foreach (EventViewerExpressionGroup group in service.Config.WindowsEventViewerGetGroupsMatchingKeywords(keywordsULONG))
                {
                    foreach (EventViewerExpression expression in group.Expressions)
                    {
                        // find all the nodes, try and get an ip from any of them, all must match
                        XmlNodeList nodes = doc.SelectNodes(expression.XPath);

                        if (nodes.Count == 0)
                        {
                            IPBanLog.Debug("No nodes found for xpath {0}", expression.XPath);
                            info = null;
                            break;
                        }

                        // if there is a regex, it must match
                        if (string.IsNullOrWhiteSpace(expression.Regex))
                        {
                            // count as a match, do not modify the ip address if it was already set
                            IPBanLog.Debug("No regex, so counting as a match");
                        }
                        else
                        {
                            info = null;

                            // try and find an ip from any of the nodes
                            foreach (XmlNode node in nodes)
                            {
                                // if we get a match, stop checking nodes
                                info = IPBanService.GetIPAddressInfoFromRegex(service.DnsLookup, expression.RegexObject, node.InnerText);
                                if (info.FoundMatch)
                                {
                                    if (group.NotifyOnly)
                                    {
                                        foundNotifyOnly = true;
                                    }
                                    else if (foundNotifyOnly)
                                    {
                                        throw new InvalidDataException("Conflicting expressions in event viewer, both failed and success logins matched keywords " + group.Keywords);
                                    }
                                    break;
                                }
                            }

                            if (info != null && !info.FoundMatch)
                            {
                                // match fail, null out ip, we have to match ALL the nodes or we get null ip and do not ban
                                IPBanLog.Debug("Regex {0} did not match any nodes with xpath {1}", expression.Regex, expression.XPath);
                                info            = null;
                                foundNotifyOnly = false;
                                break;
                            }
                        }
                    }

                    if (info != null && info.FoundMatch && info.IPAddress != null)
                    {
                        info.Source = info.Source ?? group.Source;
                        break;
                    }
                    info = null; // set null for next attempt
                }
            }

            if (info != null)
            {
                info.Type = (foundNotifyOnly ? IPAddressEventType.SuccessfulLogin : IPAddressEventType.FailedLogin);
            }
            return(info);
        }
示例#13
0
 protected override void OnStop()
 {
     service.Stop();
     service = null;
     base.OnStop();
 }