Inheritance: System.ServiceProcess.ServiceBase
 public static void RunConsole(string[] args)
 {
     IPBanService svc = new IPBanService();
     svc.OnStart(args);
     Console.WriteLine("Press ENTER to quit");
     Console.ReadLine();
     svc.OnStop();
 }
Exemplo n.º 2
0
 private static void CreateService()
 {
     if (service != null)
     {
         service.Dispose();
     }
     service = IPBanService.CreateService <IPBanService>();
     service.Start();
 }
Exemplo n.º 3
0
 private static void CreateService(bool testing)
 {
     if (service != null)
     {
         service.Dispose();
     }
     service = IPBanService.CreateService(testing);
     service.Start();
     eventViewer = new IPBanWindowsEventViewer(service);
 }
Exemplo n.º 4
0
        public static void MacMain(string[] args)
        {
            IPBanService service = IPBanService.CreateService();

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

            wait.WaitOne();
        }
Exemplo n.º 5
0
        public static void LinuxMain(string[] args)
        {
            bool         testing = false; // TODO: Change to true if we are running Linux tests
            IPBanService service = IPBanService.CreateService(testing);

            service.Start();
            IPBanLog.Write(LogLevel.Warning, "IPBan Linux Service Running, Press Ctrl-C to quit.");
            ManualResetEvent wait = new ManualResetEvent(false);

            wait.WaitOne();
        }
Exemplo n.º 6
0
 /// <summary>
 /// Download data from a URL using GET method
 /// </summary>
 /// <param name="url">Url</param>
 /// <returns>Raw bytes</returns>
 public Task <byte[]> DownloadDataAsync(string url)
 {
     Interlocked.Increment(ref requestCount);
     using (WebClient client = new WebClient())
     {
         Assembly a = (Assembly.GetEntryAssembly() ?? IPBanService.GetIPBanAssembly());
         client.UseDefaultCredentials = true;
         client.Headers["User-Agent"] = a.GetName().Name;
         return(client.DownloadDataTaskAsync(url));
     }
 }
Exemplo n.º 7
0
        public static int RunConsole(string[] args)
        {
            IPBanService service = CreateService();

            if (args.Contains("test", StringComparer.OrdinalIgnoreCase))
            {
                service.RunTestsOnStart = true;
            }
            service.Start();
            Console.WriteLine("Press ENTER to quit");
            Console.ReadLine();
            service.Stop();
            return(0);
        }
Exemplo n.º 8
0
 public static void RunConsole(string[] args)
 {
     IPBanService svc = new IPBanService();
     svc.OnStart(args);
     Console.WriteLine("Press ENTER to quit");
     string line;
     while ((line = Console.ReadLine()).Length != 0)
     {
         if (line.Equals("t", StringComparison.OrdinalIgnoreCase))
         {
             svc.ReadAppSettings();
             svc.RunTests();
         }
     }
     svc.OnStop();
 }
Exemplo n.º 9
0
        public static void RunConsole(string[] args)
        {
            IPBanService svc = new IPBanService();

            svc.OnStart(args);
            Console.WriteLine("Press ENTER to quit");
            string line;

            while ((line = Console.ReadLine()).Length != 0)
            {
                if (line.Equals("t", StringComparison.OrdinalIgnoreCase))
                {
                    svc.ReadAppSettings();
                    svc.RunTests();
                }
            }
            svc.OnStop();
        }
Exemplo n.º 10
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);
            IPAddressLogInfo info = IPBanService.GetIPAddressInfoFromRegex(dns, regex, line);

            if (info.FoundMatch)
            {
                info.Source = info.Source ?? Source;
                IPBanLog.Debug("Log file found match, ip: {0}, user: {1}, source: {2}, count: {3}", info.IPAddress, info.UserName, info.Source, info.Count);
                failedLogin.AddFailedLogin(info);
            }
            else
            {
                IPBanLog.Debug("No match for line {0}", line);
            }

            return(true);
        }
Exemplo n.º 11
0
 public Task <byte[]> MakeRequestAsync(string url, string postJson = null, params KeyValuePair <string, string>[] headers)
 {
     Interlocked.Increment(ref requestCount);
     using (WebClient client = new WebClient())
     {
         Assembly a = (Assembly.GetEntryAssembly() ?? IPBanService.GetIPBanAssembly());
         client.UseDefaultCredentials = true;
         client.Headers["User-Agent"] = a.GetName().Name;
         foreach (KeyValuePair <string, string> header in headers)
         {
             client.Headers[header.Key] = header.Value;
         }
         if (string.IsNullOrWhiteSpace(postJson))
         {
             return(client.DownloadDataTaskAsync(url));
         }
         client.Headers["Content-Type"] = "application/json";
         return(client.UploadDataTaskAsync(url, "POST", Encoding.UTF8.GetBytes(postJson)));
     }
 }
Exemplo n.º 12
0
        private static void CreateService(bool test)
        {
            if (service != null)
            {
                service.Dispose();
            }
            service = IPBanService.CreateService();
            if (test)
            {
                // TODO: Move to unit test project
                service.MultiThreaded     = false;
                service.ManualCycle       = true;
                service.SubmitIPAddresses = false;
                service.DB.Truncate(true);
            }
            service.Start();

            // attach Windows event viewer to the service
            eventViewer = new IPBanWindowsEventViewer(service);
        }
Exemplo n.º 13
0
        private void ExtractEventViewerXml(XmlDocument doc, out string ipAddress, out string source, out string userName)
        {
            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);

            ipAddress = source = userName = null;

            if (keywordsNode != null)
            {
                // we must match on keywords
                foreach (ExpressionsToBlockGroup group in service.Config.WindowsEventViewerGetGroupsMatchingKeywords(keywordsULONG))
                {
                    foreach (ExpressionToBlock 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.Write(LogLevel.Information, "No nodes found for xpath {0}", expression.XPath);
                            ipAddress = 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.Write(LogLevel.Information, "No regex, so counting as a match");
                        }
                        else
                        {
                            bool foundMatch = false;

                            // try and find an ip from any of the nodes
                            foreach (XmlNode node in nodes)
                            {
                                // if we get a match, stop checking nodes
                                if ((foundMatch = IPBanService.GetIPAddressAndUserNameFromRegex(expression.RegexObject, node.InnerText, ref ipAddress, ref userName)))
                                {
                                    break;
                                }
                            }

                            if (!foundMatch)
                            {
                                // match fail, null out ip, we have to match ALL the nodes or we get null ip and do not ban
                                IPBanLog.Write(LogLevel.Information, "Regex {0} did not match any nodes with xpath {1}", expression.Regex, expression.XPath);
                                ipAddress = null;
                                break;
                            }
                        }
                    }

                    if (ipAddress != null)
                    {
                        source = group.Source;
                        break;
                    }
                    ipAddress = source = userName = null; // set null for the next node attempt
                }
            }
        }
Exemplo n.º 14
0
 protected override void OnStop()
 {
     service.Stop();
     service = null;
     base.OnStop();
 }
Exemplo n.º 15
0
 protected override void OnStart(string[] args)
 {
     base.OnStart(args);
     service = CreateService();
     service.Start();
 }
Exemplo n.º 16
0
        private IPAddressLogInfo 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);
            IPAddressLogInfo info          = null;

            if (keywordsNode != null)
            {
                // we must match on keywords
                foreach (ExpressionsToBlockGroup group in service.Config.WindowsEventViewerGetGroupsMatchingKeywords(keywordsULONG))
                {
                    foreach (ExpressionToBlock 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.Info("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.Info("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)
                                {
                                    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.Info("Regex {0} did not match any nodes with xpath {1}", expression.Regex, expression.XPath);
                                info = null;
                                break;
                            }
                        }
                    }

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

            return(info);
        }
Exemplo n.º 17
0
        private bool PingFile(WatchedFile file, FileStream fs)
        {
            const int maxCountBeforeNewline = 1024;
            int       b;
            long      lastNewlinePos = -1;

            byte[] bytes;
            long   end = Math.Min(file.LastLength, fs.Length);
            int    countBeforeNewline = 0;

            fs.Position = file.LastPosition;

            IPBanLog.Info("Processing watched file {0}, len = {1}, pos = {2}", file.FileName, file.LastLength, file.LastPosition);

            while (fs.Position < end && countBeforeNewline++ != maxCountBeforeNewline)
            {
                // read until last \n is found
                b = fs.ReadByte();
                if (b == '\n')
                {
                    lastNewlinePos     = fs.Position - 1;
                    countBeforeNewline = 0;
                }
            }

            if (countBeforeNewline == maxCountBeforeNewline)
            {
                throw new InvalidOperationException("Log file " + this.fileMask + " may not be a plain text new line delimited file");
            }

            if (lastNewlinePos > -1)
            {
                // set file position ready for the next read right after the newline
                fs.Position = file.LastPosition;
                bytes       = new BinaryReader(fs).ReadBytes((int)(lastNewlinePos - fs.Position));

                // set position for next ping
                file.LastPosition = lastNewlinePos + 1;

                // read text and run regex to find ip addresses to ban
                string   subString = Encoding.UTF8.GetString(bytes);
                string[] lines     = subString.Split('\n');
                bool     foundOne  = false;

                // find ip and user name from all lines
                foreach (string line in lines)
                {
                    string trimmedLine = line.Trim();
                    IPBanLog.Debug("Parsing log file line {0}...", trimmedLine);
                    IPAddressLogInfo info = IPBanService.GetIPAddressInfoFromRegex(dns, Regex, trimmedLine);
                    if (info.FoundMatch)
                    {
                        info.Source = info.Source ?? Source;
                        IPBanLog.Debug("Log file found match, ip: {0}, user: {1}, source: {2}, count: {3}", info.IPAddress, info.UserName, info.Source, info.Count);
                        failedLogin.AddFailedLogin(info);
                        foundOne = true;
                    }
                    else
                    {
                        IPBanLog.Debug("No match for line {0}", line);
                    }
                }

                if (foundOne)
                {
                    // signal that we have found ip addresses
                    ipEvent.Set();
                }
            }

            return(maxFileSize > 0 && fs.Length > maxFileSize);
        }
Exemplo n.º 18
0
        private bool PingFile(WatchedFile file, FileStream fs)
        {
            const int maxCountBeforeNewline = 1024;
            int       b;
            long      lastNewlinePos = -1;

            byte[] bytes;
            long   end = Math.Min(file.LastLength, fs.Length);
            int    countBeforeNewline = 0;

            fs.Position = file.LastPosition;

            while (fs.Position < end && countBeforeNewline++ != maxCountBeforeNewline)
            {
                // read until last \n is found
                b = fs.ReadByte();
                if (b == '\n')
                {
                    lastNewlinePos     = fs.Position - 1;
                    countBeforeNewline = 0;
                }
            }

            if (countBeforeNewline == maxCountBeforeNewline)
            {
                throw new InvalidOperationException("Log file " + this.fileMask + " may not be a plain text new line delimited file");
            }

            if (lastNewlinePos > -1)
            {
                // set file position ready for the next read right after the newline
                fs.Position = file.LastPosition;
                bytes       = new BinaryReader(fs).ReadBytes((int)(lastNewlinePos - fs.Position));

                // set position for next ping
                file.LastPosition = lastNewlinePos + 1;

                // read text and run regex to find ip addresses to ban
                string   subString = Encoding.UTF8.GetString(bytes);
                string[] lines     = subString.Split('\n');
                string   ipAddress = null;
                string   userName  = null;
                bool     foundOne  = false;

                // find ip and user name from all lines
                foreach (string line in lines)
                {
                    IPBanLog.Write(LogLevel.Debug, "Parsing log file line {0}...", line);
                    bool foundMatch = IPBanService.GetIPAddressAndUserNameFromRegex(Regex, line.Trim(), ref ipAddress, ref userName);
                    if (foundMatch)
                    {
                        IPBanLog.Write(LogLevel.Debug, "Found match, ip: {0}, user: {1}", ipAddress, userName);
                        service.AddFailedLogin(ipAddress, Source, userName);
                        foundOne = true;
                    }
                    else
                    {
                        IPBanLog.Write(LogLevel.Debug, "No match!");
                    }
                }

                if (foundOne)
                {
                    // signal that we have found ip addresses
                    ipEvent.Set();
                }
            }

            return(maxFileSize > 0 && fs.Length > maxFileSize);
        }