Пример #1
0
        public void GetReport()
        {
            var logQuery = new MSUtil.LogQueryClass();

            var input = new MSUtil.COMTSVInputContextClass
            {
                iSeparator = Separator
            };

            var resultDataSet = logQuery.Execute($@"SELECT Level, COUNT(*) AS Total FROM {_sourcePath}\*.log GROUP BY Level", input);

            while (!resultDataSet.atEnd())
            {
                var record = resultDataSet.getRecord();
                Console.WriteLine($"{record.getValue("Level")}:{record.getValue("Total")}");
                resultDataSet.moveNext();
            }

            resultDataSet = logQuery.Execute($@"SELECT * FROM {_sourcePath}\*.log WHERE Level='ERROR'", input);
            while (!resultDataSet.atEnd())
            {
                var record = resultDataSet.getRecord();
                Console.WriteLine($"{record.getValue("Level")} : {record.getValue("Date")} : {record.getValue("Message")}");
                resultDataSet.moveNext();
            }
        }
Пример #2
0
 public override void Open()
 {
     if (state != System.Data.ConnectionState.Open)
     {
         this.query      = new LogQuery();
         this.connection = new IISLogInputFormat();
     }
     state = System.Data.ConnectionState.Open;
 }
Пример #3
0
        public DataTable readFromEvt(string sql)
        {
            try
            {
                DataTable datat = new DataTable();
                datat.Columns.Add("事件ID", typeof(string));
                datat.Columns.Add("日期", typeof(string));
                datat.Columns.Add("来源", typeof(string));
                datat.Columns.Add("描述", typeof(string));
                // Instantiate the LogQuery object
                LogQuery oLogQuery = new LogQuery();
                // Instantiate the Event Log Input Format object
                EvtInputFormat oEvtInputFormat = new EvtInputFormat();
                // Set its "direction" parameter to "BW"
                //oEvtInputFormat.direction = "BW";
                // Create the query
                string query = sql;
                // Execute the query
                LogRecordSet oRecordSet = oLogQuery.Execute(query, oEvtInputFormat);
                while (!oRecordSet.atEnd())
                {
                    var     itemData = oRecordSet.getRecord();
                    DataRow dr       = datat.NewRow();
                    dr["事件ID"] = itemData.getValue("EventID").ToString();
                    dr["日期"]   = itemData.getValue("TimeGenerated").ToString();
                    dr["来源"]   = itemData.getValue("SourceName").ToString();
                    dr["描述"]   = itemData.getValue("Message").ToString();
                    datat.Rows.Add(dr);
                    oRecordSet.moveNext();
                }

                // Close the recordset
                oRecordSet.close();
                return(datat);
            }
            catch (System.Runtime.InteropServices.COMException exc)
            {
                MessageBox.Show("Unexpected error: " + exc.Message);
                return(null);
            }
        }
Пример #4
0
        static int Main(string[] args)
        {
            bool binst = false;
            bool bdelete = false;
            bool bnorun = false;

            string evtid = "4625"; //The ID in the Security Log for the event that we're looking for ("An account failed to log on.")
            string evtrshld = "10"; //adjust this number to determine what should be the threshold for the max # of failed events before an IP is flagged

            currdir = Directory.GetCurrentDirectory();

            //check directory write permissions as the first step. If we can't output the netsh script, we can't be useful.
            if (!HasFilePermissions())
            {
                Console.WriteLine("You don't have the required file access permissions to run this application.");
                return (int)ErrorLevel.ErrFilePermission;
            }

            mydb = "Data Source=\"" + currdir + "\\bannedips.dat\";Version=3;";

            if (args.Length > 0) //check args for "--install", "--remove", "--norun" or "--debug"
            {
               foreach (string s in args)
               {
                   switch(s.ToLower()) {
                       case "--debug":
                           bdebug = true; break;
                       case "--install":
                           binst = true; break;
                       case "--remove":
                           bdelete = true; break;
                       case "--norun":
                           bnorun = true; break;

                   }
                }
               if (binst && bdelete)  //if providing both install & delete options
               {
                   OutputMsg("Options --install and --remove are mutually exclusive. Please choose only one.");
                   return 0;
               }
            }

            if (bdebug) OutputMsg("SQLite DB Connection String: " + mydb);

            if (binst) //original setup for firewall rule and scheduled task
            {
                //check to see if the rule is already there. We don't want to have extra copies
                if (!FirewallRuleExists())
                {
                    if (!AddFirewallRule())  //now add the rule if it's not already there
                    {
                        OutputMsg("Failed creating the firewall rule to block IPs. Unable to continue.");
                        return (int)ErrorLevel.ErrFirewall;
                    }
                }

                if (!ScheduleTask())  //now add scheduled task, if exists it will be overwritten
                {
                    OutputMsg("Failed creating a scheduled task to update list of blocked IP addresses. Unable to continue.");
                    return (int)ErrorLevel.ErrScheduler;
                }

                //it will continue to run once after the installation unless "--norun" is specified
                if (bnorun)
                {
                    OutputMsg("Installation was successful. Exiting app until next scheduled run.");
                    return 0;
                }
            }

            if (bdelete)   //remove firewall rule and the scheduled task (if they exist), then exit the app
            {
                if (!DeleteFirewallRule())
                {
                    OutputMsg("Failed deleting the firewall rule: \"Banned IP Addresses\". Unable to continue.");
                    return (int)ErrorLevel.ErrFirewall;
                }

                if (!RemoveScheduledTask())
                {
                    OutputMsg("Failed removing the scheduled task to update banned IP address list. Unable to continue.");
                    return (int)ErrorLevel.ErrScheduler;
                }
                OutputMsg("Scheduled System Task and Firewall Rule are now uninstalled.");
                return 0;
            }

            //we're starting the scheduled run. It could be happening without required installation
            if (!binst && !FirewallRuleExists()) //skip if right after installation
            {
                OutputMsg("Firewall rule not found. Run the app with \"--install\" parameter to set it up.");
                return (int)ErrorLevel.ErrFirewall;
            }

            //get records from the Security Logs
            try
            {
                MSUtil.LogQueryClass lq = new MSUtil.LogQueryClass();
                MSUtil.ILogRecordset rs = lq.Execute("SELECT EXTRACT_TOKEN(Strings, 19, '|') AS [IP4Detected], MAX(TimeWritten) AS [DateLastSeen]," +
                    " COUNT(*) AS [InstanceCount] FROM Security WHERE EventID=" + evtid +
                    " AND TimeWritten>SUB(TO_LOCALTIME(SYSTEM_TIMESTAMP()), TIMESTAMP('0000-01-01 23:59:59', 'yyyy-MM-dd HH:mm:ss'))" +
                    " GROUP BY EXTRACT_TOKEN(Strings, 19, '|') HAVING COUNT(*)>" + evtrshld);
                while (!rs.atEnd())
                {
                    MSUtil.ILogRecord rec = rs.getRecord();

                    FoundInLog tmp = new FoundInLog();
                    tmp.IP4Detected = rec.getValue(0);
                    tmp.DateLastSeen = rec.getValue(1);
                    tmp.InstanceCount = rec.getValue(2);

                    spmrs.Add(tmp);

                    if (bdebug) OutputMsg(tmp.IP4Detected.ToString() + ", " + tmp.DateLastSeen.ToShortDateString() + ", " + tmp.InstanceCount.ToString());
                    rs.moveNext();
                }

                if (spmrs.Count == 0)
                {
                    OutputMsg("Run successfully completed, no new records were found.");
                    return 0;
                }
            }
            catch (Exception e)
            {
                OutputMsg("Unable to query Event Log. Make sure LogParser is installed (see README for details)." , e.ToString());
                return (int)ErrorLevel.ErrLogParser;
            }

            //add the new records to the local sqlite3 database
            if (!UpdateDBRecords())
            {
                OutputMsg("Problem writing to the \"bannedips.dat\" database");
                return (int)ErrorLevel.ErrSQLiteDB;
            }

            //export updated records to a script file to be used with netsh
            if (!ExportDBRecords())
            {
                OutputMsg("Problem writing to the netsh script file");
                return (int)ErrorLevel.ErrInputOutput;
            }

            //replace IP list in the firewall rule with the new set from the DB
            if (!UpdateFirewallRule())
            {
                OutputMsg("Problem calling netsh.exe to update firewall rule.");
                return (int)ErrorLevel.ErrNetShell;
            }

            //final step - record our activity
            if (!StampLastRun())
            {
                //nothing to do
            }

            //every step is nicely completed. Report success and be done.
            OutputMsg("IP Address Blacklist was successfully updated with data from last 24 hours.");
            return 0;
        }
Пример #5
0
 public override void Open()
 {
     if (state != System.Data.ConnectionState.Open)
     {
         this.query = new LogQuery();
         this.connection = new IISLogInputFormat();
     }
     state = System.Data.ConnectionState.Open;
 }
Пример #6
0
        private void btIIS(object sender, RoutedEventArgs e)
        {
            if (Common.checkLogParser())
            {
                #region 日志分析
                //string filename = "";
                Microsoft.Win32.OpenFileDialog dialogOpenFile = new Microsoft.Win32.OpenFileDialog();
                dialogOpenFile.Filter           = "IIS日志文件(*.log)|*.log";
                dialogOpenFile.RestoreDirectory = true;
                dialogOpenFile.Multiselect      = true;//允许同时选择多个文件
                //dialogOpenFile.InitialDirectory = "c:\\";
                //dialogOpenFile.FilterIndex = 2;
                List <string> filenames = new List <string>();
                if (dialogOpenFile.ShowDialog() == true)
                {
                    //filename = dialogOpenFile.FileName;
                    for (int fi = 0; fi < dialogOpenFile.FileNames.Length; fi++)
                    {
                        filenames.Add(dialogOpenFile.FileNames[fi].ToString());
                    }
                }
                else
                {
                    return;
                }

                //初始化
                LogQuery       oLogQuery       = new LogQuery();
                IISInputFormat oIISInputFormat = new IISInputFormat();
                DataTable      datat           = new DataTable();
                datat.Columns.Add("date", typeof(string));
                datat.Columns.Add("time", typeof(string));
                datat.Columns.Add("method", typeof(string));
                datat.Columns.Add("uri", typeof(string));
                datat.Columns.Add("query", typeof(string));
                datat.Columns.Add("ip", typeof(string));
                datat.Columns.Add("status", typeof(string));
                datat.Columns.Add("useragent", typeof(string));

                foreach (string filename in filenames)
                {
                    string       query      = @"SELECT date,time,cs-method,cs-uri-stem,cs-uri-query,c-ip,sc-status,cs(User-Agent)  from '" + filename + "'";// GROUP BY c-ip
                    LogRecordSet oRecordSet = oLogQuery.Execute(query, oIISInputFormat);
                    while (!oRecordSet.atEnd())
                    {
                        var     itemData = oRecordSet.getRecord();
                        DataRow dr       = datat.NewRow();
                        dr["date"]      = itemData.getValue("date").ToString("yyyy-MM-dd");
                        dr["time"]      = itemData.getValue("time").ToString("hh:mm:ss");
                        dr["method"]    = itemData.getValue("cs-method").ToString();
                        dr["uri"]       = itemData.getValue("cs-uri-stem").ToString();
                        dr["query"]     = itemData.getValue("cs-uri-query").ToString();
                        dr["ip"]        = itemData.getValue("c-ip").ToString();
                        dr["status"]    = itemData.getValue("sc-status").ToString();
                        dr["useragent"] = itemData.getValue("cs(User-Agent)").ToString();
                        datat.Rows.Add(dr);
                        oRecordSet.moveNext();
                    }
                    oRecordSet.close();
                }
                dgQueryResult.Columns[0].Header = (object)("日期");
                dgQueryResult.Columns[1].Header = (object)("时间");
                dgQueryResult.Columns[2].Header = (object)("方法");
                dgQueryResult.Columns[3].Header = (object)("相对路径");
                dgQueryResult.Columns[4].Header = (object)("查询");
                dgQueryResult.Columns[5].Header = (object)("IP");
                dgQueryResult.Columns[6].Header = (object)("状态");
                dgQueryResult.Columns[7].Header = (object)("用户代理");
                dgQueryResult.DataContext       = datat.DefaultView;
                #endregion
            }
            else
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("该功能需要安装LogParser.", "警告", MessageBoxButton.OK, MessageBoxImage.Exclamation);

                System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();

                //设置外部程序名
                Info.FileName = "LogParser.msi";

                //设置外部程序工作目录为   C:\ 
                //Info.WorkingDirectory = @"D:\常用软件\eclipse";

                //最小化方式启动
                //Info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;

                //声明一个程序类
                System.Diagnostics.Process Proc;

                try
                {
                    Proc = System.Diagnostics.Process.Start(Info);
                    System.Threading.Thread.Sleep(500);
                }
                catch (System.ComponentModel.Win32Exception)
                {
                    return;
                }
            }
        }