Esempio n. 1
0
    public void AddWatcher(string source, string log, int id)
    {
        if (source == log && log == null)
            {
                throw new ArgumentNullException("Either source or log must be set!");
            }

            // if legeacy
            if (System.Environment.OSVersion.Version.Major < 6)
            {
                string queryString = "Select * from __InstanceCreationEvent Where TargetInstance ISA 'Win32_NTLogEvent'";
                if (source != null)
                    queryString += " AND TargetInstance.Sourcename = '" + source + "'";
                if (log != null)
                    queryString += " AND TargetInstance.LogFile = '" + log + "'";
                queryString += " AND (TargetInstance.EventCode = " + id + ")";
                ManagementEventWatcher managementWatcher = new ManagementEventWatcher(new EventQuery(queryString));
                managementWatcher.Start();
                managementWatcher.EventArrived += EventRecordWritten;
                managementWatchers.Add(managementWatcher);
            }
            else
            {
                string queryString = "<QueryList><Query Id='0' Path='" + log + "'><Select Path='" + log + "'>*[System[Provider[@Name='" + source + "']]] and *[System[EventID=" + id + "]]</Select></Query></QueryList>";

                EventLogQuery query = new EventLogQuery(log, PathType.LogName, queryString);
                EventLogWatcher eventWatcher = new EventLogWatcher(query);
                eventWatcher.EventRecordWritten += EventRecordWritten;
                eventWatcher.Enabled = true;
                eventWatchers.Add(eventWatcher);
            }
    }
Esempio n. 2
0
 public void Start()
 {
     string queryText = GetQueryText();
     this.watcher = new EventLogWatcher(new EventLogQuery("Microsoft-Windows-Diagnosis-PLA/Operational", PathType.LogName, queryText));
     this.watcher.EventRecordWritten += this.OnEventWritten;
     this.watcher.Enabled = true;
     this.collector.Start();
 }
        private void Start(string eventLog)
        {
            var query   = new EventLogQuery(eventLog, PathType.LogName);
            var watcher = new System.Diagnostics.Eventing.Reader.EventLogWatcher(query);

            watcher.EventRecordWritten += new EventHandler <EventRecordWrittenEventArgs>(SystemErrorHandler);
            watcher.Enabled             = true;
        }
Esempio n. 4
0
        public LogPublisher(EventLog eventLog, Topic topic)
        {
            this.topic = topic;

            // Creates an EventLog watcher and subscribes to EventRecordWritten event
            var query = new EventLogQuery(eventLog.Log, PathType.LogName);
            watcher = new EventLogWatcher(query);
            watcher.EventRecordWritten += WatcherEventRecordWritten;
            watcher.Enabled = true;
        }
Esempio n. 5
0
        public static IObservable<EventRecord> FromLog(string name)
        {
            var q = new EventLogQuery(name, PathType.LogName);
            var watcher = new EventLogWatcher(q);

            return Observable.Create<EventRecord>(o =>
                {
                    watcher.EventRecordWritten +=
                        (sender, args) =>
                            {
                                if (args.EventException != null)
                                    o.OnError(args.EventException);
                                else
                                    o.OnNext(args.EventRecord);
                            };

                    watcher.Enabled = true;

                    return watcher;
                });
        }
Esempio n. 6
0
        private void read_single_log_thread(log_info log) {
            string query_string = "*";
            if (provider_name != "")
                query_string = "*[System/Provider/@Name=\"" + provider_name + "\"]";

            int max_event_count = int.MaxValue;
            // debugging - load much less, faster testing
            if (util.is_debug)
                max_event_count = 250;

            try {
                // we can read the number of entres only for local logs
                if (provider_name == "" && log.remote_machine_name == "") {
                    var dummy_log = new EventLog(log.log_type);
                    lock(this)
                        log.full_log_count_ = dummy_log.Entries.Count;
                    dummy_log.Dispose();
                }

                // waiting for user to set the password
                if ( log.remote_machine_name != "")
                    while ( remote_password_ == "")
                        Thread.Sleep(100);

                SecureString pwd = new SecureString();
                foreach ( char c in remote_password_)
                    pwd.AppendChar(c);
                EventLogSession session = log.remote_machine_name != "" ? new EventLogSession(log.remote_machine_name, remote_domain_name, remote_user_name, pwd, SessionAuthentication.Default) : null;
                pwd.Dispose();

                EventLogQuery query = new EventLogQuery(log.log_type, PathType.LogName, query_string);
                query.ReverseDirection = reverse_;
                if ( session != null)
                    query.Session = session;

                EventLogReader reader = new EventLogReader(query);
                int read_idx = 0;
                for (EventRecord rec = reader.ReadEvent(); rec != null && !log.disposed_ && read_idx++ < max_event_count ; rec = reader.ReadEvent())
                    lock (this) {
                        log.last_events_.Add(rec);
                        ++log.cur_log_count_;
                    }

                lock (this)
                    log.listening_for_new_events_ = true;

                // at this point, listen for new events
                if (reverse_) {
                    // if reverse, I need to create another query, or it won't allow watching
                    query = new EventLogQuery(log.log_type, PathType.LogName, query_string);                
                    if ( session != null)
                        query.Session = session;                    
                }
				using (var watcher = new EventLogWatcher(query))
				{
					watcher.EventRecordWritten += (o, e) => {
                        lock(this)
                            log.new_events_.Add(e.EventRecord);
					};
					watcher.Enabled = true;

                    while ( !log.disposed_)
                        Thread.Sleep(100);
				}

            } catch (Exception e) {
                logger.Error("can't create event log " + log.log_type + "/" + remote_machine_name + " : " + e.Message);
                errors_.add("Can't create Log " + log.log_type + " on machine " + remote_machine_name + ", Reason=" + e.Message);
            }
            
        }
Esempio n. 7
0
        public static void Main(string[] args)
        {
            int exitCode = 0;
            IntPtr session = IntPtr.Zero;
            string channelpath;
            string query = null;
            EventLogWatcher watcher = null;

            try
            {
                //
                // Parse the command line.
                //
                if (args.Length == 0)
                {
                    Console.WriteLine("Error: No parameters provided.");
                    PrintUsage();
                    Environment.Exit(1);
                }
                if (args[0] == "/?" || args[0] == "-?")
                {
                    PrintUsage();
                    Environment.Exit(1);
                }

                channelpath = args[0];
                char[] delimiters = { ':' };

                for (int i = 1; i < args.Length; i++)
                {
                    String option = args[i].Substring(1);
                    String[] words = option.Split(delimiters, 2);
                    words[0] = words[0].ToLower(CultureInfo.InvariantCulture);

                    switch (words[0])
                    {
                        case "query":
                        case "q":
                            if (query != null)
                            {
                                Console.WriteLine("Options '/query' and '/structuredquery' cannot both be specified.");
                                PrintUsage();
                                Environment.Exit(1);
                            }
                            query = words[1];
                            break;

                        case "structuredquery":
                        case "sq":
                            if (query != null)
                            {
                                Console.WriteLine("Options '/query' and '/structuredquery' cannot both be specified.");
                                PrintUsage();
                                Environment.Exit(1);
                            }

                            using (StreamReader sr = new StreamReader(words[1]))
                            {
                                String line;
                                while ((line = sr.ReadLine()) != null)
                                {
                                    query += line;
                                }
                            }
                            break;

                        default:
                            Console.WriteLine("Unrecognized parameter option: {0}.", words[0]);
                            PrintUsage();
                            Environment.Exit(1);
                            break;
                    }
                }

                //
                // Initialize the query string to retrieve all future events.
                //
                if (query == null)
                {
                    query = "*";
                }

                //
                // Subscribe to the event log and start watching for new events.
                //
                EventLogQuery subscriptionQuery = new EventLogQuery(channelpath, PathType.LogName, query);

                watcher = new EventLogWatcher(subscriptionQuery);
                watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(DisplayEventCallback);
                watcher.Enabled = true;

                //
                // Continue watching until user stops the subscription.
                //
                Console.WriteLine("\nPress <enter> to stop subscription.\n");
                Console.Read();
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("You do not have the correct permissions. " +
                                  "Try re-running the sample with administrator privileges.\n" + e.ToString());
                exitCode = 1;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                exitCode = 1;
            }
            finally
            {
                //
                // Stop the event subscription.
                //
                if (watcher != null)
                {
                    watcher.Enabled = false;
                    watcher.Dispose();
                }
            }
            Environment.Exit(exitCode);
        }
        public void GetWindowsEventLogWithBookmark(string logName, string pathTypeName, string query, string bookmark)
        {
            PathType pathType;
            switch (pathTypeName)
            {
                case "LogName":
                    {
                        pathType = PathType.LogName;
                        break;
                    }

                case "FilePath":
                    {
                        pathType = PathType.FilePath;
                        break;
                    }

                default:
                    {
                        throw new ArgumentException("Incorrect path type. Specify 'LogName' or 'FilePath'", "pathTypeName");
                    }
            }

            EventLogQuery q = new EventLogQuery(logName, pathType, query);
            EventBookmark eventBookmark = this.ParseBookmarkString(bookmark) ?? null;
            if (bookmark == null)
            {
                this.watcher = new EventLogWatcher(q);
            }
            else
            {
                this.watcher = new EventLogWatcher(q, eventBookmark);
            }
        }
        private void SetupWatcher()
        {
            if (useLegacyWatcher)
            {
                SetupLegacyWatcher();
                return;
            }

            string queryString = GetQueryString();
            query = new EventLogQuery("Security", PathType.LogName, queryString);
            reader = new EventLogReader(query);
            reader.BatchSize = 10;
            watcher = new EventLogWatcher(query);
            watcher.EventRecordWritten += EventRecordWritten;
            watcher.Enabled = true;
        }
        protected override void OnStop()
        {
            base.OnStop();

            run = false;
            query = null;
            watcher = null;
            legacyWatcher = null;

            Log.Write(LogLevel.Info, "Stopped IPBan service");
        }
 private void SetupWatcher()
 {
     string queryString = GetQueryString();
     query = new EventLogQuery(null, PathType.LogName, queryString);
     reader = new EventLogReader(query);
     reader.BatchSize = 10;
     watcher = new EventLogWatcher(query);
     watcher.EventRecordWritten += EventRecordWritten;
     watcher.Enabled = true;
 }
Esempio n. 12
0
 private void SetupWatcher()
 {
     int id = 0;
     string queryString = "<QueryList>";
     foreach (ExpressionsToBlockGroup group in config.Expressions.Groups)
     {
         ulong keywordsDecimal = ulong.Parse(group.Keywords.Substring(2), NumberStyles.AllowHexSpecifier);
         queryString += "<Query Id='" + (++id).ToString() + "' Path='" + group.Path + "'><Select Path='" + group.Path + "'>*[System[(band(Keywords," + keywordsDecimal.ToString() + "))]]</Select></Query>";
     }
     queryString += "</QueryList>";
     query = new EventLogQuery("Security", PathType.LogName, queryString);
     reader = new EventLogReader(query);
     reader.BatchSize = 10;
     watcher = new EventLogWatcher(query);
     watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(EventRecordWritten);
     watcher.Enabled = true;
 }
Esempio n. 13
0
        public EventLogInput(InputElement input, SelectorElement selector, EventQueue equeue)
            : base(input, selector, equeue)
        {
            // Event log query with suppressed events logged by this service
            StringBuilder qstr = new StringBuilder();
            qstr.Append("<QueryList>");
            qstr.Append("<Query>");
            qstr.Append(selector.Query.Value);
            qstr.Append("<Suppress Path=\"Application\">*[System/Provider/@Name=\"F2B\"]</Suppress>");
            qstr.Append("</Query>");
            qstr.Append("</QueryList>");

            EventLogSession session = null;
            if (input.Server != string.Empty)
            {
                SecureString pw = new SecureString();
                Array.ForEach(input.Password.ToCharArray(), pw.AppendChar);
                session = new EventLogSession(input.Server, input.Domain,
                                              input.Username, pw,
                                              SessionAuthentication.Default);
                pw.Dispose();
            }

            EventLogQuery query = new EventLogQuery(null, PathType.LogName, qstr.ToString());
            if (session != null)
            {
                query.Session = session;
            }

            // create event watcher (must be enable later)
            watcher = new EventLogWatcher(query);
            watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(
                    (s, a) => EventRead(s, a));

            // event data parsers (e.g. XPath + regex to extract event data)
            // (it is important to preserve order - it is later used as array index)
            List<Tuple<string, EventDataElement>> tmp = new List<Tuple<string, EventDataElement>>();
            tmp.Add(new Tuple<string,EventDataElement>("address", selector.Address));
            tmp.Add(new Tuple<string,EventDataElement>("port", selector.Port));
            tmp.Add(new Tuple<string,EventDataElement>("username", selector.Username));
            tmp.Add(new Tuple<string,EventDataElement>("domain", selector.Domain));

            evtmap = new Dictionary<string, Tuple<int, int>>();
            evtregex = new List<Regex>();
            List<string> xPathRefs = new List<string>();

            for (int i = 0; i < tmp.Count; i++)
            {
                string evtdescr = tmp[i].Item1;
                EventDataElement evtdata = tmp[i].Item2;

                if (evtdata == null || string.IsNullOrEmpty(evtdata.XPath))
                {
                    if (evtdescr == "address")
                    {
                        throw new ArgumentException("No address in " + Name + " configuration");
                    }

                    evtmap[evtdescr] = new Tuple<int, int>(i, -1);

                    continue;
                }

                Regex regex = null;
                if (!string.IsNullOrWhiteSpace(evtdata.Value))
                {
                    string evtstr = evtdata.Value.Trim();
                    try
                    {
                        regex = new Regex(evtstr, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    }
                    catch (ArgumentException ex)
                    {
                        Log.Error("Invalid " + Name + " " + evtdescr + " regex: "
                            + evtstr + " (" + ex.Message + ")");
                        throw;
                    }
                }

                evtregex.Add(regex);
                if (xPathRefs.Contains(evtdata.XPath))
                {
                    int index = xPathRefs.IndexOf(evtdata.XPath);
                    evtmap[evtdescr] = new Tuple<int, int>(i, index);
                }
                else
                {
                    xPathRefs.Add(evtdata.XPath);
                    evtmap[evtdescr] = new Tuple<int, int>(i, xPathRefs.Count - 1);
                }
            }

            Debug.Assert(tmp.Count == evtmap.Count,
                "Invalid index map size (tmp[" + tmp.Count
                + "] != map[" + evtmap.Count + "]).");

            evtsel = new EventLogPropertySelector(xPathRefs);
        }
Esempio n. 14
0
        private void InitWatcher()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); // need to fix MS bug

            if (string.IsNullOrWhiteSpace(EventDescription.Keywords))
            {
                if (_rxFilter != null)
                    _rxFilter = null;
            }
            else
            {
                _rxFilter = new Regex(EventDescription.Keywords);
            }

            // create X-Path query
            // for example:
            // *[System[Provider[@Name='.NET Runtime' or @Name='.NET Runtime Optimization Service'
            //  or @Name='Microsoft-Windows-Dhcp-Client'] and
            // (Level=1  or Level=2 or Level=3 or Level=4 or Level=0 or Level=5) and
            // (EventID=1 or EventID=2 or  (EventID &gt;= 4 and EventID &lt;= 7) )]]
            StringBuilder xq = new StringBuilder();
            xq.Append("*");

            StringBuilder paths = new StringBuilder();
            if (string.IsNullOrWhiteSpace(EventDescription.LogSources) == false && EventDescription.LogSources.StartsWith("Please") == false)
            {
                // add paths
                string[] ps = EventDescription.LogSources.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                ps.ToList().ForEach(x => { if (paths.Length > 0) paths.Append(" or "); paths.Append("@Name='" + x.Trim() + "'"); });
            }

            StringBuilder ls = new StringBuilder();
            if (EventDescription.IsCritical || EventDescription.IsError || EventDescription.IsInformation || EventDescription.IsVerbose || EventDescription.IsWarning)
            {
                // add levels
                if (EventDescription.IsCritical)
                {
                    ls.Append("Level=" + ((int)StandardEventLevel.Critical).ToString());
                }
                if (EventDescription.IsError)
                {
                    if (ls.Length > 0)
                        ls.Append(" or ");
                    ls.Append("Level=" + ((int)StandardEventLevel.Error).ToString());
                }
                if (EventDescription.IsInformation)
                {
                    if (ls.Length > 0)
                        ls.Append(" or ");
                    ls.Append("Level=" + ((int)StandardEventLevel.Informational).ToString() + " or Level=" + ((int)StandardEventLevel.LogAlways).ToString());
                }
                if (EventDescription.IsVerbose)
                {
                    if (ls.Length > 0)
                        ls.Append(" or ");
                    ls.Append("Level=" + ((int)StandardEventLevel.Verbose).ToString());
                }
                if (EventDescription.IsWarning)
                {
                    if (ls.Length > 0)
                        ls.Append(" or ");
                    ls.Append("Level=" + ((int)StandardEventLevel.Warning).ToString());
                }
            }

            StringBuilder iid = new StringBuilder();
            // append Event IDs (without exclude expression)
            if (string.IsNullOrWhiteSpace(EventDescription.EventIds) == false)
            {
                // supressed IDs
                supressedIDs = EventDescription.EventIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).Where(x => x.StartsWith("-") == true).Select(x => x.Substring(1)).Cast<int>().ToArray();

                List<string> iids = EventDescription.EventIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).Where(x => x.StartsWith("-") == false).ToList();
                if (iids.Where(x => x.Contains("-") == false).Count() > 0)
                    iids.Where(x => x.Contains("-") == false).ToList().ForEach(x => { if (iid.Length > 0) iid.Append(" or "); iid.Append("EventID = " + x); });
                if (iids.Where(x => x.Contains("-") == true).Count() > 0)
                    iids.Where(x => x.Contains("-") == true).ToList().ForEach(x =>
                    {
                        if (iid.Length > 0) iid.Append(" or ");
                        string[] xx = x.Split(new char[] { '-' });
                        iid.Append("(EventID >= " + xx[0] + " and EventID <= " + xx[1] + ")");
                    });
            }

            if (paths.Length > 0 || ls.Length > 0 || iid.Length > 0)
            {
                xq.Append("[System[");

                if (paths.Length > 0)
                {
                    xq.Append("Provider[");
                    xq.Append(paths.ToString());
                    xq.Append("]");
                }

                if (ls.Length > 0)
                {
                    if (paths.Length > 0)
                        xq.Append(" and ");
                    xq.Append("(" + ls.ToString() + ")");
                }

                if (iid.Length > 0)
                {
                    if (paths.Length > 0 || ls.Length > 0)
                        xq.Append(" and ");
                    xq.Append("(");
                    xq.Append(iid.ToString());
                    xq.Append(")");

                }

                xq.Append("]]");
            }

            EventLogQuery subscriptionQuery = new EventLogQuery(decription.EventLogName, PathType.LogName, xq.ToString());

            watcher = new EventLogWatcher(subscriptionQuery);
            watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);
        }