示例#1
0
        /// <summary>
        /// Reads log file located a given path and returns a list of the events
        /// </summary>
        /// <param name="pathToLog">String containing the file path to the log</param>
        /// <returns>List of events</returns>
        private List <LogEvent> ReadLogFromFile(string pathToLog)
        {
            List <LogEvent> logEntries = new List <LogEvent>();

            using (var reader = new EventLogReader(pathToLog, PathType.FilePath))
            {
                EventRecord record;
                while ((record = reader.ReadEvent()) != null)
                {
                    try
                    {
                        //add the records as a logentry so that the description etc. gets loaded
                        logEntries.Add(record);
                    }
                    finally
                    {
                        if (logEntries.Count == 0)
                        {
                            throw new FileNotFoundException("Unable to parse any events from the specified file.");
                        }
                    }
                }
            }
            return(logEntries);
        }
示例#2
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;
                }
            }
        }
示例#3
0
        private static IEnumerable <EventLogRecord> ReadFile(string logFile, bool reduceReaderBatchSize = false)
        {
            long eventCount = 0; // for debugging

            using (var reader = new EventLogReader(logFile, PathType.FilePath))
            {
                // There is an acceptable limit to the event size.
                // Per batch, by default, the reader reads 64 events.
                // If event size > acceptable limit,
                // the reader throws "Array bounds are invalid".
                // To fix this, the batch size needs to be reduced.
                // This could have some performance impact, but the
                // log is readable and not written off as corrupt.
                if (reduceReaderBatchSize)
                {
                    reader.BatchSize = 1;
                }

                for (; ;)
                {
                    if (!(reader.ReadEvent() is EventLogRecord record))
                    {
                        yield break;
                    }

                    eventCount++;
                    yield return(record);
                }
            }
        }
示例#4
0
        private void SetupWatcher()
        {
            string queryString = GetQueryString();

            query                       = new EventLogQuery(null, PathType.LogName, queryString);
            reader                      = new EventLogReader(query);
            reader.BatchSize            = 10;
            watcher                     = new EventLogWatcher(query);
            watcher.EventRecordWritten += EventRecordWritten;
            watcher.Enabled             = true;

            if (!string.IsNullOrEmpty(config.WindSFTPLogFileName) && File.Exists(config.WindSFTPLogFileName) && File.Exists(config.WindSFTPUsersFileName))
            {
                GetUsersFromFile();
                file         = new FileStream(config.WindSFTPLogFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                streamReader = new StreamReader(file);
                lastSize     = file.Length;
                ProcessCurrentLogFile();

                fileWatcher = new FileSystemWatcher
                {
                    Path         = Path.GetDirectoryName(config.WindSFTPLogFileName),
                    Filter       = Path.GetFileName(config.WindSFTPLogFileName),
                    NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
                };
                fileWatcher.Changed            += FileWatcherOnChanged;
                fileWatcher.EnableRaisingEvents = true;
            }
        }
示例#5
0
        public EventLogReader GetEventLogReader(string path, string query)
        {
            // TODO: investigate https://docs.microsoft.com/en-us/previous-versions/windows/desktop/eventlogprov/win32-ntlogevent

            var eventsQuery = new EventLogQuery(path, PathType.LogName, query)
            {
                ReverseDirection = true
            };

            if (!string.IsNullOrEmpty(ComputerName))
            {
                //EventLogSession session = new EventLogSession(
                //    ComputerName,
                //    "Domain",                                  // Domain
                //    "Username",                                // Username
                //    pw,
                //    SessionAuthentication.Default); // TODO password specification! https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.eventlogsession.-ctor?view=dotnet-plat-ext-3.1#System_Diagnostics_Eventing_Reader_EventLogSession__ctor_System_String_System_String_System_String_System_Security_SecureString_System_Diagnostics_Eventing_Reader_SessionAuthentication_

                var session = new EventLogSession(ComputerName);
                eventsQuery.Session = session;
            }

            var logReader = new EventLogReader(eventsQuery);

            return(logReader);
        }
示例#6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        EventLogReader  logReader = (EventLogReader)Session["EventLogReader"];
        EmployeeProfile emp       = (EmployeeProfile)Session["EmployeeProfile"];

        LoginStatus1.Visible = (null == Session["autologin"]);
        if (null == emp ||
            !this.Page.User.Identity.IsAuthenticated ||
            string.IsNullOrEmpty(emp.Name))
        {
            FormsAuthentication.RedirectToLoginPage();
        }
        else if (logReader != null)
        {
            try {
                Generator        testClass = new Generator(logReader);
                List <TimeEntry> table     = testClass.DisplayEventAndLogInformation(logReader);
                Attendance1.Text     = String.Format("Query: {0}", Session["EventLogQuery"]);
                GridView1.DataSource = table;
                GridView1.DataBind();
                Session["EventLogReader"] = null;
                TotalOT.Text = "Total Overtime: " + testClass.TotalOvertime;

                this.StartDate.Culture      = System.Globalization.CultureInfo.GetCultureInfo("en-US");
                this.StartDate.SelectedDate = (DateTime)Session["DateTime"];
                //this.StartDate.SelectedDateChanged += new EventHandler(DatePicker1_DateChanged);
            }
            catch (EventLogException err) {
                Console.WriteLine("Could not query the remote computer! " + err.Message);
                FormsAuthentication.RedirectToLoginPage();
            }
        }
    }
示例#7
0
        public static string QueryRemoteComputer(string username, string domain, string dc, string dauser, string dapass)
        {
            string       queryString = "*[System[(EventID=4624)] and EventData[Data[@Name='TargetUserName']='******']]"; // XPATH Query
            SecureString pw          = GetPassword(dapass);

            EventLogSession session = new EventLogSession(
                dc,                               // Remote Computer
                domain,                           // Domain
                dauser,                           // Username
                pw,
                SessionAuthentication.Default);

            pw.Dispose();

            // Query the Application log on the remote computer.
            EventLogQuery query = new EventLogQuery("Security", PathType.LogName, queryString);

            query.Session = session;
            EventLogReader reader = new EventLogReader(query);
            EventRecord    eventRecord;
            string         result = String.Empty;

            while ((eventRecord = reader.ReadEvent()) != null)
            {
                result = eventRecord.FormatDescription();
            }
            // Display event info
            return(result);
        }
示例#8
0
        private bool TryCreateEventLogReader()
        {
            try
            {
                var path  = GetPath();
                var query = new EventLogQuery(path, PathType.LogName, "*");
                _reader          = new EventLogReader(query);
                _loggedException = false;

                return(true);
            }
            catch (Exception e)
            {
                if (!_loggedException)
                {
                    Log.ErrorFormat("Unable to create event log reader: {0}", e);

                    _buffer.SetValue(LogFileProperties.EmptyReason, ErrorFlags.SourceCannotBeAccessed);

                    _loggedException = true;
                }
                else
                {
                    Log.DebugFormat("Unable to create event log reader: {0}", e);
                }

                return(false);
            }
        }
示例#9
0
        public static bool DoesMountPointHaveBadBlocks(string mountPoint, out Exception ex, out string eventXML)
        {
            bool     doesMountPointHaveBadBlocks = false;
            string   evtXml      = null;
            DateTime utcNow      = DateTime.UtcNow;
            string   queryString = string.Format("*[System[EventID=24588 or EventID=24593 or EventID=24594 or EventID=24595]][System[Provider[@Name='{0}']]][System[TimeCreated[@SystemTime >= '{2}']]][System[TimeCreated[@SystemTime <= '{3}']]][EventData[Data[@Name='Volume']='{1}']]", new object[]
            {
                "Microsoft-Windows-Bitlocker-Driver",
                mountPoint,
                DateTime.UtcNow.AddDays(-31.0).ToUniversalTime().ToString("o"),
                utcNow.ToUniversalTime().ToString("o")
            });

            ex = Util.HandleExceptions(delegate
            {
                EventLogQuery eventQuery = new EventLogQuery("System", PathType.LogName, queryString);
                using (EventLogReader eventLogReader = new EventLogReader(eventQuery))
                {
                    EventRecord eventRecord;
                    if ((eventRecord = eventLogReader.ReadEvent()) != null)
                    {
                        evtXml = eventRecord.ToXml();
                        doesMountPointHaveBadBlocks = true;
                    }
                }
            });
            eventXML = evtXml;
            return(doesMountPointHaveBadBlocks);
        }
示例#10
0
        public void ExceptionOnce()
        {
            if (PlatformDetection.IsWindows7 ||                       // Null events in PowerShell log
                PlatformDetection.IsWindows10Version22000OrGreater || // Windows 11 and Windows Server 2022:
                PlatformDetection.IsWindows10Version20348OrGreater)   // ActiveIssue("https://github.com/dotnet/runtime/issues/58829")
            {
                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);
                }
            }
        }
        /// <summary>
        /// This method will try to create the <see cref="EventLogReader"/>, however, if the reader can't be created for some reason,
        /// e.g. Service not available or LogName none-existing, it will delay the creation and poll the dependency
        /// </summary>
        protected async ValueTask <EventLogReader> CreateEventLogReader(EventBookmark bookmark, CancellationToken stopToken)
        {
            while (true)
            {
                try
                {
                    var reader = new EventLogReader(new EventLogQuery(_logName, PathType.LogName, _query), _eventBookmark)
                    {
                        BatchSize = 128
                    };

                    return(reader);
                }
                catch (EventLogException ele)
                    when(ele.Message.Contains("The handle is invalid", StringComparison.OrdinalIgnoreCase) || ele is EventLogNotFoundException)
                    {
                        _logger.LogWarning(ele, "Event log '{0}' cannot be read", _logName);
                    }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Error reading event log '{_logName}' with query {_query}");
                }

                await EnsureDependencyAvailable(stopToken);
            }
        }
示例#12
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();
                    }
                }
            }
        }
示例#13
0
        public void ReadLogs()
        {
            EventLogReader reader = new EventLogReader(
                "TestLogs", "xrouter");
            var entries = reader.GetEntries(
                new DateTime(2011, 1, 1),
                new DateTime(2012, 1, 1),
                LogLevelFilters.Error | LogLevelFilters.Warning | LogLevelFilters.Info,
                int.MaxValue, 1);
            int total = entries.Count();
            Console.WriteLine("Total: " + total);

            entries = reader.GetEntries(
                new DateTime(2011, 1, 1),
                new DateTime(2012, 1, 1),
                LogLevelFilters.Error,
                int.MaxValue, 1);
            int error = entries.Count();
            Console.WriteLine("Error: " + total);
            entries = reader.GetEntries(
                new DateTime(2011, 1, 1),
                new DateTime(2012, 1, 1),
                LogLevelFilters.Warning,
                int.MaxValue, 1);
            int warning = entries.Count();
            Console.WriteLine("Warning: " + total);
            entries = reader.GetEntries(
                new DateTime(2011, 1, 1),
                new DateTime(2012, 1, 1),
                LogLevelFilters.Info,
                int.MaxValue, 1);
            int info = entries.Count();
            Console.WriteLine("Info: " + total);
            Assert.Equal(total, error + warning + info);
        }
示例#14
0
        /// <summary>
        /// Test all entries in the event viewer that match config
        /// </summary>
        public void TestAllEntries()
        {
            int count = 0;

            try
            {
                TimeSpan      timeout     = TimeSpan.FromMilliseconds(20.0);
                string        queryString = GetEventLogQueryString(null);
                EventLogQuery query       = new EventLogQuery(null, PathType.LogName, queryString)
                {
                    Session = new EventLogSession("localhost")
                };
                EventLogReader reader = new EventLogReader(query);
                EventRecord    record;
                while ((record = reader.ReadEvent(timeout)) != null)
                {
                    if (++count % 100 == 0)
                    {
                        Console.Write("Count: {0}    \r", count);
                    }
                    ProcessEventViewerXml(record.ToXml());
                }
                service.RunCycle();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
            Console.WriteLine("Tested {0} entries        ", count);
        }
        /// <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);
        }
        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);
            }
        }
示例#17
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
            }
示例#18
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);
            }
        }
示例#19
0
 public void CancelReading()
 {
     using (var eventLog = new EventLogReader("Application"))
     {
         eventLog.CancelReading();
     }
 }
示例#20
0
 public void BatchSize_OtherCtor()
 {
     using (var eventLog = new EventLogReader("Application", PathType.LogName))
     {
         Assert.Equal(64, eventLog.BatchSize);
     }
 }
示例#21
0
        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);
        }
示例#22
0
        private bool TryCreateEventLogReader()
        {
            try
            {
                var path  = GetPath();
                var query = new EventLogQuery(path, PathType.LogName, "*");
                _reader          = new EventLogReader(query);
                _loggedException = false;

                return(true);
            }
            catch (Exception e)
            {
                if (!_loggedException)
                {
                    Log.ErrorFormat("Unable to create event log reader: {0}", e);

                    // TODO: Set error
                    _buffer.SetValue(Core.Properties.EmptyReason, null);

                    _loggedException = true;
                }
                else
                {
                    Log.DebugFormat("Unable to create event log reader: {0}", e);
                }

                return(false);
            }
        }
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                return;
            }

            string dataDirectoryPath = args[0];

            Console.WriteLine($"{DateTime.Now}: Инициализация чтения логов \"{dataDirectoryPath}\"...");

            using (EventLogReader reader = EventLogReader.CreateReader(dataDirectoryPath))
            {
                reader.AfterReadEvent  += Reader_AfterReadEvent;
                reader.AfterReadFile   += Reader_AfterReadFile;
                reader.BeforeReadEvent += Reader_BeforeReadEvent;
                reader.BeforeReadFile  += Reader_BeforeReadFile;
                reader.OnErrorEvent    += Reader_OnErrorEvent;

                Console.WriteLine($"{DateTime.Now}: Всего событий к обработке: ({reader.Count()})...");
                Console.WriteLine();
                Console.WriteLine();

                while (reader.Read())
                {
                    // reader.CurrentRow - данные текущего события
                    _eventNumber += 1;
                }
            }

            Console.WriteLine($"{DateTime.Now}: Для выхода нажмите любую клавишу...");
            Console.ReadKey();
        }
示例#24
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);
        }
示例#25
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"));
            }
        }
示例#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"]);
            }
        }
示例#27
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));
        }
示例#28
0
        private void querySecHistoricLocalServerEvents()
        {
            Thread thloadSecH = new Thread(() =>
            {
                Thread.CurrentThread.Name = "thloadSecH";

                TimeSpan span      = DateTime.UtcNow.Subtract(DateTime.UtcNow.AddDays(-1));
                string queryString = "<QueryList>" +
                                     @"<Query Id = ""0"" Path = ""ForwardedEvents"">" +
                                     @"<Select Path = ""ForwardedEvents""> *[System[(EventID=4740) and TimeCreated[timediff(@SystemTime) &lt;= " + span.TotalMilliseconds + "]]]</Select>" +
                                     @"</Query>" +
                                     @"</QueryList>";

                SecureString pw = new SecureString();
                foreach (char c in frmMain.domainAccountData[2])
                {
                    pw.AppendChar(c);
                }
                EventLogSession session = new EventLogSession("corp1042", frmMain.domainAccountData[0], frmMain.domainAccountData[1], pw, SessionAuthentication.Default);
                pw.Dispose();

                // Query the Application log on the remote computer.
                EventLogQuery query = new EventLogQuery("ForwardedEvents", PathType.LogName, queryString);
                query.Session       = session;

                try
                {
                    EventLogReader logReader = new EventLogReader(query);
                    DisplayEventAndLogInformation(logReader);
                }
                catch (EventLogException ex)
                {
                    Console.WriteLine("Could not query the remote computer! " + ex.Message);
                    return;
                }
                session.Dispose();
                try
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        pBoxProgressSecH.Visible = false;
                    });
                }
                catch { Thread.CurrentThread.Abort(); }
            });

            string nOFDays;
            int    nOFDaysInt;

            nOFDays = txtBoxDays.Text;
            if (int.TryParse(nOFDays, out nOFDaysInt))
            {
                pBoxProgressSecH.Visible = true;
                thloadSecH.Start();
            }
            else
            {
                MessageBox.Show("Please enter only Numbers on field: Days", "Information!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
示例#29
0
        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);
                }
            }
        }
示例#30
0
        /// <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);
        }
示例#31
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);
            }
        }
示例#32
0
        /// <summary>
        /// Starts the reporter server in a new thread.
        /// </summary>
        public void Start()
        {
            // init log readers
            this.eventLogReader = new EventLogReader(this.storagesInfo.LogsDirectory, this.serviceName);
            this.traceLogReader = new TraceLogReader(this.storagesInfo.LogsDirectory, this.serviceName);

            this.worker = new Thread(Run);
            this.worker.Start();
        }
示例#33
0
        /// <summary>
        /// Starts the console server in a new thread.
        /// </summary>
        public void Start()
        {
            // init DB storage
            this.storage = new PersistentStorage(this.storagesInfo.DbConnectionString);

            // init log readers
            this.eventLogReader = new EventLogReader(this.storagesInfo.LogsDirectory, this.serviceName);
            this.traceLogReader = new TraceLogReader(this.storagesInfo.LogsDirectory, this.serviceName);

            ObjectConfigurator.Configurator.CustomItemTypes.Add(new TokenSelectionConfigurationItemType());
            ObjectConfigurator.Configurator.CustomItemTypes.Add(new XRouter.Common.Xrm.XrmUriConfigurationItemType());
            ObjectConfigurator.Configurator.CustomItemTypes.Add(new UriConfigurationItemType());
            UpdatePluginsInApplicationConfiguration();

            // create WCF service on a new thread
            Exception exception = null;
            Thread wcfHostThread = new Thread(delegate(object data)
            {
                try
                {
                    this.wcfHost = new ServiceHost(this, new Uri(this.uri));

                    // set binding (WebService - SOAP/HTTP)
                    WSHttpBinding binding = new WSHttpBinding();
                    binding.MaxReceivedMessageSize = int.MaxValue;
                    binding.ReaderQuotas = new XmlDictionaryReaderQuotas()
                    {
                        MaxBytesPerRead = int.MaxValue,
                        MaxArrayLength = int.MaxValue,
                        MaxStringContentLength = int.MaxValue
                    };

                    // set endpoint
                    this.wcfHost.AddServiceEndpoint(typeof(IConsoleServer), binding, "ConsoleServer");

                    // set metadata behavior
                    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    smb.HttpGetUrl = new Uri(this.metadataUri);
                    this.wcfHost.Description.Behaviors.Add(smb);
                    foreach (var b in this.wcfHost.Description.Behaviors)
                    {
                        if (b is System.ServiceModel.Description.ServiceDebugBehavior)
                        {
                            var sdb = (System.ServiceModel.Description.ServiceDebugBehavior)b;
                            sdb.IncludeExceptionDetailInFaults = true;
                        }
                    }

                    // open connection
                    this.wcfHost.Open();
                }
                catch (Exception e)
                {
                    exception = e;
                }
            });
            wcfHostThread.Start();
            wcfHostThread.Join();

            if (exception != null)
            {
                throw exception;
            }
        }