Exemple #1
0
        WindowsDefenderDetail GetDetail(string queryString)
        {
            var query = new EventLogQuery("Microsoft-Windows-Windows Defender/Operational", PathType.LogName, queryString);

            using (var reader = new EventLogReader(query))
            {
                EventRecord eventInstance = reader.ReadEvent();
                try
                {
                    while (eventInstance != null)
                    {
                        var instance = reader.ReadEvent();
                        if (instance == null)
                        {
                            break;
                        }
                        eventInstance = instance;
                    }

                    return(ParseData(eventInstance));
                }
                finally
                {
                    if (eventInstance != null)
                    {
                        eventInstance.Dispose();
                    }
                }
            }
        }
Exemple #2
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);
            }
        }
        /// <summary>
        /// Gets the timestamp from the last reboot prior to encryption
        /// of the first file from the Windows Event Log
        /// </summary>
        /// <param name="firstEncryptedFile"></param>
        /// <returns></returns>
        public static DateTime getLastReboot(DateTime firstEncryptedFile)
        {
            string eventID   = "6005"; // “The event log service was started.” This is synonymous to system startup.
            string LogSource = "System";
            string sQuery    = $"*[System/EventID={eventID}]";

            var                elQuery    = new EventLogQuery(LogSource, PathType.LogName, sQuery);
            var                elReader   = new EventLogReader(elQuery);
            DateTime           lastReboot = default(DateTime);
            List <EventRecord> eventList  = new List <EventRecord>();

            for (EventRecord eventInstance = elReader.ReadEvent();
                 null != eventInstance; eventInstance = elReader.ReadEvent())
            {
                DateTime thisReboot = (DateTime)eventInstance.TimeCreated;

                //Make sure we get timestamp of the last reboot prior to the ransomware attack
                if (lastReboot < thisReboot && thisReboot < firstEncryptedFile)
                {
                    lastReboot = thisReboot;
                }
            }

            if (lastReboot == default(DateTime))
            {
                Console.Write("[-] Unable to retrieve last boot time from Windows Event Log. This will severely impact password crack time.");
            }

            return(lastReboot);
        }
Exemple #4
0
        private void check_log(string name)
        {
            try {
                SecureString pwd = new SecureString();
                foreach (char c in remote_passw_)
                {
                    pwd.AppendChar(c);
                }
                EventLogSession session = remote_machine_name_ != "" ? new EventLogSession(remote_machine_name_, remote_domain_, remote_username_, pwd, SessionAuthentication.Default) : null;
                pwd.Dispose();
                string        query_string = "*";
                EventLogQuery query        = new EventLogQuery(name, PathType.LogName, query_string);

                using (EventLogReader reader = new EventLogReader(query))
                    for (EventRecord rec = reader.ReadEvent(); rec != null; rec = reader.ReadEvent())
                    {
                        lock (this)
                            --log_names_[name];
                    }
            } catch (Exception e) {
                logger.Error("error checking log " + name + " on " + remote_machine_name_ + " : " + e.Message);
            }

            // mark log as fully read
            lock (this) {
                log_names_[name] = -log_names_[name];
                if (log_names_[name] == 0)
                {
                    // convention - 0 entries
                    log_names_[name] = int.MinValue;
                }
            }
        }
        public GatherResult GatherLogs()
        {
            var logEntries = new List <dynamic>();

            var      logQuery         = string.Format(WindowsLogQuery, LastLogEntrySent.ToString("o"));
            var      eventQuery       = new EventLogQuery("Application", PathType.LogName, logQuery);
            var      eventReader      = new EventLogReader(eventQuery);
            var      record           = eventReader.ReadEvent();
            DateTime?lastLogEntryTime = null;

            while (record != null)
            {
                if (record.TimeCreated.HasValue && record.TimeCreated.Value.ToUniversalTime() > LastLogEntrySent)
                {
                    lastLogEntryTime = record.TimeCreated.Value.ToUniversalTime();
                }
                logEntries.Add(CreateDynamic(record));
                record = eventReader.ReadEvent();
            }

            return(new GatherResult
            {
                Logs = logEntries,
                LastLogEntryTime = lastLogEntryTime
            });
        }
Exemple #6
0
        private void DisplayEventAndLogInformation(EventLogReader logreader)

        {
            DataSet ds = new DataSet();


            ds.Tables.Add("Events");
            ds.Tables["Events"].Columns.Add("EventID");
            ds.Tables["Events"].Columns.Add("Level");


            ds.Tables["Events"].Columns.Add("Time");

            ds.Tables["Events"].Columns.Add("Task");

            ds.Tables["Events"].Columns.Add("Operation");
            ds.Tables["Events"].Columns.Add("XML");



            for (EventRecord eventInstance = logreader.ReadEvent();

                 null != eventInstance; eventInstance = logreader.ReadEvent())

            {
                ds.Tables["Events"].Rows.Add(eventInstance.Id, eventInstance.LevelDisplayName, eventInstance.TimeCreated, eventInstance.TaskDisplayName, eventInstance.OpcodeDisplayName, eventInstance.ToXml());
            }



            data = ds;
        }
        public void GetPropertyValues_MatchProviderIdUsingProviderMetadata_Success()
        {
            Dictionary <string, Guid> providerNameAndIds = new Dictionary <string, Guid>();

            string logName     = "Application";
            string queryString = "*[System/Level=4]";
            var    xPathEnum   = new List <string>()
            {
                "Event/System/EventID", "Event/System/Provider/@Name"
            };
            var logPropertyContext = new EventLogPropertySelector(xPathEnum);
            var eventsQuery        = new EventLogQuery(logName, PathType.LogName, queryString);

            try
            {
                using (var logReader = new EventLogReader(eventsQuery))
                {
                    for (EventLogRecord eventRecord = (EventLogRecord)logReader.ReadEvent();
                         eventRecord != null;
                         eventRecord = (EventLogRecord)logReader.ReadEvent())
                    {
                        IList <object> logEventProps;
                        logEventProps = eventRecord.GetPropertyValues(logPropertyContext);
                        int eventId;
                        Assert.True(int.TryParse(string.Format("{0}", logEventProps[0]), out eventId));
                        string providerName = (string)logEventProps[1];
                        if (!providerNameAndIds.ContainsKey(providerName) && eventRecord.ProviderId.HasValue)
                        {
                            providerNameAndIds.Add(providerName, eventRecord.ProviderId.Value);
                        }
                    }
                }
            }
            catch (EventLogNotFoundException) { }

            if (providerNameAndIds.Count > 0)
            {
                using (var session = new EventLogSession())
                {
                    foreach (var nameAndId in providerNameAndIds)
                    {
                        ProviderMetadata providerMetadata = null;
                        try
                        {
                            providerMetadata = new ProviderMetadata(nameAndId.Key);
                            Assert.Equal(providerMetadata.Id, nameAndId.Value);
                        }
                        catch (EventLogException)
                        {
                            continue;
                        }
                        finally
                        {
                            providerMetadata?.Dispose();
                        }
                    }
                }
            }
        }
    public static String getDiagnosticsLogForEvents(int startId, int endId)
    {
        String   queryString = "*"; // XPATH Query
        String   logName     = "Microsoft-Windows-Diagnostics-Performance/Operational";
        PathType pathType    = PathType.LogName;

        StringBuilder sb          = new StringBuilder();
        EventLogQuery eventsQuery = new EventLogQuery(logName, pathType, queryString);

        sb.AppendLine(logName);
        sb.AppendLine("ID=" + startId + "-" + endId);


        try {
            EventLogReader logReader = new EventLogReader(eventsQuery);
            int            count     = 0;
            EventLogRecord elr;
            for (EventRecord er = logReader.ReadEvent();
                 er != null; er = logReader.ReadEvent())
            {
                if (er.Id < startId || er.Id > endId)
                {
                    continue;
                }
                count++;
                // Needs to be cast to get to FormatDescription
                elr = (EventLogRecord)er;
                sb.AppendLine(SEPARATOR_LINE);
                // This outputs the description formatted with the event values
                sb.AppendLine(elr.FormatDescription());
#if false
                IEnumerable <String> keywordDisplayNames = er.KeywordsDisplayNames;
                sb.AppendLine("Keyword Display Names");
                foreach (String name in keywordDisplayNames)
                {
                    sb.AppendLine("  " + name);
                }

                IList <EventProperty> eventProperties = er.Properties;
                sb.AppendLine("Event Properties");
                foreach (EventProperty prop in eventProperties)
                {
                    sb.AppendLine("  " + prop.Value);
                }
                sb.AppendLine("XML: " + er.ToXml());
#endif
            }
            sb.AppendLine(SEPARATOR_LINE);
            sb.AppendLine(LF + "Events found : " + count);
        } catch (EventLogNotFoundException ex) {
            Console.WriteLine(excMsgLocal("Could not find the " + logName + "log", ex));
            return(null);
        } catch (Exception ex) {
            Console.WriteLine(excMsgLocal("Error in getBootTimes", ex));
            return(null);
        }

        return(sb.ToString());
    }
Exemple #9
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 #10
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);
        }
Exemple #11
0
        private void GatherBootUpTimeEtc()
        {
            LastBootUpTime = "";
            LastLoginTime  = "";

            try
            {
                var q1 = "*[System/Provider/@Name='Microsoft-Windows-Kernel-Boot' and System/EventID=27]";
                var d1 = LastEventDateTime(q1);
                LastBootUpTime = $"{SafeDate.ToLongDate(d1.ToUniversalTime())}";

                var q2 = "*[System/Provider/@Name='Microsoft-Windows-Winlogon' and System/EventID=7001]";
                var d2 = LastEventDateTime(q2);
                LastLoginTime = $"{SafeDate.ToLongDate(d2.ToUniversalTime())}";
            }
            catch
            {
                // Do Nothing
            }

            // Local Function
            DateTime LastEventDateTime(string query)
            {
                DateTime result = DateTime.MinValue;

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

                using (var elReader = new EventLogReader(eventLogQuery))
                {
                    EventRecord eventInstance = elReader.ReadEvent();
                    while (eventInstance != null)
                    {
                        if (eventInstance.TimeCreated.HasValue)
                        {
                            var thisTime = eventInstance.TimeCreated.Value.ToUniversalTime();
                            if (thisTime > result)
                            {
                                result = thisTime;
                            }
                            else
                            {
                                Debugger.Break();
                            }
                        }

                        eventInstance = elReader.ReadEvent();
                    }
                }

                if (result == DateTime.MinValue)
                {
                    result = DateTime.UtcNow;
                }
                return(result);
            }
        }
Exemple #12
0
        public override async Task ScanEventLogsAsync()
        {
            ScanCompleted.Value = false;
            BlackoutDates.Clear();
            var      oldest   = DateTime.Today - TimeSpan.FromDays(PreferenceService.Preference.MaxDays);
            DateTime?lastDate = oldest - TimeSpan.FromDays(30);     // To easy recognission of oldest date

            ScannedDate.Value = oldest;
            AllPowerLogs.Clear();
            long maxTimeDiff = PreferenceService.Preference.MaxDays * 86400000L;
            var  queryStr    = "<QueryList><Query Id=\"0\" Path=\"System\">"
                               + "<Select Path =\"System\">"
                               + "*[System[Provider[@Name = 'Microsoft-Windows-Kernel-Boot'"
                               + " or @Name = 'Microsoft-Windows-Kernel-General'"
                               + " or @Name = 'Microsoft-Windows-Kernel-Power'"
                               + " or @Name = 'EventLog'] "
                               + " and TimeCreated[timediff(@SystemTime) &lt;= " + $"{maxTimeDiff}"
                               + "]]] </Select></Query></QueryList>";
            var            query  = new EventLogQuery("System", PathType.LogName, queryStr);
            EventLogReader reader = new EventLogReader(query);
            EventRecord    record = reader.ReadEvent();

            while (record != null && !ScanCompleted.Value)
            {
                PowerLogEntry pwle = ToPowerLogEntry(record);
                if (pwle != null)
                {
                    AllPowerLogs.Add(pwle);
                    if (lastDate != pwle.Timestamp.Date)
                    {
                        UpdateBlackoutDateRange(lastDate, pwle.Timestamp.Date);
                        ScannedDate.Value = lastDate = pwle.Timestamp.Date;
                        await Task.Yield();
                    }
                }
                record = reader.ReadEvent();
            }
            Logger.Debug("AllPowerLogs.Count = {0}", AllPowerLogs.Count);
            if (AllPowerLogs.Count > 0)
            {
                UpdateBlackoutDateRange(lastDate, DateTime.Today + TimeSpan.FromDays(1));
                if (!ScanCompleted.Value)   // not aborted
                {
                    ScannedDate.Value = AllPowerLogs[AllPowerLogs.Count - 1].Timestamp.Date;
                }
            }
            else
            {
                UpdateBlackoutDateRange(lastDate, DateTime.Today + TimeSpan.FromDays(1));
            }
            BlackoutDateArray   = BlackoutDates.ToArray();
            ScanCompleted.Value = true;
            Logger.Debug("Scan completed");
        }
Exemple #13
0
        static IEnumerable <SecurityLog> GetData()
        {
            var reader = new EventLogReader(new EventLogQuery("Security", PathType.LogName));

            for (var evt = reader.ReadEvent(); evt != null; evt = reader.ReadEvent())
            {
                var rec = evt as EventLogRecord;
                yield return(new SecurityLog(rec));
            }
            SecurityLog.ClearCache();
        }
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 GetEvents(DateTime startTime, DateTime endTime, Boolean lastEventOnly = false)
        {
            StringBuilder events = new StringBuilder();

            try
            {
                String query = "<QueryList>"
                               + "<Query Id=\"0\" Path=\"Application\">"
                               + "<Select Path=\"Application\">*[System[Provider[@Name='.NET Runtime'] and (EventID=1026) "
                               + " and TimeCreated[@SystemTime&gt;='"
                               + XmlConvert.ToString(startTime, XmlDateTimeSerializationMode.Utc)
                               + "' and @SystemTime&lt;='"
                               + XmlConvert.ToString(endTime, XmlDateTimeSerializationMode.Utc)
                               + "']"
                               + "]]</Select>"
                               + "</Query>"
                               + "</QueryList>";

                EventLogQuery eventLogQuery = new EventLogQuery("Application", PathType.LogName, query);

                if (lastEventOnly)
                {
                    eventLogQuery.ReverseDirection = true;
                }

                using (EventLogReader logReader = new EventLogReader(eventLogQuery))
                {
                    if (lastEventOnly)
                    {
                        EventRecord eventLogEntry = logReader.ReadEvent();
                        WriteCrashReport(events, eventLogEntry);
                    }
                    else
                    {
                        for (EventRecord eventLogEntry = logReader.ReadEvent();
                             eventLogEntry != null;
                             eventLogEntry = logReader.ReadEvent())
                        {
                            WriteCrashReport(events, eventLogEntry);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                events.Append("Error Reading from EventLog. Message:" + ex.Message + " " + ex.StackTrace);
            }

            return(events.ToString());
        }
            private IDataReader ExecureEventLogReader()
            {
                EventLogQuery eventLogQuery = new EventLogQuery(
                    null,
                    PathType.LogName,
                    this._eventLogQuery.TrimmedOrEmpty()
                    );

                EventLogSession session = new EventLogSession(this._eventLogConnection.MachineName);

                eventLogQuery.Session = session;

                EventLogReader eventLogReader = new EventLogReader(eventLogQuery);

                Dictionary <string, string> mappings = _mappings.Count > 0
                                        ? new Dictionary <string, string>(_mappings)
                                        : new Dictionary <string, string>(DefaultMappings);

                DataTable dt = new DataTable();

                foreach (KeyValuePair <string, string> mapping in mappings)
                {
                    dt.Columns.Add(mapping.Key, typeof(string));
                }

                EventRecord eventInstance = eventLogReader.ReadEvent();

                while (eventInstance != null)
                {
                    XmlDocument    eventDoc  = RemoveXmlns(eventInstance.ToXml());
                    XPathNavigator navigator = eventDoc.CreateNavigator();
                    DataRow        row       = dt.NewRow();

                    foreach (KeyValuePair <string, string> mapping in mappings)
                    {
                        string         column = mapping.Key;
                        string         xpath  = mapping.Value;
                        XPathNavigator node   = navigator.SelectSingleNode(xpath);

                        row[column] = node == null || node.Value == null
                                                        ? string.Empty
                                                        : node.Value;
                    }

                    dt.Rows.Add(row);
                    eventInstance = eventLogReader.ReadEvent();
                }

                return(dt.CreateDataReader());
            }
Exemple #17
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 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);
            }
        }
        /// <summary>
        /// Pulls out the PowerShell events from the event log
        /// </summary>
        /// <returns>PSEventEntry object with the latest event properties</returns>
        private PSEventEntry getPSEvent()
        {
            // event id 40962 and 4104

            string logType = "Microsoft-Windows-PowerShell/Operational";
            string query   = $"*[System[(EventID='4104' or EventID='40962') and TimeCreated[timediff(@SystemTime) <= {timespan}]]]";

            var elQuery  = new EventLogQuery(logType, PathType.LogName, query);
            var elReader = new EventLogReader(elQuery);

            for (EventRecord eventInstance = elReader.ReadEvent(); eventInstance != null; eventInstance = elReader.ReadEvent())
            {
                // add data to the object
                entry.username  = new SecurityIdentifier(eventInstance.UserId.Value).Translate(typeof(NTAccount)).ToString();
                entry.datetime  = (DateTime)eventInstance.TimeCreated;
                entry.processID = (int)eventInstance.ProcessId;

                if (eventInstance.TaskDisplayName.ToLower().Contains("block") || eventInstance.TaskDisplayName.ToLower().Contains("suspicious"))
                {
                    entry.malware = true;
                }
                if (eventInstance.TaskDisplayName.ToLower().Contains("execute"))
                {
                    entry.runcount = entry.runcount + 1;
                }
                if (eventInstance.TaskDisplayName.ToLower().Contains("console startup"))
                {
                    entry.opencommand = true;
                }
            }
            return(entry);
        }
Exemple #20
0
        /// <summary>
        ///Executes the log command
        /// </summary>
        /// <param string[]="args"></param>
        /// <param out bool="result"></param>
        /// <return the log ></return>
        public string Execute(string[] args, out bool result)
        {
            EventLog[] eventLogs = EventLog.GetEventLogs();

            EventLogQuery  query  = new EventLogQuery("ImageServiceLog", PathType.LogName, "*");
            EventLogReader reader = new EventLogReader(query);

            EventRecord eventRecord;

            IList <string> logs = new List <string>();

            string output = "";
            int    i      = 0;

            while ((eventRecord = reader.ReadEvent()) != null)
            {
                logs.Add(eventRecord.Id + "," + eventRecord.FormatDescription() + "*");
            }
            for (int j = logs.Count - 1; j > 0; j--)
            {
                if (logs.ElementAt(j).Contains("SERVICE_RUNNING"))
                {
                    output += logs[j];
                    break;
                }
                output += logs[j];
            }


            result = true;
            return(output);
        }
Exemple #21
0
            public static DataTable SearchEventLogsForLockouts(string[] DomainControllers, DateTime LastScan)
            {
                DataTable table = new DataTable(); //Build a table to house the results

                table.Columns.Add("Date", typeof(DateTime));
                table.Columns.Add("User");
                table.Columns.Add("Machine");
                table.Columns.Add("DC");

                foreach (string dc in DomainControllers)
                {
                    EventLogQuery   eventsQuery = new EventLogQuery("Security", PathType.LogName, "*[System/EventID=4740]"); //Create an eventlog query to find 4740 events in the security log
                    EventLogSession session     = new EventLogSession(dc);                                                   //Create an eventlog session on the target machine
                    eventsQuery.Session = session;                                                                           //Invoke the session

                    try
                    {
                        EventLogReader logReader = new EventLogReader(eventsQuery);                                                                                 //start the eventlog reader

                        for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent())                             //foreach the results of the reader
                        {
                            if (eventdetail.TimeCreated > LastScan)                                                                                                 //find entries newer than the date specified
                            {
                                table.Rows.Add(eventdetail.TimeCreated, eventdetail.Properties[0].Value, eventdetail.Properties[1].Value, eventdetail.MachineName); //add the specific columns to the table
                            }
                        }
                    }
                    catch { }
                }
                return(table); //return the table
            }
Exemple #22
0
        // get events since <Timestamp>, to be used for the first iteration of SendDataLoop
        private List <EventRecord> MessagesSinceTime(string Timestamp, string LogSource)
        {
            string sQuery = $"*[System[TimeCreated[@SystemTime>='{Timestamp}']]]";

            var elQuery  = new EventLogQuery(LogSource, PathType.LogName, sQuery);
            var elReader = new EventLogReader(elQuery);
            List <EventRecord> records = new List <EventRecord>();

            for (EventRecord eventInstance = elReader.ReadEvent();
                 null != eventInstance; eventInstance = elReader.ReadEvent())
            {
                records.Add(eventInstance);
            }

            return(records);
        }
        private static bool remote_event_log_exists(string log, string remote_machine_name, string remote_domain_name, string remote_user_name, string remote_password_name)
        {
            try {
                SecureString pwd = new SecureString();
                foreach (char c in remote_password_name)
                {
                    pwd.AppendChar(c);
                }
                EventLogSession session = remote_machine_name.Trim() != ""
                    ? new EventLogSession(remote_machine_name, remote_domain_name, remote_user_name, pwd, SessionAuthentication.Default)
                    : null;
                pwd.Dispose();
                EventLogQuery query = new EventLogQuery(log, PathType.LogName);
                if (session != null)
                {
                    query.Session = session;
                }

                EventLogReader reader = new EventLogReader(query);
                if (reader.ReadEvent(TimeSpan.FromMilliseconds(500)) != null)
                {
                    return(true);
                }
            } catch (Exception e) {
                logger.Error("can't login " + e.Message);
            }
            return(false);
        }
Exemple #24
0
        private void ParseLogs(List <string> eventLogNames)
        {
            foreach (string eventLogName in eventLogNames)
            {
                using (StreamWriter outputFile = new StreamWriter(this.outputFilename, true))
                    using (EventLogReader reader = new EventLogReader(eventLogName, PathType.FilePath))
                    {
                        EventRecord record;
                        while ((record = reader.ReadEvent()) != null)
                        {
                            using (record)
                            {
                                if (record.Id == 4624)
                                {
                                    XmlDocument xmlRecord = new XmlDocument();
                                    xmlRecord.LoadXml(record.ToXml());
                                    string targetUserName = xmlRecord.ChildNodes[0].ChildNodes[1].ChildNodes[5].InnerText;

                                    if (targetUserName == usernameToFind)
                                    {
                                        outputFile.WriteLine("{0},{1},{2}", record.TimeCreated,
                                                             targetUserName,
                                                             xmlRecord.ChildNodes[0].ChildNodes[1].ChildNodes[18].InnerText);
                                    }
                                }
                            }
                        }
                    }

                File.Delete(eventLogName);
            }
        }
Exemple #25
0
        // get events newer than <RecordId>, for all other iterations of SendDataLoop
        private List <EventRecord> MessagesSinceRecordId(long?RecordId, string LogSource)
        {
            string sQuery = $"*[System[EventRecordID>'{RecordId}']]";

            var elQuery  = new EventLogQuery(LogSource, PathType.LogName, sQuery);
            var elReader = new EventLogReader(elQuery);
            List <EventRecord> records = new List <EventRecord>();

            for (EventRecord eventInstance = elReader.ReadEvent();
                 null != eventInstance; eventInstance = elReader.ReadEvent())
            {
                records.Add(eventInstance);
            }

            return(records);
        }
Exemple #26
0
        public void TestRawEventRecordEnvelope_GivenJsonFormat_FallsBackToEventRecordEnvelopeBehavior()
        {
            using (var eventReader = new EventLogReader("Application", PathType.LogName))
            {
                EventLog.WriteEntry(LogSource, "Test message", EventLogEntryType.Information, 0);
                EventRecord eventRecord = null;
                do
                {
                    System.Threading.Thread.Sleep(100);
                    eventRecord = eventReader.ReadEvent();
                } while (eventRecord == null);

                var envelope = new RawEventRecordEnvelope(eventRecord, true, 0);
                var jsonStr  = envelope.GetMessage("json");
                var jsonObj  = JObject.Parse(jsonStr);
                Assert.NotNull(jsonObj);
                Assert.NotNull(jsonObj["EventId"]);
                Assert.NotNull(jsonObj["LevelDisplayName"]);
                Assert.NotNull(jsonObj["LogName"]);
                Assert.NotNull(jsonObj["MachineName"]);
                Assert.NotNull(jsonObj["ProviderName"]);
                Assert.NotNull(jsonObj["TimeCreated"]);
                Assert.NotNull(jsonObj["Description"]);
                Assert.NotNull(jsonObj["Index"]);
                Assert.NotNull(jsonObj["UserName"]);
                Assert.NotNull(jsonObj["Keywords"]);
            }
        }
Exemple #27
0
        public void TestRenderedXmlFormatRawRecordEnvelope()
        {
            using (var eventReader = new EventLogReader("Application", PathType.LogName))
            {
                EventLog.WriteEntry(LogSource, "Test message", EventLogEntryType.Information, 0);
                EventRecord eventRecord = null;
                do
                {
                    System.Threading.Thread.Sleep(100);
                    eventRecord = eventReader.ReadEvent();
                } while (eventRecord == null);

                var envelop       = new RawEventRecordEnvelope(eventRecord, true, 0);
                var renderedXml   = envelop.GetMessage("RenderedXml");
                var xml           = XElement.Parse(renderedXml);
                var renderingInfo = xml.Element(xml.Name.Namespace + "RenderingInfo");
                Assert.NotNull(renderingInfo);
                Assert.NotNull(renderingInfo.Element(xml.Name.Namespace + "Message"));
                Assert.NotNull(renderingInfo.Element(xml.Name.Namespace + "Level"));
                Assert.NotNull(renderingInfo.Element(xml.Name.Namespace + "Task"));
                Assert.NotNull(renderingInfo.Element(xml.Name.Namespace + "Opcode"));
                Assert.NotNull(renderingInfo.Element(xml.Name.Namespace + "Channel"));
                Assert.NotNull(renderingInfo.Element(xml.Name.Namespace + "Provider"));
                Assert.NotNull(renderingInfo.Element(xml.Name.Namespace + "Keywords"));
            }
        }
Exemple #28
0
        static CheckInfo checkTimeModification()
        {
            EventRecord    entry;
            string         logPath     = @"C:\Windows\System32\winevt\Logs\Security.evtx";
            EventLogReader logReader   = new EventLogReader(logPath, PathType.FilePath);
            DateTime       pcStartTime = startTime();

            while ((entry = logReader.ReadEvent()) != null)
            {
                if (entry.Id != 4616)
                {
                    continue;
                }
                if (entry.TimeCreated <= pcStartTime)
                {
                    continue;
                }

                IList <EventProperty> properties = entry.Properties;
                DateTime previousTime            = DateTime.Parse(properties[4].Value.ToString());
                DateTime newTime = DateTime.Parse(properties[5].Value.ToString());

                if (Math.Abs((previousTime - newTime).TotalMinutes) > 5)
                {
                    return(new CheckInfo(true, previousTime, newTime, entry.TimeCreated, entry.RecordId));
                }
            }
            return(new CheckInfo(false));
        }
        public void ExceptionOnce()
        {
            if (PlatformDetection.IsWindows7) // Null events in PowerShell log
            {
                return;
            }
            var query = new EventLogQuery("Application", PathType.LogName, "*[System]")
            {
                ReverseDirection = true
            };
            var    eventLog = new EventLogReader(query, Helpers.GetBookmark("Application", PathType.LogName));
            string levelDisplayName = null, opcodeDisplayName = null, taskDisplayName = null;

            using (eventLog)
            {
                using (var record = (EventLogRecord)eventLog.ReadEvent())
                {
                    ThrowsMaxOnce <EventLogNotFoundException>(() => levelDisplayName  = record.LevelDisplayName);
                    ThrowsMaxOnce <EventLogNotFoundException>(() => opcodeDisplayName = record.OpcodeDisplayName);
                    ThrowsMaxOnce <EventLogNotFoundException>(() => taskDisplayName   = record.TaskDisplayName);
                    Assert.Equal(levelDisplayName, record.LevelDisplayName);
                    Assert.Equal(opcodeDisplayName, record.OpcodeDisplayName);
                    Assert.Equal(taskDisplayName, record.TaskDisplayName);
                }
            }
        }
Exemple #30
0
        /// <summary>
        /// Get entries that match the LogReader query parmaters from an unwatched log
        /// </summary>
        /// <returns></returns>
        public void ReadLog(Dictionary <string, Query> result, CancellationTokenSource ct = null)
        {
            EventLogReader logReader = new EventLogReader(elq);
            EventRecord    entry     = logReader.ReadEvent();

            while (entry != null)
            {
                if (ct != null && ct.Token.IsCancellationRequested)
                {
                    break;
                }

                ParseEventRecord(entry, result);
                entry = logReader.ReadEvent();
            }
        }