コード例 #1
0
 /// <summary>
 /// Update - if the text file path exists, all ip addresses from each line will be banned
 /// </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 ban from {1} file", lines.Length, textFilePath);
             List <IPAddressLogEvent> bans = new List <IPAddressLogEvent>();
             foreach (string[] pieces in lines.Select(l => l.Split(',')))
             {
                 if (pieces.Length < 1)
                 {
                     continue;
                 }
                 string ipAddress = pieces[0];
                 string source    = (pieces.Length < 2 ? "Block" : pieces[1]);
                 bans.Add(new IPAddressLogEvent(ipAddress, string.Empty, source, 1, IPAddressEventType.Blocked));
             }
             service.AddIPAddressLogEvents(bans);
             IPBanExtensionMethods.FileDeleteWithRetry(textFilePath);
         }
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
     }
 }
コード例 #2
0
        /// <summary>
        /// Stop the service, dispose of all resources
        /// </summary>
        public void Dispose()
        {
            if (!IsRunning)
            {
                return;
            }

            IsRunning = false;
            try
            {
                firewallQueueCancel.Cancel();
                GetUrl(UrlType.Stop).Sync();
                cycleTimer?.Dispose();
                IPBanDelegate?.Dispose();
                IPBanDelegate = null;
                lock (updaters)
                {
                    foreach (IUpdater updater in updaters.ToArray())
                    {
                        updater.Dispose();
                    }
                    updaters.Clear();
                }
                foreach (IPBanLogFileScanner file in logFilesToParse)
                {
                    file.Dispose();
                }
                ipDB?.Dispose();
                IPBanLog.Warn("Stopped IPBan service");
            }
            finally
            {
                stopEvent.Release();
            }
        }
コード例 #3
0
        private void SetupEventLogWatcher()
        {
            try
            {
                List <string> ignored     = new List <string>();
                string        queryString = GetEventLogQueryString(ignored);
                if (queryString != null && queryString != previousQueryString)
                {
                    IPBanLog.Warn("Event viewer query string: {0}", queryString);
                    foreach (string path in ignored)
                    {
                        IPBanLog.Warn("Ignoring event viewer path {0}", path);
                    }

                    watcher?.Dispose();
                    query   = new EventLogQuery(null, PathType.LogName, queryString);
                    watcher = new EventLogWatcher(query);
                    watcher.EventRecordWritten += EventRecordWritten;
                    watcher.Enabled             = true;
                    previousQueryString         = queryString;
                }
            }
            catch (Exception ex)
            {
                IPBanLog.Error("Failed to create event viewer watcher", ex);
            }
        }
コード例 #4
0
 /// <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);
             IPBanExtensionMethods.FileDeleteWithRetry(textFilePath);
         }
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
     }
 }
コード例 #5
0
        /// <summary>
        /// Initialize and start the service
        /// </summary>
        public async Task StartAsync()
        {
            if (IsRunning)
            {
                return;
            }

            try
            {
                IsRunning = true;
                ipDB      = new IPBanDB(DatabasePath ?? "ipban.sqlite");
                AddWindowsEventViewer();
                AddUpdater(new IPBanUnblockIPAddressesUpdater(this, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "unban.txt")));
                AddUpdater(new IPBanBlockIPAddressesUpdater(this, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ban.txt")));
                AssemblyVersion = IPBanService.IPBanAssembly.GetName().Version.ToString();
                await ReadAppSettings();

                UpdateBannedIPAddressesOnStart();
                IPBanDelegate?.Start(this);
                if (!ManualCycle)
                {
                    if (RunFirstCycleRightAway)
                    {
                        await RunCycle(); // run one cycle right away
                    }
                    cycleTimer          = new System.Timers.Timer(Config.CycleTime.TotalMilliseconds);
                    cycleTimer.Elapsed += async(sender, e) => await CycleTimerElapsed(sender, e);

                    cycleTimer.Start();
                }
                IPBanLog.Warn("IPBan {0} service started and initialized. Operating System: {1}", IPBanOS.Name, IPBanOS.OSString());
                IPBanLog.WriteLogLevels();
            }
            catch (Exception ex)
            {
                IPBanLog.Error("Critical error in IPBanService.Start", ex);
            }
        }
コード例 #6
0
 public IPBanWindowsServiceRunner(IPBanServiceRunner runner, string[] args)
 {
     runner.ThrowIfNull();
     try
     {
         IPBanLog.Warn("Running as a Windows service");
         this.runner = runner;
         CanShutdown = false;
         CanStop     = CanHandleSessionChangeEvent = CanHandlePowerEvent = true;
         var acceptedCommandsField = typeof(ServiceBase).GetField("acceptedCommands", BindingFlags.Instance | BindingFlags.NonPublic);
         if (acceptedCommandsField != null)
         {
             int acceptedCommands = (int)acceptedCommandsField.GetValue(this);
             acceptedCommands |= 0x00000100; // SERVICE_ACCEPT_PRESHUTDOWN;
             acceptedCommandsField.SetValue(this, acceptedCommands);
         }
         Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
     }
 }
コード例 #7
0
        /// <summary>
        /// Run the service
        /// </summary>
        /// <param name="requireAdministrator">True to require administrator, false otherwise</param>
        /// <returns>Exit code</returns>
        public async Task RunAsync(bool requireAdministrator = true)
        {
            if (requireAdministrator)
            {
                IPBanExtensionMethods.RequireAdministrator();
            }

            if (args.Length != 0 && (args[0].Equals("info", StringComparison.OrdinalIgnoreCase) || args[0].Equals("-info", StringComparison.OrdinalIgnoreCase)))
            {
                IPBanLog.Warn("System info: {0}", IPBanOS.OSString());
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                await RunWindowsService(args);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                await RunLinuxService(args);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
        }
コード例 #8
0
ファイル: IPBanConfig.cs プロジェクト: krugertech/IPBan
        private void ParseFirewallBlockRules()
        {
            string firewallBlockRuleString = null;

            GetConfig <string>("FirewallRules", ref firewallBlockRuleString);
            firewallBlockRuleString = (firewallBlockRuleString ?? string.Empty).Trim();
            if (firewallBlockRuleString.Length == 0)
            {
                return;
            }
            IEnumerable <string> firewallBlockRuleList = firewallBlockRuleString.Trim().Split('\n').Select(s => s.Trim()).Where(s => s.Length != 0);

            foreach (string firewallBlockRule in firewallBlockRuleList)
            {
                string[] pieces = firewallBlockRule.Split(';');
                if (pieces.Length == 5)
                {
                    IPBanFirewallRule firewallBlockRuleObj = new IPBanFirewallRule
                    {
                        Block           = (pieces[1].Equals("block", StringComparison.OrdinalIgnoreCase)),
                        IPAddressRanges = pieces[2].Split(',').Select(p => IPAddressRange.Parse(p)).ToList(),
                        Name            = "EXTRA_" + pieces[0].Trim(),
                        AllowPortRanges = pieces[3].Split(',').Select(p => PortRange.Parse(p)).Where(p => p.MinPort >= 0).ToList(),
                        PlatformRegex   = new Regex(pieces[4].Replace('*', '.'), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)
                    };
                    if (firewallBlockRuleObj.PlatformRegex.IsMatch(IPBanOS.Name))
                    {
                        extraRules.Add(firewallBlockRuleObj);
                    }
                }
                else
                {
                    IPBanLog.Warn("Firewall block rule entry should have 3 comma separated pieces: name;ips;ports. Invalid entry: {0}", firewallBlockRule);
                }
            }
        }