Пример #1
0
 private void OnEventRecordWritten(object sender, EventRecordWrittenEventArgs e)
 {
     try
     {
         string[] propertyQueries = new string[] { "Event/EventData/Data[@Name=\"IpAddress\"]" };
         EventLogPropertySelector propertySelector = new EventLogPropertySelector(propertyQueries);
         string str = ((EventLogRecord)e.EventRecord).GetPropertyValues(propertySelector)[0].ToString();
         NegotiationdEventArgs data = new NegotiationdEventArgs
         {
             IpAddress       = str,
             EventId         = e.EventRecord.Id,
             EventName       = e.EventRecord.LogName,
             EventMessageXml = e.EventRecord.ToXml(),
             CreateDate      = e.EventRecord.TimeCreated.Value
         };
         if (Negotiated != null)
         {
             Negotiated(this, data);
         }
     }
     catch (Exception exception)
     {
         WriteEntry(exception.Message);
     }
 }
        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 void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
        {
            if (arg.EventRecord != null)
            {
                //////
                // This section creates a list of XPath reference strings to select
                // the properties that we want to display
                // In this example, we will extract the User, TimeCreated, EventID and EventRecordID
                //////
                // Array of strings containing XPath references
                String[] xPathRefs = new String[8];
                xPathRefs[0] = "Event/System/TimeCreated/@SystemTime";
                xPathRefs[1] = "Event/System/Computer";
                xPathRefs[2] = "Event/System/EventRecordID";
                xPathRefs[3] = "Event/EventData/Data[@Name=\"TargetUserName\"]";
                xPathRefs[4] = "Event/EventData/Data[@Name=\"TargetDomainName\"]";
                xPathRefs[5] = "Event/UserData/EventXML/User";
                xPathRefs[6] = "Event/UserData/EventXML/Address";
                xPathRefs[7] = "Event/System/EventID";


                IEnumerable <String> xPathEnum = xPathRefs;

                // Create the property selection context using the XPath reference
                EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

                IList <object> logEventProps = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext);
                StreamWriterExtention.WriteToFile(logEventProps);
                DbOperationExtentions.WriteToDb(logEventProps);

#if (DEBUG)
                {
                    Console.WriteLine("U1 Time: {0}", logEventProps[0]);
                    Console.WriteLine("Computer: {0}", logEventProps[1]);
                    Console.WriteLine("EventRecordId: {0}", logEventProps[2]);
                    Console.WriteLine("TargetUserName: {0}", logEventProps[3]);
                    Console.WriteLine("TargetDomainName: {0}", logEventProps[4]);
                    Console.WriteLine("User: {0}", logEventProps[5]);
                    Console.WriteLine("IP: {0}", logEventProps[6]);
                    Console.WriteLine("EventType: {0}", logEventProps[7]);

                    Console.WriteLine("---------------------------------------");

                    Console.WriteLine("Description: {0}", arg.EventRecord.FormatDescription());
                }
#endif
            }
            else
            {
#if (DEBUG)
                {
                    Console.WriteLine("The event instance was null.");
                }
#endif
            }
        }
        public void Ctor_NonEmptyPropertyQuery_Success()
        {
            IDictionary <string, string> dictionary = new SortedDictionary <string, string>()
            {
                ["key"] = "value"
            };
            var selector = new EventLogPropertySelector(dictionary.Keys);

            Assert.NotNull(selector);
            selector.Dispose();
        }
Пример #5
0
        void OnEntryWritten(object source, EventRecordWrittenEventArgs evt)
        {
            EventLogRecord e = (EventLogRecord)evt.EventRecord;

            using (var loginEventPropertySelector = new EventLogPropertySelector(new[]
            {
                // (The XPath expression evaluates to null if no Data element exists with the specified name.)
                "Event/EventData/Data[@Name='TargetUserSid']",
                "Event/EventData/Data[@Name='TargetLogonId']",
                "Event/EventData/Data[@Name='LogonType']",
                "Event/EventData/Data[@Name='ElevatedToken']",
                "Event/EventData/Data[@Name='WorkstationName']",
                "Event/EventData/Data[@Name='ProcessName']",
                "Event/EventData/Data[@Name='IpAddress']",
                "Event/EventData/Data[@Name='IpPort']",
                "Event/EventData/Data[@Name='TargetUserName']"
            }))

                using (var logoffEventPropertySelector = new EventLogPropertySelector(new[]
                {
                    "Event/EventData/Data[@Name='TargetUserSid']",
                    "Event/EventData/Data[@Name='TargetLogonId']"
                }))

                    switch (e.Id)
                    {
                    case 4624:
                        var loginPropertyValues = ((EventLogRecord)e).GetPropertyValues(loginEventPropertySelector);
                        var sid             = loginPropertyValues[0];
                        var logonId         = loginPropertyValues[1];
                        var logonType       = loginPropertyValues[2];
                        var elevatedToken   = loginPropertyValues[3];
                        var workstationName = loginPropertyValues[4];
                        var processName     = loginPropertyValues[5];
                        var ipAddress       = loginPropertyValues[6];
                        var ipPort          = loginPropertyValues[7];
                        var userName        = loginPropertyValues[8];

                        Console.WriteLine("got eventId={0} sid={1} logonId={2} logonType={3} token={4} workstation={5} process={6} ip={7} port={8} user={9}",
                                          e.Id, sid, logonId, logonType, elevatedToken, workstationName, processName, ipAddress, ipPort, userName);

                        break;

                    case 4634:
                        var logoffPropertyValues = ((EventLogRecord)e).GetPropertyValues(logoffEventPropertySelector);
                        var sid1     = logoffPropertyValues[0];
                        var logoffId = logoffPropertyValues[1];

                        Console.WriteLine("got eventId={0} sid={1} logonId={2}",
                                          e.Id, sid1, logoffId);

                        break;
                    }
        }
        public static void ReadEventLogData()
        {
            string queryString =
                "<QueryList>" +
                "  <Query Id='0' Path='Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'>" +
                "    <Select Path='Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'>*[System[(EventID=21 or EventID=23 or EventID=24 or EventID=25)]]</Select>" +
                "  </Query>" +
                "</QueryList>";

            try
            {
                EventLogQuery  eventsQuery = new EventLogQuery("System", PathType.LogName, queryString);
                EventLogReader logReader   = new EventLogReader(eventsQuery);

                //create an array of strings for xpath enum.
                String[] xPathRefs = new String[4];
                xPathRefs[0] = "Event/UserData/EventXML/User";
                xPathRefs[1] = "Event/UserData/EventXML/Address";
                xPathRefs[2] = "Event/System/EventRecordID";
                xPathRefs[3] = "Event/System/EventID";

                //Sample to read different way to map.
                //xPathRefs[2] = "Event/EventData/Data[@Name='MainPathBootTime']";
                //xPathRefs[3] = "Event/EventData/Data[@Name='BootPostBootTime']";

                IEnumerable <String>     xPathEnum          = xPathRefs;
                EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

                for (EventRecord eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
                {
                    IList <object> logEventProps;
                    logEventProps = ((EventLogRecord)eventDetail).GetPropertyValues(logPropertyContext);

                    string user          = logEventProps[0].ToString();
                    string ip            = logEventProps[1] != null ? logEventProps[1].ToString() : "";
                    int    eventRecordID = logEventProps[2] != null?Convert.ToInt32(logEventProps[2]) : 0;

                    int eventTypeId = logEventProps[3] != null?Convert.ToInt32(logEventProps[3]) : 0;
                }
            }
            catch (EventLogNotFoundException e)
            {
#if (DEBUG)
                {
                    Console.WriteLine("Error while reading the event logs");
                }
#endif
            }
        }
Пример #7
0
        public List <IEvent> ReadEventLogData()
        {
            List <IEvent> coll        = new List <IEvent>();
            string        queryString =
                "<QueryList>" +
                "  <Query Id='0' Path='Microsoft-Windows-Diagnostics-Performance/Operational'>" +
                "    <Select Path='Microsoft-Windows-Diagnostics-Performance/Operational'>*[System[(EventID=100)]]</Select>" +
                "  </Query>" +
                "</QueryList>";

            try
            {
                EventLogQuery  eventsQuery = new EventLogQuery("System", PathType.LogName, queryString);
                EventLogReader logReader   = new EventLogReader(eventsQuery);

                //create an array of strings for xpath enum.
                String[] xPathRefs = new String[4];
                xPathRefs[0] = "Event/EventData/Data[@Name='BootEndTime']";
                xPathRefs[1] = "Event/EventData/Data[@Name='BootTime']";
                xPathRefs[2] = "Event/EventData/Data[@Name='MainPathBootTime']";
                xPathRefs[3] = "Event/EventData/Data[@Name='BootPostBootTime']";
                IEnumerable <String>     xPathEnum          = xPathRefs;
                EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

                for (EventRecord eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
                {
                    IList <object> logEventProps;
                    // Cast the EventRecord into an EventLogRecord to retrieve property values.
                    // This will fetch the event properties we requested through the
                    // context created by the EventLogPropertySelector
                    logEventProps = ((EventLogRecord)eventDetail).GetPropertyValues(logPropertyContext);
                    if (eventDetail.Id == 100)
                    {
                        int      boot     = Convert.ToInt32(logEventProps[1]);
                        int      mainPath = Convert.ToInt32(logEventProps[2]);
                        int      postBoot = Convert.ToInt32(logEventProps[3]);
                        DateTime date     = (DateTime)logEventProps[0];
                        coll.Add(new StartupEvent(date, boot, mainPath, postBoot, (int)eventDetail.Level));
                    }
                }
            }
            catch (EventLogNotFoundException e)
            {
                Console.WriteLine("Error while reading the event logs");
            }
            return(coll);
        }
Пример #8
0
 private void watcher_EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
 {
     try {
         string[] xPathProperties = new string[1] {
             @"Event/EventData/Data[@Name=""IpAddress""]"
         };
         EventLogPropertySelector props = new EventLogPropertySelector(xPathProperties);
         string ipAddress           = ((EventLogRecord)e.EventRecord).GetPropertyValues(props)[0].ToString();
         NotificationEventArgs args = new NotificationEventArgs();
         args.CreateDate = e.EventRecord.TimeCreated.Value;
         args.EventId    = e.EventRecord.Id;
         args.IpAddress  = ipAddress;
         OnAttackDetected(this, args);
     } catch (Exception ex) {
         EventLog.WriteEntry("Cyberarms.IntrusionDetection.Base.Plugins.WindowsSecurityBase", ex.Message);
     }
 }
Пример #9
0
 public void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
 {
     if (arg.EventRecord != null)
     {
         EventRecord eventInstance = arg.EventRecord;
         //String eventMessage = eventInstance.FormatDescription(); // You can get event information from FormatDescription API itself.
         //String eventMessageXMLFmt = eventInstance.ToXml(); // Getting event information in xml format
         String[] xPathRefs = new String[9];
         xPathRefs[0] = "Event/System/TimeCreated/@SystemTime";
         xPathRefs[1] = "Event/System/Computer";
         xPathRefs[2] = "Event/EventData/Data[@Name=\"TargetUserName\"]";
         IEnumerable <String>     xPathEnum          = xPathRefs;
         EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);
         IList <object>           logEventProps      = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext);
         Log("Time: ", logEventProps[0]);
         Log("Computer: ", logEventProps[1]);
     }
 }
Пример #10
0
        public void TestEventLogReader()
        {
            string eventLogQuery = @"<QueryList>
                  <Query Id=""0"" Path=""Security"">
                    <Select Path=""Security"">
                        *[System[(EventID=4625) and
                        TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]
                    </Select>

                  </Query>
                </QueryList>";


            EventLogQuery query = new EventLogQuery("Security", PathType.LogName,
                                                    String.Format(eventLogQuery));
            EventLogReader rdr = new EventLogReader(query);

            EventRecord eventRecord = rdr.ReadEvent();

            if (eventRecord != null)
            {
                foreach (string s in eventRecord.KeywordsDisplayNames)
                {
                    System.Diagnostics.Debug.Print(s);
                }
            }

            string[] xPathProperties = new string[1] {
                @"Event/EventData/Data[@Name=""IpAddress""]"
            };

            EventLogPropertySelector props = new EventLogPropertySelector(xPathProperties);

            System.Diagnostics.Debug.Print(((EventLogRecord)eventRecord).GetPropertyValues(props)[0].ToString());

            System.Diagnostics.Debug.Print(eventRecord.Properties[0].Value.ToString());
        }
Пример #11
0
        private void Worker()
        {
            if (_listener is null)
            {
                return;
            }

            var logRecords = new List <LogRecord>();
            var cfg        = new Config(_configFile);

            LogMessage("Starting new observation loop.");
            LogMessage($"Last logged IMAP session: {cfg.LastObservationSession}");
            LogMessage($"Last logged IMAP time: {cfg.LastObservationTime}");
            LogMessage($"Searching for matching events: {cfg.CheckEventLog}");
            LogMessage($"Max days to retain logs: {cfg.MaxDaysToRetainLogs}");
            LogMessage(
                "Log directory: " +
                (string.IsNullOrWhiteSpace(cfg.LogDirectory) ? "(auto discovered)" : cfg.LogDirectory));

            // support both daily and hourly log files.
            var rexLogFile = new Regex(@"^imap4(\d{8}|\d{10})(?:-\d+)?\.log$", RegexOptions.IgnoreCase);

            bool QuitNow() => _listener?.CancellationToken.IsCancellationRequested ?? true;

            try
            {
                while (!QuitNow())
                {
                    logRecords.Clear();

                    var minLogDate = cfg.LastObservationTime ?? DateTime.Now.AddMinutes(-cfg.MaxAgeInMinutesToReport);
                    var minLogSess = cfg.LastObservationSession ?? 0;
                    var fnMinTime  = long.Parse(minLogDate.ToUniversalTime().ToString("yyyyMMddHH"));

                    // search the log directories for new log entries.
                    foreach (var filename in AvailableLogFiles(cfg))
                    {
                        if (QuitNow())
                        {
                            return;
                        }

                        var match = rexLogFile.Match(Path.GetFileName(filename) ?? "");
                        if (!match.Success)
                        {
                            continue;
                        }
                        var tss = match.Groups[1].Value;
                        if (tss.Length == 8)
                        {
                            tss += "24";
                        }
                        var ts = long.Parse(tss);
                        if (ts < fnMinTime)
                        {
                            continue;
                        }
                        logRecords.AddRange(ParseLog(filename));
                        logRecords.RemoveAll(
                            (r) => (r.LogDate < minLogDate && !r.LogDate.CloseTo(minLogDate)) ||
                            (r.LogDate.CloseTo(minLogDate) && r.SessionID <= minLogSess) ||
                            !r.IsLoginFailure);
                    }

                    if (QuitNow())
                    {
                        return;
                    }

                    if (!logRecords.Any())
                    {
                        continue;
                    }

                    // check the event log for user names if configured to do so.
                    var identified = 0;
                    if (cfg.CheckEventLog)
                    {
                        var ts = minLogDate.AddSeconds(-5)
                                 .ToUniversalTime()
                                 .ToString("yyyy-MM-dd'T'HH:mm:ss'.000Z'");
                        var evQuery  = $"*[System[(EventID=4625) and (TimeCreated[@SystemTime>='{ts}'])]]";
                        var evLog    = new EventLogQuery("Security", PathType.LogName, evQuery);
                        var selector = new EventLogPropertySelector(
                            new[]
                        {
                            "Event/EventData/Data[@Name='ProcessName']",
                            "Event/EventData/Data[@Name='TargetUserName']"
                        });
                        using (var evReader = new EventLogReader(evLog))
                        {
                            var ev = evReader.ReadEvent();
                            while (ev != null)
                            {
                                if (QuitNow())
                                {
                                    return;
                                }
                                if (ev is EventLogRecord er && er.TimeCreated.HasValue)
                                {
                                    var props = er.GetPropertyValues(selector).Select(x => x?.ToString() ?? "")
                                                .ToArray();

                                    if (!string.IsNullOrWhiteSpace(props[1]) &&
                                        props[0].EndsWith(
                                            "Microsoft.Exchange.Imap4.exe", StringComparison.OrdinalIgnoreCase)
                                        )
                                    {
                                        var evTime   = er.TimeCreated.GetValueOrDefault();
                                        var logEntry = logRecords
                                                       .Where(r => r.LogDate.CloseTo(evTime, 2.0))
                                                       .OrderBy(r => Math.Abs(r.LogDate.Subtract(evTime).TotalSeconds))
                                                       .FirstOrDefault();

                                        if (logEntry != null && logEntry.User == "imap-user")
                                        {
                                            identified++;
                                            logEntry.User = props[1];
                                        }
                                    }
                                }

                                ev = evReader.ReadEvent();
                            }
                        }
                    }

                    if (logRecords.Count == 1)
                    {
                        LogMessage(
                            identified > 0
                                                                ? "Found 1 login attempt and identified the user."
                                                                : "Found 1 login attempt and did not identify the user.");
                    }
                    else
                    {
                        LogMessage(
                            $"Found {logRecords.Count} login attempts and identified the user in {identified} of them.");
                    }

                    // report the observations to the listener.
                    foreach (var record in logRecords)
                    {
                        if (QuitNow())
                        {
                            return;
                        }
                        _listener.RecordObservation(record.ToObservation());
                        if (record.SessionID > cfg.LastObservationSession.GetValueOrDefault())
                        {
                            cfg.LastObservationSession = record.SessionID;
                        }
                        if (record.LogDate > cfg.LastObservationTime.GetValueOrDefault())
                        {
                            cfg.LastObservationTime = record.LogDate;
                        }
                    }

                    // update the configuration.
                    File.WriteAllText(_configFile, cfg.ToString());

                    // purge older log files.
                    minLogDate = DateTime.Today.AddDays(-cfg.MaxDaysToRetainLogs);
                    fnMinTime  = long.Parse(minLogDate.ToUniversalTime().ToString("yyyyMMdd'24'"));
                    foreach (var filename in AvailableLogFiles(cfg))
                    {
                        var match = rexLogFile.Match(Path.GetFileName(filename) ?? "");
                        if (!match.Success)
                        {
                            continue;
                        }
                        var tss = match.Groups[1].Value;
                        if (tss.Length == 8)
                        {
                            tss += "24";
                        }
                        var ts = long.Parse(tss);
                        if (ts >= fnMinTime)
                        {
                            continue;
                        }
                        try
                        {
                            File.Delete(filename);
                        }
                        catch (Exception e) when(
                            e is IOException ||
                            e is ArgumentException ||
                            e is NotSupportedException ||
                            e is UnauthorizedAccessException
                            )
                        {
                            // ignore
                        }
                    }

                    // wait a minute before the next pass.
                    var timeout = DateTime.Now.AddMinutes(1);
                    while (DateTime.Now < timeout && !QuitNow())
                    {
                        Thread.Sleep(10);
                    }
                }
            }
            finally
            {
                try
                {
                    File.WriteAllText(_configFile, cfg.ToString());
                }
                catch (Exception e) when(
                    e is ArgumentException ||
                    e is IOException ||
                    e is UnauthorizedAccessException ||
                    e is NotSupportedException ||
                    e is SecurityException
                    )
                {
                    // Ignore.
                }

                LogMessage("Stopping observation loop.");
            }
        }
Пример #12
0
        public static IReadOnlyList <SecurityEvent> ReadAll()
        {
            var events = new List <SecurityEvent>();

            // To investigate as a separate report:

            // 4625 An account failed to log on.
            // 4648 A logon was attempted using explicit credentials.
            // 4672 Special privileges assigned to new logon.
            // 4675 SIDs were filtered.
            // 4797 Sometimes "An attempt was made to query the existence of a blank password for an account."
            // Logoff events without logon events

            var query = new EventLogQuery(
                "Security",
                PathType.LogName,
                @"*[(((System[EventID=4624] and EventData[Data[@Name='LogonType']!=5]) or System[EventID=4634])
                    and EventData[
                        Data[@Name='TargetUserSid']!='S-1-0-0'
                        and Data[@Name='TargetUserSid']!='S-1-5-7'
                        and Data[@Name='TargetUserSid']!='S-1-5-18'
                        and Data[@Name='TargetDomainName']!='Font Driver Host'
                        and Data[@Name='TargetDomainName']!='Window Manager'])
                    or System[EventID=4647 or EventID=4608]]");

            using (var loginEventPropertySelector = new EventLogPropertySelector(new[]
            {
                "Event/EventData/Data[@Name='TargetLogonId']",
                "Event/EventData/Data[@Name='TargetLinkedLogonId']",
                "Event/EventData/Data[@Name='TargetUserSid']",
                "Event/EventData/Data[@Name='TargetUserName']",
                "Event/EventData/Data[@Name='TargetDomainName']",
                "Event/EventData/Data[@Name='LogonType']",
                "Event/EventData/Data[@Name='ElevatedToken']",
                "Event/EventData/Data[@Name='WorkstationName']",
                "Event/EventData/Data[@Name='ProcessName']",
                "Event/EventData/Data[@Name='IpAddress']",
                "Event/EventData/Data[@Name='IpPort']"
            }))
                using (var logoffEventPropertySelector = new EventLogPropertySelector(new[]
                {
                    "Event/EventData/Data[@Name='TargetLogonId']",
                    "Event/EventData/Data[@Name='TargetUserSid']"
                }))
                    using (var reader = new EventLogReader(query))
                    {
                        while (reader.ReadEvent() is { } ev)
                        {
                            switch (ev.Id)
                            {
                            case 4608:
                                events.Add(new StartupEvent(ev.TimeCreated.Value));
                                break;

                            case 4624:
                                var loginPropertyValues = ((EventLogRecord)ev).GetPropertyValues(loginEventPropertySelector);

                                events.Add(new LogonEvent(
                                               ev.TimeCreated.Value,
                                               logonId: (ulong)loginPropertyValues[0],
                                               linkedLogonId: (ulong)loginPropertyValues[1],
                                               user: (SecurityIdentifier)loginPropertyValues[2],
                                               userName: (string)loginPropertyValues[3],
                                               domainName: (string)loginPropertyValues[4],
                                               logonType: (LogonType)(uint)loginPropertyValues[5],
                                               elevatedToken: loginPropertyValues[6] is "%%1842",
                                               workstationName: GetXPathString(loginPropertyValues[7]),
                                               processName: GetXPathString(loginPropertyValues[8]),
                                               ipAddress: GetXPathString(loginPropertyValues[9]),
                                               ipPort: GetXPathString(loginPropertyValues[10])));
                                break;

                            case 4634:
                            case 4647:
                                var logoffPropertyValues = ((EventLogRecord)ev).GetPropertyValues(logoffEventPropertySelector);

                                events.Add(new LogoffEvent(
                                               ev.TimeCreated.Value,
                                               logonId: (ulong)logoffPropertyValues[0],
                                               user: (SecurityIdentifier)logoffPropertyValues[1]));
                                break;
                            }
                        }
                    }

            return(events);
        }
Пример #13
0
    static void Main(string[] args)
    {
        String       logName     = "Application";
        String       queryString = "*[System/Level=2]";
        UdpClient    _udpClient;
        String       host      = "192.168.1.28";
        UTF8Encoding _encoding = new UTF8Encoding();

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

        EventLogReader logReader;

        Console.WriteLine("Querying the Application channel event log for all events...");
        try
        {
            // Query the log
            logReader = new EventLogReader(eventsQuery);
        }
        catch (EventLogNotFoundException e)
        {
            Console.WriteLine("Failed to query the log!");
            Console.WriteLine(e);
            return;
        }

        //////
        // This section creates a list of XPath reference strings to select
        // the properties that we want to display
        // In this example, we will extract the User, TimeCreated, EventID and EventRecordID
        //////
        // Array of strings containing XPath references
        String[] xPathRefs = new String[4];
        xPathRefs[0] = "Event/System/Security/@UserID";
        xPathRefs[1] = "Event/System/TimeCreated/@SystemTime";
        xPathRefs[2] = "Event/System/EventID";
        xPathRefs[3] = "Event/System/EventRecordID";
        // Place those strings in an IEnumberable object
        IEnumerable <String> xPathEnum = xPathRefs;
        // Create the property selection context using the XPath reference
        EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

        _udpClient = new UdpClient();
        _udpClient.Connect(host, 5140);

        int numberOfEvents = 0;

        // For each event returned from the query
        for (EventRecord eventInstance = logReader.ReadEvent();
             eventInstance != null;
             eventInstance = logReader.ReadEvent())
        {
            IList <object> logEventProps;
            try
            {
                // Cast the EventRecord into an EventLogRecord to retrieve property values.
                // This will fetch the event properties we requested through the
                // context created by the EventLogPropertySelector
                logEventProps = ((EventLogRecord)eventInstance).GetPropertyValues(logPropertyContext);
                Console.WriteLine("Event {0} :", ++numberOfEvents);
                Console.WriteLine("User: {0}", logEventProps[0]);
                Console.WriteLine("TimeCreated: {0}", logEventProps[1]);
                Console.WriteLine("EventID: {0}", logEventProps[2]);
                Console.WriteLine("EventRecordID : {0}", logEventProps[3]);

                // Event properties can also be retrived through the event instance
                Console.WriteLine("Event Description:" + eventInstance.FormatDescription());
                Console.WriteLine("MachineName: " + eventInstance.MachineName);



                Console.WriteLine("=================== START ====================");
                Console.WriteLine(eventInstance.ToXml());
                Console.WriteLine("==============================================");

                String xmlString = eventInstance.ToXml();
                byte[] data      = _encoding.GetBytes(xmlString);
                _udpClient.Send(data, data.Length);
            }
            catch (Exception e)
            {
                Console.WriteLine("Couldn't render event!");
                Console.WriteLine("Exception: Event {0} may not have an XML representation \n\n", ++numberOfEvents);
                Console.WriteLine(e);
            }
        }
    }
Пример #14
0
        public EventLogInput(InputElement input, SelectorElement selector, EventQueue equeue)
            : base(input, selector, equeue)
        {
            Log.Info("input[" + InputName + "]/selector[" + SelectorName
                     + "] creating EventLogInput");

            // Event log query with suppressed events logged by this service
            StringBuilder qstr = new StringBuilder();

            qstr.Append("<QueryList>");
            qstr.Append("<Query>");
            qstr.Append(selector.Query.Value);
            qstr.Append("<Suppress Path=\"Application\">*[System/Provider/@Name=\"F2B\"]</Suppress>");
            qstr.Append("</Query>");
            qstr.Append("</QueryList>");

            EventLogSession session = null;

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

            EventLogQuery query = new EventLogQuery(null, PathType.LogName, qstr.ToString());

            if (session != null)
            {
                query.Session = session;
            }

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

            // event data parsers (e.g. XPath + regex to extract event data)
            // (it is important to preserve order - it is later used as array index)
            evtregexs = new List <EventLogParserData>();
            List <string> xPathRefs = new List <string>();

            foreach (RegexElement item in selector.Regexes)
            {
                if (string.IsNullOrEmpty(item.XPath))
                {
                    Log.Warn("Invalid input[" + InputName + "]/selector[" + SelectorName
                             + "] event regexp \"" + item.Id + "\" attribute xpath empty");

                    continue;
                }

                if (!xPathRefs.Contains(item.XPath))
                {
                    xPathRefs.Add(item.XPath);
                }

                try
                {
                    int index = xPathRefs.IndexOf(item.XPath);
                    EventLogParserData eli = new EventLogParserData(item.Id, item.Type, item.XPath, index, item.Value);
                    evtregexs.Add(eli);
                }
                catch (ArgumentException ex)
                {
                    Log.Error("Invalid input[" + InputName + "]/selector[" + SelectorName
                              + "] event regexp failed: " + ex.Message);

                    throw;
                }
            }

            evtsel = null;
            if (xPathRefs.Count > 0)
            {
                evtsel = new EventLogPropertySelector(xPathRefs);
            }

            // user defined event properties
            evtdata_before = new List <EventDataElement>();
            evtdata_match  = new List <KeyValuePair <string, EventDataElement> >();
            evtdata_after  = new List <EventDataElement>();
            foreach (EventDataElement item in selector.EventData)
            {
                if (item.Apply == "before")
                {
                    evtdata_before.Add(item);
                }
                else if (item.Apply == "after")
                {
                    evtdata_after.Add(item);
                }
                else if (item.Apply.StartsWith("match."))
                {
                    string key = item.Apply.Substring("match.".Length);
                    evtdata_match.Add(new KeyValuePair <string, EventDataElement>(key, item));
                }
                else
                {
                    Log.Warn("Invalid input[" + InputName + "]/selector[" + SelectorName
                             + "] event data \"" + item.Name + "\" attribute apply \""
                             + item.Apply + "\": ignoring this item");
                }
            }
        }