Exemple #1
0
        private static void TestEventRead()
        {
            string LogName = "Application", SearchString = null, XPathQuery = null;
            int    MaxEvents       = 100;
            bool   SearchUseRegExp = false;

            using (EventLogSession eventLogSession = new EventLogSession())
            {
                EventLogQuery eventLogQuery = string.IsNullOrWhiteSpace(XPathQuery) ?
                                              new EventLogQuery(LogName, PathType.LogName)
                {
                    Session             = eventLogSession,
                    TolerateQueryErrors = true,
                    ReverseDirection    = true
                } :
                new EventLogQuery(LogName, PathType.LogName, XPathQuery)
                {
                    Session             = eventLogSession,
                    TolerateQueryErrors = true,
                    ReverseDirection    = true
                };
                int eventReadCounter = MaxEvents;
                using (EventLogReader eventLogReader = new EventLogReader(eventLogQuery))
                {
                    eventLogReader.Seek(System.IO.SeekOrigin.Begin, 0);
                    do
                    {
                        if (eventReadCounter <= 0)
                        {
                            break;
                        }

                        EventRecord eventData = eventLogReader.ReadEvent();
                        if (eventData == null)
                        {
                            break;
                        }

                        if (string.IsNullOrWhiteSpace(SearchString))
                        {
                            Console.WriteLine($"{eventData.TimeCreated}: {eventData.FormatDescription()}, {eventData.KeywordsDisplayNames}");
                            eventReadCounter--;
                        }
                        else
                        {
                            if (Regex.IsMatch(eventData.FormatDescription(), SearchUseRegExp ? SearchString : Regex.Escape(SearchString), RegexOptions.IgnoreCase))
                            {
                                Console.WriteLine($"{eventData.TimeCreated}: {eventData.FormatDescription()}");
                                eventReadCounter--;
                            }
                        }
                        eventData.Dispose();
                    } while (true);
                }

                return;
            }
        }
Exemple #2
0
        public static void ReadEvents()
        {
            String logName = "Application";

            String queryString = "*[System/Level=3]";

            EventLogQuery eventsQuery = new EventLogQuery(logName,
                                                          PathType.LogName, queryString);

            EventLogReader logReader;

            try
            {
                // Query the log and create a stream of selected events
                logReader = new EventLogReader(eventsQuery);
            }
            catch (EventLogNotFoundException e)
            {
                Console.WriteLine("Failed to query the log!");
                Console.WriteLine(e);
                return;
            }

            // For each event returned from the query
            for (EventRecord eventInstance = logReader.ReadEvent();
                 eventInstance != null;
                 eventInstance = logReader.ReadEvent())
            {
                //build an IEnumerable<object>
                List <object> varRepSet = new List <object>();
                for (int i = 0; i < eventInstance.Properties.Count; i++)
                {
                    varRepSet.Add((object)(eventInstance.Properties[i].Value.ToString()));
                }

                //wrapped in a try block as some fail to resolve using the second pathway (provider not found error"
                try
                {
                    //WORKS
                    string description1 = eventInstance.FormatDescription();

                    //neither of these work, they bring back the template string with empty values substituted
                    //BROKEN: format description with the built-in properties array
                    string description2 = eventInstance.FormatDescription(eventInstance.Properties);
                    //BROKEN: format description with the input explicitly typed as an IEnumerable<object>
                    string description3 = eventInstance.FormatDescription(varRepSet.AsEnumerable());

                    Console.WriteLine(description1);
                    Console.WriteLine(description2);
                    Console.WriteLine(description3);
                    Console.WriteLine("PRESS ANY KEY FOR NEXT EVENT, or CTRL+C TO EXIT...");
                    Console.ReadKey();
                }
                catch (Exception)
                {
                }
            }
        }
Exemple #3
0
        public SecurityLog(EventRecord rec)
        {
            Console.WriteLine(count++);
            ProcessId   = rec.ProcessId;
            TimeCreated = rec.TimeCreated;
            Source      = rec.ProviderName;

            var keyTask = new ProviderMetadataCache <int?>(rec.ProviderName, rec.Task);

            if (!Tasks.ContainsKey(keyTask))
            {
                Tasks[keyTask] = rec.TaskDisplayName;
            }
            Task = Tasks[keyTask];

            var keyOpeCode = new ProviderMetadataCache <short?>(rec.ProviderName, rec.Opcode);

            if (!OpCodes.ContainsKey(keyOpeCode))
            {
                OpCodes[keyOpeCode] = rec.OpcodeDisplayName;
            }
            OpCode = OpCodes[keyOpeCode];

            var keyKeyword = new ProviderMetadataCache <long?>(rec.ProviderName, rec.Keywords);

            if (!Keywords.ContainsKey(keyKeyword))
            {
                Keywords[keyKeyword] = rec.KeywordsDisplayNames.FirstOrDefault();
            }

            Message = rec.FormatDescription();
        }
Exemple #4
0
        public override string Execute(EventEntry evtlog)
        {
            if (!(evtlog.LogData.GetType() == typeof(EventRecordWrittenEventArgs) ||
                  evtlog.LogData.GetType().IsSubclassOf(typeof(EventRecordWrittenEventArgs))))
            {
                return(goto_next);
            }

            EventRecordWrittenEventArgs evtarg = evtlog.LogData as EventRecordWrittenEventArgs;
            EventRecord evtrec    = evtarg.EventRecord;
            string      xmlString = evtrec.ToXml();

            evtlog.SetProcData("EventData.XML", xmlString);
            evtlog.SetProcData("EventData.Description", evtrec.FormatDescription());

            // process event XML data
            var doc        = XDocument.Parse(xmlString);
            var namespaces = new XmlNamespaceManager(new NameTable());
            var ns         = doc.Root.GetDefaultNamespace();

            namespaces.AddNamespace("ns", ns.NamespaceName);

            foreach (var element in doc.XPathSelectElements("/ns:Event/ns:System/*", namespaces))
            {
                if (!string.IsNullOrWhiteSpace(element.Value))
                {
                    evtlog.SetProcData("EventSystem." + element.Name.LocalName, element.Value);
                }
                if (element.HasAttributes)
                {
                    foreach (var attribute in element.Attributes())
                    {
                        evtlog.SetProcData("EventSystem." + element.Name.LocalName + "." + attribute.Name, attribute.Value);
                    }
                }
            }

            int dataCnt = 0;

            foreach (var element in doc.XPathSelectElements("/ns:Event/ns:EventData/ns:Data", namespaces))
            {
                var name = element.Attribute("Name");
                if (name != null)
                {
                    evtlog.SetProcData("EventData." + name.Value, element.Value);
                }
                else
                {
                    evtlog.SetProcData("EventData[" + dataCnt + "]", element.Value);
                    dataCnt++;
                }
            }

            if (dataCnt > 0)
            {
                evtlog.SetProcData("EventData", dataCnt);
            }

            return(goto_next);
        }
        public void CanReadAndWriteMessages()
        {
            string messageDllPath       = Path.Combine(Path.GetDirectoryName(typeof(EventLog).Assembly.Location), "System.Diagnostics.EventLog.Messages.dll");
            EventSourceCreationData log = new EventSourceCreationData($"TestEventMessageSource {Guid.NewGuid()}", "Application")
            {
                MessageResourceFile = messageDllPath
            };

            try
            {
                if (EventLog.SourceExists(log.Source))
                {
                    EventLog.DeleteEventSource(log.Source);
                }

                EventLog.CreateEventSource(log);
                string message = $"Hello {Guid.NewGuid()}";
                Helpers.Retry(() => EventLog.WriteEntry(log.Source, message));

                using (EventLogReader reader = new EventLogReader(new EventLogQuery("Application", PathType.LogName, $"*[System/Provider/@Name=\"{log.Source}\"]")))
                {
                    EventRecord evt = reader.ReadEvent();

                    string logMessage = evt.FormatDescription();

                    Assert.Equal(message, logMessage);
                }
            }
            finally
            {
                EventLog.DeleteEventSource(log.Source);
            }
        }
Exemple #6
0
        /// <summary>
        /// Displays the event information and log information on the console for
        /// all the events returned from a query.
        /// </summary>
        private static void DisplayEventAndLogInformation(EventLogReader logReader)
        {
            for (EventRecord eventInstance = logReader.ReadEvent();
                 null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                if (eventInstance.Id == 14151)
                {
                    Console.WriteLine("-----------------------------------------------------");
                    Console.WriteLine("Event ID: {0}", eventInstance.Id);
                    Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                }

                try
                {
                    Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                }
                catch (EventLogException e)
                {
                    Console.WriteLine(e.Message);
                    // The event description contains parameters, and no parameters were
                    // passed to the FormatDescription method, so an exception is thrown.
                }

                // Cast the EventRecord object as an EventLogRecord object to
                // access the EventLogRecord class properties
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog);
            }
        }
Exemple #7
0
        static string GetEventDescription(EventRecord eventRecord)
        {
            string descr;

            try
            {
                descr = (eventRecord.FormatDescription() ?? "").Trim();
            }
            catch (EventLogException)
            {
                descr = "";
            }
            string keywords;

            try
            {
                keywords = string.Join(", ", eventRecord.KeywordsDisplayNames);
            }
            catch
            {
                keywords = "";
            }
            return(string.Format("{0}{1}Event {2} from {3}{4}{5}",
                                 descr, descr.Length > 0 ? ". " : "",
                                 eventRecord.Id,
                                 eventRecord.ProviderName,
                                 keywords.Length > 0 ? ", keywords=" : "", keywords));
        }
        public dynamic CreateDynamic(EventRecord record)
        {
            var obj = new ExpandoObject();
            IDictionary <string, object> underObject = obj;

            underObject["Source"]     = "WindowsEventLog";
            underObject["Devicename"] = record.MachineName.ToUpper();
            underObject["EventTime"]  = record.TimeCreated.Value.ToUniversalTime().ToString("o");
            underObject["EventId"]    = record.Id.ToString();
            underObject["Level"]      = record.Level.HasValue ? ((int)record.Level.Value).ToString() : string.Empty;
            underObject["User"]       = record.UserId != null?record.UserId.Translate(typeof(NTAccount)).ToString() : "N/A";

            underObject["ProviderName"] = record.ProviderName;

            // if SQL Audit Event
            if (record.Id == 33205)
            {
                var entries = record.FormatDescription().Replace("Audit event: ", "").Split(new[] { '\n' });
                foreach (var entry in entries)
                {
                    var colon = entry.IndexOf(':');
                    if (colon != -1)
                    {
                        underObject.Add(entry.Substring(0, colon), entry.Substring(colon + 1, entry.Length - colon - 1));
                    }
                }
            }
            else
            {
                underObject["Description"] = record.FormatDescription();
                var        root      = XElement.Parse(record.ToXml());
                XNamespace x         = "http://schemas.microsoft.com/win/2004/08/events/event";
                var        dataNodes = root.Descendants(x + "Data")
                                       .Where(e => e.HasAttributes && e.Attributes().Any(a => a.Name == "Name"));
                foreach (var node in dataNodes)
                {
                    var key = node.Attributes().First(a => a.Name == "Name").Value;
                    if (!underObject.ContainsKey(key))
                    {
                        underObject.Add(key, node.Value);
                    }
                }
            }

            return(underObject);
        }
        private log_entry_line to_log_entry(EventRecord rec, string log_name)
        {
            log_entry_line entry = new log_entry_line();

            try {
                entry.add("Log", log_name);
                entry.add("EventID", "" + rec.Id);

                entry.add("level", event_level((StandardEventLevel)rec.Level));
                entry.analyze_and_add("timestamp", rec.TimeCreated.Value);

                try {
                    var task = rec.Task != 0 ? rec.TaskDisplayName : "";
                    entry.add("Category", task ?? "");
                } catch {
                    entry.add("Category", "");
                }

                entry.add("Machine Name", rec.MachineName);
                entry.add("Source", "" + rec.ProviderName);
                string user_id = rec.UserId != null ? rec.UserId.Value : "";
                if (user_id != "")
                {
                    user_id = new SecurityIdentifier(user_id).Translate(typeof(NTAccount)).ToString();
                }
                ;
                entry.add("User Name", user_id);

                /* 1.5.14+ this generates waaaay too many errors - just ignore for now
                 * try {
                 *  var keywords = rec.KeywordsDisplayNames;
                 *  entry.add("Keywords", keywords != null ? util.concatenate(keywords, ",") : "");
                 * } catch {
                 *  entry.add("Keywords", "");
                 * }*/


                // note: this throws a lot of exceptions; however, we don't have much of a choice here - just showing the raw properties is rather useless
                try {
                    var desc = rec.FormatDescription();
                    if (desc == null)
                    {
                        desc = util.concatenate(rec.Properties.Select(x => x.Value.ToString()), "\r\n");
                    }
                    entry.add("msg", desc ?? "");
                } catch {
                    try {
                        string desc = util.concatenate(rec.Properties.Select(x => x.Value.ToString()), "\r\n");
                        entry.add("msg", desc);
                    } catch {
                        entry.add("msg", "");
                    }
                }
            } catch (Exception e) {
                logger.Fatal("can't convert EventRectord to entry " + e.Message);
            }
            return(entry);
        }
        private EventInfo CreateEventInfo(EventRecord eventData)
        {
            EventInfo result = new EventInfo
            {
                Computer             = eventData.MachineName,
                EventId              = eventData.Id,
                FormattedDescription = eventData.FormatDescription(),
                Logged  = eventData.TimeCreated ?? DateTime.MinValue,
                LogName = eventData.LogName,
                RawXML  = eventData.ToXml(),
                User    = eventData.UserId?.ToString() ?? "N/A"
            };

            try
            {
                result.Keywords = eventData.KeywordsDisplayNames.Cast <object>().ToArray().EnumElements(); // ((object[])eventData.KeywordsDisplayNames).EnumElements(),
            }
            catch
            {
                result.Keywords = eventData.Keywords?.ToString() ?? "";
            }
            try
            {
                result.Source = eventData.ProviderName;
            }
            catch
            {
                result.Source = "";
            }
            try
            {
                result.TaskCategory = eventData.TaskDisplayName;
            }
            catch
            {
                result.TaskCategory = "";
            }
            try
            {
                result.Level = eventData.LevelDisplayName;
            }
            catch
            {
                result.Level = GetDefaultLevelName(eventData.Level);
            }
            if (string.IsNullOrWhiteSpace(result.FormattedDescription))
            {
                result.FormattedDescription = "Event description was not found. \r\n\r\nThe following information was included with the event: \r\n";
                if (eventData.Properties != null)
                {
                    foreach (EventProperty prop in eventData.Properties)
                    {
                        result.FormattedDescription += $"{prop.Value?.ToString() ?? ""}\r\n";
                    }
                }
            }
            return(result);
        }
 public void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
 {
     if (arg.EventRecord != null)
     {
         EventRecord eventInstance      = arg.EventRecord;
         String      eventMessage       = eventInstance.FormatDescription(); // You can get event information from FormatDescription API itself.
         String      eventMessageXMLFmt = eventInstance.ToXml();             // Getting event information in xml format
     }
 }
Exemple #12
0
        static void Main(string[] args)
        {
            SystemLog systemlog = new SystemLog();

            ManagementObjectSearcher ComSerial = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");

            foreach (ManagementObject wmi in ComSerial.Get())
            {
                try
                {
                    systemlog.Serial_Number = wmi.GetPropertyValue("SerialNumber").ToString();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
            systemlog.Last_Updated = System.DateTime.Now.ToString();
            int    MonthsToSearch = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MonthsWindow"]);
            var    startTime      = System.DateTime.Now.AddMonths(MonthsToSearch);
            string query          = string.Format(@"*[System/Level=1 or System/Level=2] and *[System[TimeCreated[@SystemTime >= '{0}']]]",
                                                  startTime.ToUniversalTime().ToString("o"));


            MappingSection mappingSection = ConfigurationManager.GetSection("Mappings") as MappingSection;

            EventLogQuery eventsQuery = new EventLogQuery("System", PathType.LogName, query);

            try
            {
                EventLogReader logReader = new EventLogReader(eventsQuery);
                systemlog.Machine_Name = logReader.ReadEvent().MachineName;
                for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent())
                {
                    var mappings = mappingSection.ExclusionEvents.Cast <MappingElement>().Where(c => c.EventID.Equals(eventdetail.Id.ToString()) && c.Source.Equals(eventdetail.ProviderName));
                    if (mappings.Any())
                    {
                        continue;
                    }
                    SystemEventRecord systemeventrecord = new SystemEventRecord();
                    systemeventrecord.Level        = eventdetail.LevelDisplayName;
                    systemeventrecord.Source       = eventdetail.ProviderName;
                    systemeventrecord.Time_Created = eventdetail.TimeCreated.ToString();
                    systemeventrecord.EventId      = eventdetail.Id;
                    systemeventrecord.Message      = eventdetail.FormatDescription();
                    systemlog.Events.Add(systemeventrecord);
                }
            }
            catch (EventLogNotFoundException exception)
            {
                Console.WriteLine(exception.Message);
            }

            // serialize to json
            var jsonsytemlog = Newtonsoft.Json.JsonConvert.SerializeObject(systemlog);
        }
        static void Main(string[] args)
        {
            string[] queryString = new string[]
            {
                "*[System[(EventID=4624)] and EventData[Data[@Name=\"TargetUserName\"]=\"{0}\"]]",
                "*[System[(EventID=4624)] and EventData[Data[@Name=\"TargetDomainName\"]=\"{0}\"]]",
                "*[EventData[Data[@Name=\"IpAddress\"] and(Data=\"{0}\")]]"
            };
            string search = args[1];

            if (!Enum.IsDefined(typeof(Options), args[0]))
            {
                Console.WriteLine("Invalid Option: username, domain, ip");
                return;
            }
            Console.WriteLine("Searching for '{0}'", search);

            int index = (int)Enum.Parse(typeof(Options), args[0]);

            string query = String.Format(queryString[index], search);

            Console.WriteLine("Querying: {0}", query);
            foreach (DomainController target in Domain.GetCurrentDomain().DomainControllers)
            {
                try
                {
                    Console.WriteLine("Parsing {0} ({1}) logs", target.IPAddress, target.Name);
                    EventLogSession els = new EventLogSession(target.Name);

                    EventLogQuery logQuery = new EventLogQuery("Security", PathType.LogName, query);
                    logQuery.Session = els;

                    EventLogReader elr = new EventLogReader(logQuery);
                    while (true)
                    {
                        EventRecord er = elr.ReadEvent();

                        if (er == null)
                        {
                            break;
                        }
                        Console.WriteLine(er.FormatDescription() + "\r\n-----------------------------------\r\n");

                        if (er != null)
                        {
                            er.Dispose();
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                }
            }
        }
Exemple #14
0
        public void Poll(int Tick)
        {
            if (sample_rate <= 0 || Tick % sample_rate != 0)
            {
                return;
            }
            log.debug(1, "Polling event data " + path, 0);

            Stopwatch sw = new Stopwatch();

            sw.Start();
            this.Clear();

            string queryString =
                "<QueryList>" +
                "  <Query Id=\"0\" Path=\"" + path + "\">" +
                "    <Select Path=\"" + path + "\">" +
                "        *[System[(Level &lt;= " + event_level + ") and (Level != 0) and " +
                "        TimeCreated[timediff(@SystemTime) &lt;= " + (hours * 3600000) + "]]]" +
                "    </Select>" +
                "  </Query>" +
                "</QueryList>";

            log.debug(2, "QueryString=" + queryString, 0);
            EventLogQuery  eventsQuery = new EventLogQuery(path, PathType.FilePath, queryString);
            EventLogReader logReader   = new EventLogReader(eventsQuery);

            for (EventRecord e = logReader.ReadEvent(); e != null; e = logReader.ReadEvent())
            {
                EventItem temp;
                try
                {
                    temp = new EventItem(e.Id,
                                         e.FormatDescription(),
                                         e.LevelDisplayName,
                                         (int)e.Level,
                                         e.ProviderName,
                                         e.TimeCreated.ToString());
                }
                catch
                {
                    temp = new EventItem(e.Id,
                                         "Unable to get data",
                                         "Unable to get data",
                                         (int)e.Level,
                                         e.ProviderName,
                                         e.TimeCreated.ToString());
                }
                this.Add(temp);
            }
            sw.Stop();
            this.ticks = sw.ElapsedMilliseconds;
        }
Exemple #15
0
        private string FormatRawMessage(EventRecord eventRecord)
        {
            var builder = new StringBuilder();

            builder.Append(eventRecord.TimeCreated);
            builder.Append(' ');
            builder.Append(GetLevel(eventRecord));
            builder.Append(' ');
            builder.Append(eventRecord.FormatDescription());

            return(builder.ToString());
        }
        public void FormatDescription(string log)
        {
            if (PlatformDetection.IsWindows7) // Null events in PowerShell log
            {
                return;
            }
            var query = new EventLogQuery(log, PathType.LogName, "*[System]")
            {
                ReverseDirection = true
            };

            using (var eventLog = new EventLogReader(query, Helpers.GetBookmark(log, PathType.LogName)))
            {
                using (EventRecord record = eventLog.ReadEvent())
                {
                    Assert.IsType <EventLogRecord>(record);
                    string description = record.FormatDescription();
                    Assert.Equal(description, record.FormatDescription(null));
                    Assert.Equal(description, record.FormatDescription(new List <object>()));
                }
            }
        }
Exemple #17
0
        private static bool EventContains(EventRecord eventRecord, IList <string> contains)
        {
            string msg = eventRecord.FormatDescription();

            foreach (var ev in contains)
            {
                if (msg.IndexOf(ev, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
                {
                    return(true);
                }
            }
            return(false);
        }
Exemple #18
0
        private object[] DisplayEventAndLogInformation(EventLogReader logReader)
        {
            ArrayList eventlog_json_arraylist = new ArrayList();

            for (EventRecord eventInstance = logReader.ReadEvent();
                 null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                string eventlog_json = JsonConvert.SerializeObject(eventInstance);
                eventlog_json_arraylist.Add(eventlog_json);

                var    serializer = new YamlSerializer();
                String yaml       = serializer.Serialize(eventInstance);

                var serializer2 = new YamlDotNet.Serialization.Serializer();
                serializer2.Serialize(System.Console.Out, eventInstance);
                if (Verbose)
                {
                    Console.WriteLine("-----------------------------------------------------");
                    Console.WriteLine("Event ID: {0}", eventInstance.Id);
                    Console.WriteLine("Level: {0}", eventInstance.Level);
                    Console.WriteLine("LevelDisplayName: {0}", eventInstance.LevelDisplayName);
                    Console.WriteLine("Opcode: {0}", eventInstance.Opcode);
                    Console.WriteLine("OpcodeDisplayName: {0}", eventInstance.OpcodeDisplayName);
                    Console.WriteLine("TimeCreated: {0}", eventInstance.TimeCreated);
                    Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                }
                try
                {
                    if (Verbose)
                    {
                        Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                    }
                }
                catch (EventLogException)
                {
                    // The event description contains parameters, and no parameters were
                    // passed to the FormatDescription method, so an exception is thrown.
                }
                // Cast the EventRecord object as an EventLogRecord object to
                // access the EventLogRecord class properties
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                if (Verbose)
                {
                    Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog);
                }
            }
            object[] result = eventlog_json_arraylist.ToArray();
            return(result);
        }
        public void QueryEventLogWithParameterContent()
        {
            // EventLogQ
            String         query          = $@"Event[System/Provider/@Name=""{ESightEventSource}"" and EventData[Data[1] and Data=""User Action: parameter2""]]";
            EventLogQuery  eventlogQuery  = new EventLogQuery(ESightEventLogName, PathType.LogName, query);
            EventLogReader eventlogReader = new EventLogReader(eventlogQuery);

            // Loop through the events returned
            for (EventRecord eventRecord = eventlogReader.ReadEvent(); null != eventRecord; eventRecord = eventlogReader.ReadEvent())
            {
                // Get the description from the eventrecord.
                string message = eventRecord.FormatDescription();
                Trace.WriteLine(message);
                // Do something cool with it :)
            }
        }
Exemple #20
0
        internal static TraceTelemetry ToTrace(EventRecord @event)
        {
            var trace = new TraceTelemetry(@event.FormatDescription(), MapSeverity(@event.Level));

            trace.Timestamp = @event.TimeCreated.GetValueOrDefault(DateTime.UtcNow);
            trace.Context.Cloud.RoleInstance = @event.MachineName;
            trace.Context.Properties.Add("LogName", @event.LogName);
            trace.Context.Properties.Add("MachineName", @event.MachineName);
            trace.Context.Properties.Add("ProviderName", @event.ProviderName);
            trace.Context.Properties.Add("ActivityId", @event.ActivityId.GetValueOrDefault(Guid.Empty).ToString());
            trace.Context.Properties.Add("EventId", @event.Id.ToString());
            trace.Context.Properties.Add("KeywordsDisplayName", string.Join(", ", @event.KeywordsDisplayNames));
            trace.Context.Properties.Add("ProcessId", @event.ProcessId.GetValueOrDefault(0).ToString());
            trace.Context.Properties.Add("ProviderId", @event.ProviderId.ToString());

            return(trace);
        }
Exemple #21
0
 //----------------------------------------------------------------------------------------------
 /// <summary>コンストラクタ</summary>
 /// <param name="arg">イベントログレコード</param>
 public LogonRecord(EventRecord arg)
 {
     // ユーザIDをSIDからアカウント名に変換する
     try
     {
         NTAccount account = (NTAccount)arg.UserId.Translate(typeof(NTAccount));
         this.UserId = account.ToString();
     }
     catch (Exception e)
     {
         this.UserId = e.Message;
     }
     this.EventDatetime = (DateTime)arg.TimeCreated;
     this.MachineName   = arg.MachineName.ToString();
     this.ProviderName  = arg.ProviderName;
     this.Message       = arg.FormatDescription();
     this.EventId       = arg.Id;
 }
Exemple #22
0
        public EventItem(EventRecord eventRecord)
        {
            Record      = eventRecord;
            TimeOfEvent = eventRecord.TimeCreated ?? DateTime.MinValue;
            try
            {
                Message = eventRecord.FormatDescription();

                //TODO: Align to Event Viewer (e.g. Event ID 27 of e1dexpress)
                if (Message == null)
                {
                    Message = "(EventLook) The description for the event cannot be found.";
                }
            }
            catch (Exception ex)
            {
                Message = "(EventLook) Exception occurred while reading the description:\n" + ex.Message;
            }
        }
        public void QueryPowershellEventLog()
        {
            var LogName   = "Windows PowerShell";
            var LogSource = "PowerShell";
            // EventLogQ
            String         query          = $@"*[System/Provider/@Name=""{LogSource}""]";
            EventLogQuery  eventlogQuery  = new EventLogQuery(LogName, PathType.LogName, query);
            EventLogReader eventlogReader = new EventLogReader(eventlogQuery);

            Console.WriteLine(eventlogReader.BatchSize);
            // Loop through the events returned
            for (EventRecord eventRecord = eventlogReader.ReadEvent(); null != eventRecord; eventRecord = eventlogReader.ReadEvent())
            {
                // Get the description from the eventrecord.
                string message = eventRecord.FormatDescription();
                Trace.WriteLine(message);
                Console.WriteLine(message);
                // Do something cool with it :)
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: GetEventLog activityId machines");
                Console.WriteLine("Example: GetEventLog \"0724A8D0-D873-4CB3-8762-C9A70084DD98\" \"server1.company.com,server2.company.com\"");
                return;
            }

            string activityId   = args[0];
            string machineNames = args[1];

            string adfsAdminLogName = "AD FS 2.0/Admin";

            string[] machineNamesArray = machineNames.Split(new char[1] {
                ','
            });
            foreach (string machineName in machineNamesArray)
            {
                Console.WriteLine();
                Console.WriteLine("--------------------------------------------------------------------------------");
                Console.WriteLine("Getting AD FS event logs with correlation activity ID " + activityId + " from " + machineName);

                string        query         = "*[System/Correlation/@ActivityID=\"{" + activityId + "}\"]";
                EventLogQuery eventLogQuery = new EventLogQuery(adfsAdminLogName, PathType.LogName, query);
                eventLogQuery.Session = new EventLogSession(machineName);
                EventLogReader eventLogReader = new EventLogReader(eventLogQuery);

                for (EventRecord eventRecord = eventLogReader.ReadEvent(); eventRecord != null; eventRecord = eventLogReader.ReadEvent())
                {
                    //Console.WriteLine("eventRecord.ActivityId=" + eventRecord.ActivityId);
                    Console.WriteLine();
                    Console.WriteLine("--------------------------------------------------------------------------------");
                    Console.WriteLine("Event ID: " + eventRecord.Id);
                    Console.WriteLine("Logged: " + eventRecord.TimeCreated);
                    Console.WriteLine(eventRecord.FormatDescription());
                }
            }
        }
Exemple #25
0
        private void Append(EventRecord record)
        {
            if (_progressCount == 1)
            {
                Console.WriteLine("Total Lines = {0}\n", _counter);
            }

            if (_progressCount % 100 == 0)
            {
                Console.WriteLine("Progress Count = " + _progressCount);
            }

            Mapper.Initialize(cfg => cfg.CreateMap <EventRecord, EventLogModel>());
            var model = Mapper.Map <EventLogModel>(record);

            model.Description  = record.FormatDescription();
            model.Keywords     = GetKeyWords(record.KeywordsDisplayNames);
            model.TaskCategory = record.Task ?? 0;

            _returnValue.Add(model);
            _progressCount++;
        }
Exemple #26
0
        //this mettod is called after the Plugin is loaded
        public override void PluginLoaded()
        {
            eventId       = ConvertStringToInt(GetValueForKey("Event Id"));
            timeInMinutes = ConvertStringToInt(GetValueForKey("Time in minutes"));

            if (eventId != null && timeInMinutes != null)
            {
                var startTime = System.DateTime.Now.AddMinutes(-(int)timeInMinutes);
                var endTime   = System.DateTime.Now;

                var query = string.Format(@"*[System/EventID={0}] and *[System[TimeCreated[@SystemTime >= '{1}']]] and *[System[TimeCreated[@SystemTime <= '{2}']]]",
                                          eventId,
                                          startTime.ToUniversalTime().ToString("o"),
                                          endTime.ToUniversalTime().ToString("o"));
                EventLogQuery eventsQuery = new EventLogQuery("System", PathType.LogName, query);

                try
                {
                    EventLogReader logReader = new EventLogReader(eventsQuery);

                    for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent())
                    {
                        //Console.Write(eventdetail.ToString());
                        int    message = eventdetail.Id;
                        string texst   = eventdetail.FormatDescription();
                        string time    = eventdetail.TimeCreated.ToString();
                        //     Console.WriteLine("MY " + message + " " + texst+" "+time);
                        ComputerInfo localComputer = GetComputerInfo();

                        messageL = "The event " + eventId + " was logged on the computer " + localComputer.Name + " into the group " + localComputer.Group + "\n\n" + texst + " " + time;
                    }
                }
                catch (EventLogNotFoundException e)
                {
                    //  Console.WriteLine("Error while reading the event logs");
                    return;
                }
            }
        }
        private static EventInfo ConvertEventRecordToEventInfo(EventRecord record, bool includeEventData)
        {
            var eventInfo = new EventInfo()
            {
                EventId          = record.Id,
                LevelDisplayName = GetLevelDisplayName(record.Level), //The LevelDisplayName sometime get EventLogNotFoundException exception
                LogName          = record.LogName,
                MachineName      = record.MachineName,
                ProviderName     = record.ProviderName,
                TimeCreated      = Utility.ToUniversalTime(record.TimeCreated),
                Description      = record.FormatDescription(),
                Index            = record.RecordId,
                UserName         = record.UserId?.Value,
                Keywords         = GetKeywords(record.KeywordsDisplayNames),
            };

            if (includeEventData)
            {
                eventInfo.EventData = GetEventData(record.Properties);
            }

            return(eventInfo);
        }
        private static string CreateEventText(EventRecord record, ref int counter)
        {
            string task = !record.TaskDisplayName.IsEmpty() ? record.TaskDisplayName : "N/A";
            string user = record.UserId != null?record.UserId.ToString() : "N/A";

            string opcode = !record.OpcodeDisplayName.IsEmpty() ? record.OpcodeDisplayName : "N/A";
            string desc   = record.FormatDescription();

            string text = "Event[" + counter++ +
                          "]:\n  Log Name: " + record.LogName +
                          "\n  Source: " + record.ProviderName +
                          "\n  Date: " + record.TimeCreated +
                          "\n  Event ID: " + record.Id +
                          "\n  Task: " + task +
                          "\n  Level: " + record.LevelDisplayName +
                          "\n  Opcode: " + opcode +
                          "\n  Keyword: " + Arr.ToString(record.Keywords, ", ") +
                          "\n  User: "******"\n  User Name: " + user +
                          "\n  Computer: " + record.MachineName +
                          "\n  Description: " + desc + "\n\n";

            return(text);
        }
Exemple #29
0
    //---------------------------------------------------------------------------------------------
    /// <summary>追加のメッセージを編集する</summary>
    /// <param name="record">イベントログのレコード</param>
    /// <return>追加メッセージ文字列</return>
    protected string EditRenderingInfo(EventRecord record)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("\r\n");
        sb.Append("\t\t<RenderingInfo Culture='ja-JP'>\r\n");
        sb.Append("\t\t\t<Message>");
        sb.Append(record.FormatDescription());
        sb.Append("</Message>\r\n");
        sb.Append("\t\t\t<Level>");
        sb.Append(record.LevelDisplayName);
        sb.Append("</Level>\r\n");
        sb.Append("\t\t\t<Task>");
        sb.Append(record.TaskDisplayName);
        sb.Append("</Task>\r\n");
        sb.Append("\t\t\t<Opcode>");
        sb.Append(record.OpcodeDisplayName);
        sb.Append("</Opcode>\r\n");
        sb.Append("\t\t\t<Channel>Microsoft-Windows-User Profile Service/Operational</Channel>\r\n");
        sb.Append("\t\t\t<Provider>Microsoft-Windows-User Profile Service</Provider>\r\n");
        sb.Append("\t\t\t<Keywords></Keywords>\r\n");
        sb.Append("\t\t</RenderingInfo>\r\n");
        return(sb.ToString());
    }
Exemple #30
0
        private static string SerializeEventRecord(EventRecord e)
        {
            string logstashEvent = string.Empty;

            using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
                using (JsonTextWriter writer = new JsonTextWriter(sw))
                {
                    writer.WriteStartObject();
                    AddEventProperty(writer, "@version", 1);
                    string normalisedDate = ((DateTime)e.TimeCreated).ToString("o", CultureInfo.InvariantCulture);

                    AddEventProperty(writer, "@timestamp", normalisedDate);
                    AddEventProperty(writer, "type", "eventlog");
                    try
                    {
                        AddEventProperty(writer, "SourceName", e.ProviderName);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "EventIdentifier", e.Id);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "ComputerName", e.MachineName);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "@message", e.FormatDescription());
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "TaskName", e.TaskDisplayName);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "host", Environment.MachineName);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "path", e.LogName);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "LogFile", e.LogName);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "SourceIdentifier", e.ProviderId);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "Type", System.Enum.GetName(typeof(StandardEventLevel), e.Level));
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "EventType", e.Level);
                    }
                    catch {}
                    try
                    {
                        if (!IsNull(e.UserId))
                        {
                            AddEventProperty(writer, "User", ResolveSIDtoUsername(e.UserId.Value));
                        }
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "RecordNumber", e.RecordId);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "ActivityIdentifier", e.ActivityId);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "RelatedActivityIdentifier", e.RelatedActivityId);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "Opcode", e.Opcode);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "OpcodeName", e.OpcodeDisplayName);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "pid", e.ProcessId);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "ThreadId", e.ThreadId);
                    }
                    catch {}
                    try
                    {
                        SerializeEventProperties(writer, e.Properties);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "Qualifiers", e.Qualifiers);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "Task", e.Task);
                    }
                    catch {}
                    try
                    {
                        AddEventProperty(writer, "EventVersion", e.Version);
                    }
                    catch {}

                    writer.WriteEndObject();
                    logstashEvent = sw.ToString();
                }

            return(logstashEvent);
        }