Ejemplo n.º 1
0
        /// <summary>
        /// WaitForEvent2 where "2" designates alternate event subscription paradigm of waiting for event
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="source"></param>
        /// <param name="entryType"></param>
        /// <param name="timeOutSeconds"></param>
        /// <param name="action"></param>
        /// <param name="expectedEventCount"></param>
        /// <returns></returns>
        public static bool WaitForEvent2(int eventId, string eventMessage, string source, EventLogEntryType entryType,
                                         int timeOutSeconds,
                                         Action action, int expectedEventCount)
        {
            lock (_lock)
            {
                //really intended for single threaded tests - locking this region just in case
                _found      = false;
                _signal     = new AutoResetEvent(false);
                _eventCount = expectedEventCount;
                EventLogWatcher watcher = null;
                //try
                //{
                int level = -1;
                switch (entryType)
                {
                case EventLogEntryType.Information:
                    level = 4;
                    break;

                case EventLogEntryType.Warning:
                    level = 3;
                    break;

                case EventLogEntryType.Error:
                    level = 2;
                    break;
                }
                //The following if check is for use when you check for multiple events in subsequent, separate calls -e.g.
                //WaitForEvent2(1000, ....);  --> Here the event subscription will kick in looking for 1000...alll the while 2000 events may be logged
                //WaitForEvent2(2000, ....);  --> 2000 events already logged won't be caught
                //cff: there is a theoretical threading issue if you do the above
                int eventsExist = CheckEventCount(eventId, eventMessage, entryType);
                _eventCount -= eventsExist;
                if (_eventCount == 0)
                {
                    _found = true;
                }

                else
                {
                    //here's where the theoretical threading issue occurs ONLY if you are doing two subsequent WaitForEvent2's
                    //inbetween if the if statement above and the subscription below

                    EventLogQuery subscriptionQuery = new EventLogQuery(
                        "Application", PathType.LogName,
                        string.Format("*[System[Provider[@Name='{0}'] and (EventID={1}) and (Level={2})]]", source,
                                      eventId,
                                      level));

                    using (watcher = new EventLogWatcher(subscriptionQuery))
                    {
                        // Make the watcher listen to the EventRecordWritten
                        // events.  When this event happens, the callback method
                        // (EventLogEventRead) is called.
                        watcher.EventRecordWritten +=
                            EventLogEventRead;

                        // Activate the subscription
                        watcher.Enabled = true;
                        action();
                        _signal.WaitOne(timeOutSeconds * 1000);
                        watcher.Enabled = false;
                    }
                    //if (_eventCount > 0)
                    //{
                    eventsExist = CheckEventCount(eventId, eventMessage, entryType);
                    if (eventsExist == expectedEventCount)
                    {
                        _found = true;
                    }
                    else
                    {
                        _found = false;
                    }
                    //}
                }
            }
            return(_found);
        }
Ejemplo n.º 2
0
        static public void InsertEventLog()
        {
            if (Triger)
            {
                Console.WriteLine("Already On");
                return;
            }
            else
            {
                Console.WriteLine("LogSearchStart");
                Triger = true;
            }

            EvLogPara nevlp = new EvLogPara("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            EvLogPara oevlp = new EvLogPara("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");

            TC_2 = TC_1;

            StringBuilder sb          = new StringBuilder();
            const string  queryString = @"<QueryList>
                                          <Query Id=""0"" Path=""Security"">
                                            <Select Path=""Security"">*</Select>
                                          </Query>
                                        </QueryList>";
            EventLogQuery eventsQuery = new EventLogQuery("Security", PathType.LogName, queryString);

            eventsQuery.ReverseDirection = true;
            EventLogReader logReader = new EventLogReader(eventsQuery);

            //string g_ConnectionStr = @"Data Source=192.168.10.230,7100;Initial Catalog=arcon;Integrated Security=False;User ID=arconsa;Password=arconsa@pass0;Connect Timeout=5;Encrypt=False;TrustServerCertificate=False";
            string        g_ConnectionStr = @"Data Source=127.0.0.1,1433;Initial Catalog=Eventlog;Integrated Security=False;User ID=eventsa;Password=eventsa@pass0;Connect Timeout=5;Encrypt=False;TrustServerCertificate=False";
            SqlCommand    sqlCmd          = new SqlCommand();
            SqlConnection sqlCon          = new SqlConnection(g_ConnectionStr);

            for (EventRecord eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                foreach (var VARIABLE in eventInstance.Properties)
                {
                    if (!VARIABLE.Value.ToString().Contains(g_FoldertoSearch))
                    {
                        continue;
                    }
                    if (!TF)
                    {
                        if (DateTime.Compare(TC_2, (DateTime)eventInstance.TimeCreated) != -1)
                        {
                            continue;
                        }
                    }
                    try
                    {
                        if ((eventInstance.TaskDisplayName.ToString() == LanguageFilter[0] || eventInstance.TaskDisplayName.ToString() == LanguageFilter[1] || eventInstance.TaskDisplayName.ToString() == LanguageFilter[2]))
                        {
                            if (eventInstance.Id.ToString() == "4656")//본인 PC
                            {
                                if (eventInstance.Properties[6].Value.ToString().Replace(g_FoldertoSearch, "").Length != 0)
                                {
                                    nevlp.LoadTime       = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.sss");
                                    nevlp.EventID        = eventInstance.Id.ToString();
                                    nevlp.UserName       = eventInstance.Properties[1].Value.ToString();
                                    nevlp.DomainName     = eventInstance.Properties[2].Value.ToString();
                                    nevlp.LogonID        = eventInstance.Properties[3].Value.ToString();
                                    nevlp.Information    = eventInstance.Properties[4].Value.ToString();
                                    nevlp.Subject        = eventInstance.Properties[5].Value.ToString();
                                    nevlp.PC_IPAddress   = "";
                                    nevlp.PC_Port        = "";
                                    nevlp.ShareName      = "";
                                    nevlp.ShareLocalPath = eventInstance.Properties[6].Value.ToString();
                                    nevlp.FileName       = Path.GetFileName(eventInstance.Properties[6].Value.ToString());
                                    nevlp.AccessMask     = "";
                                    nevlp.AccessList     = DataReplace(eventInstance.Properties[9].Value.ToString());
                                    nevlp.AccessReason   = DataReplace(eventInstance.Properties[10].Value.ToString());
                                    nevlp.EventTime      = eventInstance.TimeCreated.Value.ToString("yyyy-MM-dd HH:mm:ss.sss");

                                    Console.WriteLine("==============================================================");
                                    Console.WriteLine("LoadTime " + nevlp.LoadTime);
                                    Console.WriteLine("EventID : " + nevlp.EventID);
                                    Console.WriteLine("UserName : "******"DomainName : " + nevlp.DomainName);
                                    Console.WriteLine("LogonID : " + nevlp.LogonID);
                                    Console.WriteLine("Information : " + nevlp.Information);
                                    Console.WriteLine("Subject : " + nevlp.Subject);
                                    Console.WriteLine("ShareLocalPath : " + nevlp.ShareLocalPath);
                                    Console.WriteLine("FileName : " + nevlp.FileName);
                                    Console.WriteLine("AccessList : \n" + nevlp.AccessList);
                                    Console.WriteLine("AccessReason : \n" + nevlp.AccessReason);
                                    Console.WriteLine("EventTime: " + nevlp.EventTime);
                                }
                            }
                            if (eventInstance.Id.ToString() == "5145")//공유 폴더
                            {
                                if (eventInstance.Properties[9].Value.ToString().Replace("\\", "").Length != 0 && eventInstance.TaskDisplayName.ToString() == LanguageFilter[1])
                                {
                                    nevlp.LoadTime       = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.sss");
                                    nevlp.EventID        = eventInstance.Id.ToString();
                                    nevlp.UserName       = eventInstance.Properties[1].Value.ToString();
                                    nevlp.DomainName     = eventInstance.Properties[2].Value.ToString();
                                    nevlp.Subject        = eventInstance.Properties[4].Value.ToString();
                                    nevlp.LogonID        = eventInstance.Properties[3].Value.ToString();
                                    nevlp.PC_IPAddress   = eventInstance.Properties[5].Value.ToString();
                                    nevlp.PC_Port        = eventInstance.Properties[6].Value.ToString();
                                    nevlp.ShareName      = eventInstance.Properties[7].Value.ToString();
                                    nevlp.ShareLocalPath = eventInstance.Properties[8].Value.ToString();
                                    nevlp.FileName       = eventInstance.Properties[9].Value.ToString();
                                    nevlp.AccessMask     = eventInstance.Properties[10].Value.ToString();
                                    nevlp.AccessList     = DataReplace(eventInstance.Properties[11].Value.ToString());
                                    nevlp.AccessReason   = DataReplace(eventInstance.Properties[12].Value.ToString());
                                    nevlp.EventTime      = eventInstance.TimeCreated.Value.ToString("yyyy-MM-dd HH:mm:ss.sss");
                                    nevlp.Information    = "";

                                    Console.WriteLine("==============================================================");
                                    Console.WriteLine("LoadTime " + nevlp.LoadTime);
                                    Console.WriteLine("EventID : " + nevlp.EventID);
                                    Console.WriteLine("UserName : "******"DomainName : " + nevlp.DomainName);
                                    Console.WriteLine("Subject : " + nevlp.Subject);
                                    Console.WriteLine("LogonID : " + nevlp.LogonID);
                                    Console.WriteLine("PC_IPAddress : " + nevlp.PC_IPAddress);
                                    Console.WriteLine("PC_Port : " + nevlp.PC_Port);
                                    Console.WriteLine("ShareName: " + nevlp.ShareName);
                                    Console.WriteLine("ShareLocalPath : " + nevlp.ShareLocalPath);
                                    Console.WriteLine("FileName: " + nevlp.FileName);
                                    Console.WriteLine("AccessMask : " + nevlp.AccessMask);
                                    Console.WriteLine("AccessList : \n" + nevlp.AccessList);
                                    Console.WriteLine("AccessReason : \n" + nevlp.AccessReason);
                                    Console.WriteLine("CreateTime : " + nevlp.EventTime);
                                }
                            }
                        }
                        if (nevlp.EventID != "" && hasing(oevlp, nevlp))
                        {
                            sqlCon.Open();
                            sqlCmd.Connection = sqlCon;

                            sqlCmd.CommandText = $"INSERT INTO Eventlog.dbo.EventLogView(LoadTime, EventID, UserName, DomainName, Subject, PC_IPAddress, PC_Port, ShareName, ShareLocalPath, FileName, AccessMask, AccessList, AccessReason, EventTime, LogonID, Information)" +
                                                 $" VALUES ('" + nevlp.LoadTime + "','" + nevlp.EventID + "','" + nevlp.UserName + "','" + nevlp.DomainName + "','" + nevlp.Subject + "','" + nevlp.PC_IPAddress + "','" + nevlp.PC_Port + "','" + nevlp.ShareName + "','" + nevlp.ShareLocalPath + "','" + nevlp.FileName + "','" + nevlp.AccessMask + "','" + nevlp.AccessList + "','" + nevlp.AccessReason + "','" + nevlp.EventTime + "','" + nevlp.LogonID + "','" + nevlp.Information + "')";

                            oevlp = nevlp;
                            sqlCmd.ExecuteNonQuery();
                            sqlCon.Close();

                            if (DateTime.Compare(TC_1, (DateTime)eventInstance.TimeCreated) == -1)
                            {
                                TC_1 = (DateTime)eventInstance.TimeCreated;
                            }

                            TF = false;

                            Console.WriteLine("insert Data");
                        }
                    }
                    catch (Exception e2)
                    {
                        sqlCon.Close();
                        Console.WriteLine(e2.Message);
                    }
                }
            }
            Triger = false;
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Stop the agent
 /// </summary>
 protected override void OnStopAgent()
 {
     watcher.Enabled = false;
     watcher         = null;
     query           = null;
 }
Ejemplo n.º 4
0
        public override IEnumerable <CommandDTOBase?> Execute(string[] args)
        {
            // adapted from @djhohnstein's EventLogParser project
            //  https://github.com/djhohnstein/EventLogParser/blob/master/EventLogParser/EventLogHelpers.cs
            // combined with scraping from https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands

            WriteVerbose($"Searching script block logs (EID 4104) for sensitive data.\n");

            var context = 3; // number of lines around the match to display

            string[] powershellLogs = { "Microsoft-Windows-PowerShell/Operational", "Windows PowerShell" };

            // Get our "sensitive" cmdline regexes from a common helper function.
            var powershellRegex = MiscUtil.GetProcessCmdLineRegex();

            foreach (var logName in powershellLogs)
            {
                var query         = "*[System/EventId=4104]";
                var eventLogQuery = new EventLogQuery(logName, PathType.LogName, query)
                {
                    ReverseDirection = true
                };
                var logReader = new EventLogReader(eventLogQuery);

                for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
                {
                    var scriptBlock = eventDetail.Properties[2].Value.ToString();
                    foreach (var reg in powershellRegex)
                    {
                        var m = reg.Match(scriptBlock);
                        if (!m.Success)
                        {
                            continue;
                        }

                        var contextLines = new List <string>();

                        var scriptBlockParts = scriptBlock.Split('\n');
                        for (var i = 0; i < scriptBlockParts.Length; i++)
                        {
                            if (!scriptBlockParts[i].Contains(m.Value))
                            {
                                continue;
                            }

                            var printed = 0;
                            for (var j = 1; i - j > 0 && printed < context; j++)
                            {
                                if (scriptBlockParts[i - j].Trim() == "")
                                {
                                    continue;
                                }

                                contextLines.Add(scriptBlockParts[i - j].Trim());
                                printed++;
                            }
                            printed = 0;
                            contextLines.Add(m.Value.Trim());
                            for (var j = 1; printed < context && i + j < scriptBlockParts.Length; j++)
                            {
                                if (scriptBlockParts[i + j].Trim() == "")
                                {
                                    continue;
                                }

                                contextLines.Add(scriptBlockParts[i + j].Trim());
                                printed++;
                            }
                            break;
                        }

                        var contextJoined = string.Join("\n", contextLines.ToArray());

                        yield return(new PowerShellEventsDTO(
                                         eventDetail.TimeCreated,
                                         eventDetail.Id,
                                         $"{eventDetail.UserId}",
                                         m.Value,
                                         contextJoined
                                         ));
                    }
                }
            }
        }
    /// <summary>
    /// Gets a List of int[N_BOOT_VALS] values representing the boot times.
    /// <list type="bullet">
    /// <item>0: BootStartTime</item>
    /// <item>1: BootTime</item>
    /// <item>2: MainPathBootTime</item>
    /// <item>3: BootPostBootTime</item>
    /// </list>
    /// </summary>
    /// <returns>The List.</returns>
    public static List <String[]> getBootTimes()
    {
        //String queryString = "*[System/Level=2]"; // XPATH Query
        String   queryString = "*"; // XPATH Query
        String   logName     = "Microsoft-Windows-Diagnostics-Performance/Operational";
        PathType pathType    = PathType.LogName;

        List <String[]> list        = new List <String[]>();
        EventLogQuery   eventsQuery = new EventLogQuery(logName, pathType, queryString);
        int             nItems      = 0;

        try {
            EventLogReader logReader = new EventLogReader(eventsQuery);
            for (EventRecord eventInstance = logReader.ReadEvent();
                 eventInstance != null; eventInstance = logReader.ReadEvent())
            {
                if (eventInstance.Id != 100)
                {
                    continue;
                }
                String[] vals = new String[N_BOOT_VALS];
                list.Add(vals);
                String      xml = eventInstance.ToXml();
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
                // Assign a prefix to allow accessing the namespace. Select without a namespace
                // gives only items not in a namespace.  All of ours are in the
                // http://schemas.microsoft.com/win/2004/08/events/event namespace.  Thus,
                // we need to specify the namespace.
                XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
                namespaceManager.AddNamespace("ms",
                                              "http://schemas.microsoft.com/win/2004/08/events/event");
                XPathNavigator nav = doc.CreateNavigator();

                XPathNodeIterator iter;
                int count;
                for (int i = 0; i < N_BOOT_VALS; i++)
                {
                    iter =
                        nav.Select("/ms:Event/ms:EventData/ms:Data[@Name='" + BOOT_DATA_NAMES[i] + "']",
                                   namespaceManager);
                    count = iter.Count;
                    if (count == 0)
                    {
                        vals[i] = "NA";
                    }
                    else
                    {
                        iter.MoveNext();
                        vals[i] = iter.Current.Value;
                    }
                }
                nItems++;
            }
        } 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(list);
    }
Ejemplo n.º 6
0
        public static void Main(string[] args)
        {
            int      exitCode         = 0;
            String   path             = "";
            String   query            = "*";
            bool     reverseDirection = false;
            UInt32   count            = UInt32.MaxValue;
            String   format           = "xml";
            PathType pathType         = PathType.LogName;

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

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

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

                    switch (words[0])
                    {
                    case "logfile":
                    case "lf":
                        pathType = PathType.FilePath;
                        break;

                    case "query":
                    case "q":
                        query = words[1];
                        break;

                    case "reversedirection":
                    case "rd":
                        reverseDirection = true;
                        break;

                    case "count":
                    case "c":
                        count = Convert.ToUInt32(words[1], CultureInfo.InvariantCulture);
                        break;

                    case "format":
                    case "f":
                        format = words[1].ToLower(CultureInfo.InvariantCulture);
                        if (format != "text" && format != "xml")
                        {
                            throw (new Exception(String.Format(CultureInfo.InvariantCulture, "Unrecognized format option: {0}.", format)));
                        }
                        break;

                    default:
                        throw (new Exception(String.Format(CultureInfo.InvariantCulture, "Unrecognized parameter option: {0}.", words[0])));
                    }
                }

                //
                // Query the event log.
                //
                EventLogQuery queryObj = new EventLogQuery(path, pathType, query);
                queryObj.ReverseDirection    = reverseDirection;
                queryObj.TolerateQueryErrors = true;  // Continue to read events even if an error occurs.

                EventLogReader reader  = new EventLogReader(queryObj);
                TimeSpan       timeout = new TimeSpan(0, 0, 5);

                EventRecord eventRecord = null;
                UInt32      eventsRead  = 0;
                while (((eventRecord = reader.ReadEvent(timeout)) != null) && (eventsRead++ < count))
                {
                    if (format == "xml")
                    {
                        Console.WriteLine("\n" + eventRecord.ToXml());
                    }
                    else if (format == "text")
                    {
                        Console.WriteLine("Source:\t\t" + eventRecord.ProviderName);
                        Console.WriteLine("Description:\t" + eventRecord.FormatDescription() + "\n");
                    }
                }
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("You do not have the correct permissions. " +
                                  "Try re-running the sample with administrator privileges.\n" + e.ToString());
                exitCode = 1;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                exitCode = 1;
            }
            Environment.Exit(exitCode);
        }
Ejemplo n.º 7
0
        public void CollectWinRMEvents()
        {
            //Check if log path is created
            if (!(Directory.Exists(RemoteNotifyLogsPath)))
            {
                Directory.CreateDirectory(RemoteNotifyLogsPath);
            }

            //Check if log is created
            if (!(File.Exists(RemoteNotifyLogsPath + "\\" + LogName)))
            {
                //create CSV File and add Header column names
                using (StreamWriter writer = File.CreateText(RemoteNotifyLogsPath + "\\" + LogName))
                {
                    writer.WriteLine("TimeGenerated,TimeLogged,TimeCollectedByRemoteNotify,InstanceID,MachineName,Message,SourceApplication,UserResponsible,State,OwningPID,OwningProcessName,ConnectionGuid");
                }
            }

            while (true)
            {
                try
                {
                    //Have it run every second
                    Thread.Sleep(1000);

                    //Check if windows log exists
                    if (File.Exists(WindowsLogDirectory + "\\" + "Microsoft-Windows-WinRM%4Operational.evtx"))
                    {
                        String        LastRecordedEventTime = LastLogCollectedTime();
                        EventLogQuery WinRMEventLogQuery;

                        if (LastRecordedEventTime == "")
                        {
                            WinRMEventLogQuery = new EventLogQuery(WindowsLogDirectory + "\\" + "Microsoft-Windows-WinRM%4Operational.evtx", PathType.FilePath);
                            bool test = File.Exists(WindowsLogDirectory + "\\" + "Microsoft-Windows-WinRM%4Operational.evtx");
                        }
                        else
                        {
                            // Only return events since last recorded event
                            String QueryString = "*[System[TimeCreated[@SystemTime >= \'" + LastRecordedEventTime + "\']]]";
                            WinRMEventLogQuery = new EventLogQuery(WindowsLogDirectory + "\\" + "Microsoft-Windows-WinRM%4Operational.evtx", PathType.FilePath, QueryString);
                            bool test = File.Exists(WindowsLogDirectory + "\\" + "Microsoft-Windows-WinRM%4Operational.evtx");
                        }

                        EventLogReader logReader;
                        try
                        {
                            // Query the log and create a stream of selected events
                            logReader = new EventLogReader(WinRMEventLogQuery);
                        }
                        catch (EventLogNotFoundException)
                        {
                            return; //Failed to query the WinRM log!
                        }

                        for (EventRecord eventInstance = logReader.ReadEvent(); eventInstance != null; eventInstance = logReader.ReadEvent())
                        {
                            String eventXml = eventInstance.ToXml();
                            Console.WriteLine(eventXml);
                            using (StreamWriter writer = new StreamWriter(RemoteNotifyLogsPath + "\\" + LogName, true))
                            {
                                writer.WriteLine(eventXml);
                            }
                        }

                        //Write to log if originating by Winrm
                        //using (StreamWriter writer = new StreamWriter(RemoteNotifyLogsPath + "\\" + LogName, true))
                        //{
                        //    writer.WriteLine(LogEntry.TimeGenerated.ToString() + "," +
                        //            DateTime.Now.ToString() + "," +
                        //            LogEntry.TimeWritten.ToString() + "," +
                        //            LogEntry.InstanceId.ToString() + "," +
                        //            LogEntry.MachineName.ToString() + "," +
                        //            LogEntry.Message.ToString() + "," +
                        //            LogEntry.Source.ToString() + "," +
                        //            LogEntry.UserName.ToString() + "," +
                        //             + "," +
                        //            Process.GetProcessById(checked((int)Connection.Connection.owningPid)).ProcessName + "," +
                        //            Connection.ConnectionGuid.ToString()
                        //            );
                        //}
                    }
                }
                catch (ThreadInterruptedException)
                {
                    return;
                }
            }
        }
Ejemplo n.º 8
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);
            }
        }
    }
 // Token: 0x060000DE RID: 222 RVA: 0x000051E8 File Offset: 0x000033E8
 public CrimsonChannelReader(EventLogQuery query, EventLogReaderAdapter adapter = null)
 {
     this.Query  = query;
     this.reader = (adapter ?? new EventLogReaderAdapter(this.Query));
 }
Ejemplo n.º 10
0
        public static List <RemoteLogonHistory> GetLogonHistory()
        {
            var logonHistory = new List <RemoteLogonHistory>();

            Result = new TaskResult();

            const int logonEventId   = 4624;
            const int logoffEventIdA = 4634;
            const int logoffEventIdB = 4647;
            const int landeskRemoteControlEventId = 2;

            string queryString =
                "<QueryList><Query Id='1'>" +
                "<Select Path='Security'>" +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logonEventId + ")]] and " +
                "*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] and " +
                "*[EventData[Data[@Name='LogonGuid'] != '{00000000-0000-0000-0000-000000000000}']] and " +
                "*[EventData[Data[@Name='LogonProcessName'] != 'seclogo']]" +
                "</Select>" +
                "<Select Path='Security'>" +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logonEventId + ")]] and " +
                "*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] and " +
                "*[EventData[Data[@Name='TargetDomainName'] = '" + RemoteLogonSession.ComputerName.ToUpper().Trim() + "']]" +
                "</Select>" +
                "<Select Path='Security'>" +
                //"*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                //"(EventID=" + logoffEventIdA + ")]] and " +
                //"*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] or " +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logoffEventIdB + ")]]" +
                "</Select>" +
                "<Select Path='Application'>" +
                "*[System[Provider[@Name='LANDESK Remote Control Service'] and (EventID=" + landeskRemoteControlEventId + ")]]" +
                "</Select>" +
                "</Query></QueryList>";

            try
            {
                var eventLogSession = new EventLogSession(RemoteLogonSession.ComputerName);
                var eventLogQuery   = new EventLogQuery("Security", PathType.LogName, queryString);
                eventLogQuery.ReverseDirection = true;
                eventLogQuery.Session          = eventLogSession;

                using (
                    GlobalVar.UseAlternateCredentials
                        ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                        : null)
                    using (var eventLogReader = new EventLogReader(eventLogQuery))
                    {
                        for (EventRecord eventLogRecord = eventLogReader.ReadEvent(); null != eventLogRecord; eventLogRecord = eventLogReader.ReadEvent())
                        {
                            string regexString;

                            switch (eventLogRecord.Id)
                            {
                            case (logonEventId):
                                regexString = @"An account was successfully logged on.*Logon Type:\s+(?<logonType>.*?)\r" +
                                              @".*\tAccount Name:\s+(?<accountName>.*?)\r" +
                                              @".*\tAccount Domain:\s+(?<accountDomain>.*?)\r" +
                                              @".*Network Information:.*Source Network Address:\s+(?<sourceIpAddress>.*?)\r";
                                break;

                            case (landeskRemoteControlEventId):
                                regexString = @"^Remote control action: (?<controlAction>\w+?) Remote Control  Initiated from (?<sourceHostname>.*?) by user " +
                                              @"(?<accountName>.*?), Security Type";
                                break;

                            case (logoffEventIdA):
                                regexString = @"An account was logged off" +
                                              @".*Subject:.*Account Name:\s+(?<accountName>.*?)\r" +
                                              @".*Account Domain:\s+(?<accountDomain>.*?)\r" +
                                              @".*Logon Type:\s+(?<logonType>.*?)\r";
                                break;

                            case (logoffEventIdB):
                                regexString = @"User initiated logoff" +
                                              @".*Subject:.*Account Name:\s+(?<accountName>.*?)\r" +
                                              @".*Account Domain:\s+(?<accountDomain>.*?)\r";
                                break;

                            default:
                                regexString = string.Empty;
                                break;
                            }
                            var match = Regex.Match(eventLogRecord.FormatDescription(), regexString, RegexOptions.Singleline);

                            if (match.Success)
                            {
                                switch (eventLogRecord.Id)
                                {
                                case (logonEventId):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = match.Groups["logonType"].Value,
                                        IpAddress   = match.Groups["sourceIpAddress"].Value
                                    });
                                    break;

                                case (landeskRemoteControlEventId):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonDomain = string.Empty,
                                        LogonType   = "LANDesk",
                                        LogonAction = match.Groups["controlAction"].Value,
                                        IpAddress   = match.Groups["sourceHostname"].Value
                                    });
                                    break;

                                case (logoffEventIdA):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = "Logoff"
                                    });
                                    break;

                                case (logoffEventIdB):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = "Logoff"
                                    });
                                    break;
                                }
                            }
                        }

                        Result.DidTaskSucceed = true;
                    }
            }
            catch (UnauthorizedAccessException)
            {
                Result.DidTaskSucceed = false;
                Result.MessageBody    = "This feature is currently only supported on Windows Vista and Server 2008 or higher.";
            }
            catch
            {
                Result.DidTaskSucceed = false;
            }

            return(logonHistory);
        }
Ejemplo n.º 11
0
        private void InitWatcher()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); // need to fix MS bug

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

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

            xq.Append("*");

            StringBuilder paths = new StringBuilder();

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

            StringBuilder ls = new StringBuilder();

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

            StringBuilder iid = new StringBuilder();

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

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


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

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

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

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

                xq.Append("]]");
            }


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

            watcher = new EventLogWatcher(subscriptionQuery);
            watcher.EventRecordWritten += new EventHandler <EventRecordWrittenEventArgs>(EventLogEventRead);
        }
Ejemplo n.º 12
0
        public void OnSessionChange(SessionChangeDescription sessionChange)
        {
            var wtsSessionId = sessionChange.SessionId;
            var logprefix    = "SessionMon #" + wtsSessionId.ToString("D2") + " [" + sessionChange.Reason.ToString() + "]: ";

            //EventLog.WriteEntry("OnSessionChange", changeDescription.Reason.ToString() + " Session ID: " + changeDescription.SessionId.ToString());
            Log(logprefix + "@");
            WTS.SessionInfo wtsInfo;
            var             utcNow = DateTime.UtcNow;

            try
            {
                switch (sessionChange.Reason)
                {
                // SessionLogon
                case SessionChangeReason.SessionLogon:
                    Thread.Sleep(3000 * 1);       // Wait for session to be logged in event log
                    var provider = "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational";
                    var fromUtc  = utcNow.Subtract(TimeSpan.FromMinutes(1));
                    //var toUtc = utcNow.Add(TimeSpan.FromMinutes(1));
                    var query = "*[" +
                                "(System/EventID=21 and UserData/EventXML/SessionID=" + wtsSessionId + ")" +
                                " and " +
                                "System[TimeCreated[@SystemTime>'" + fromUtc.ToString("yyyy-MM-dd") + "T" + fromUtc.ToString("HH:mm:ss") + ".000000000Z" + "']]" +

                                /*" and " +
                                 * "System[TimeCreated[@SystemTime<'" + toUtc.ToString("yyyy-MM-dd") + "T" + toUtc.ToString("HH:mm:ss") + ".000000000Z" + "']] " +*/
                                "]";
                    var eventsQuery = new EventLogQuery(provider, PathType.LogName, query);
                    {
                        var logReader = new EventLogReader(eventsQuery);
                        for (var evt = logReader.ReadEvent(); evt != null; evt = logReader.ReadEvent())
                        {
                            var xmldoc = new XmlDocument();
                            var xml    = evt.ToXml();
                            var ns     = new XmlNamespaceManager(xmldoc.NameTable);
                            //ns.AddNamespace("ns", "http://schemas.microsoft.com/win/2004/08/events/event");
                            ns.AddNamespace("ns", "Event_NS");
                            xmldoc.LoadXml(xml);
                            var nodes = xmldoc.SelectNodes("//ns:*", ns);
                            if (nodes != null)
                            {
                                int    _wtsSessionId = -1;
                                string user = null, addr = null;
                                for (int i = 0; i < nodes.Count; i++)
                                {
                                    if (nodes[i].Name == "SessionID")
                                    {
                                        int.TryParse(nodes[i].InnerText, out _wtsSessionId);
                                    }
                                    if (nodes[i].Name == "User")
                                    {
                                        user = nodes[i].InnerText;
                                    }
                                    if (nodes[i].Name == "Address")
                                    {
                                        addr = nodes[i].InnerText;
                                    }
                                }
                                Log(logprefix + "session=" + _wtsSessionId + ", user="******", addr=" + addr);
                                if (_wtsSessionId != -1)
                                {
                                    wtsInfo = WTS.QuerySessionInfo(_wtsSessionId);
                                    if (wtsInfo != null)
                                    {
                                        using (var db = new LiteDatabase("Filename=" + Utils.MyPath("RdpMon.db") + ";utc=true"))
                                        {
                                            var table   = db.GetCollection <Session>("Session");
                                            var session = new Session
                                            {
                                                SessionUid   = Session.GetSessionUid(_wtsSessionId, wtsInfo.LogonTime),
                                                WtsSessionId = _wtsSessionId,
                                                Start        = wtsInfo.LogonTime,
                                                End          = null,
                                                User         = wtsInfo.UserName,
                                                Addr         = addr,
                                                Flags        = 0,
                                            };
                                            table.Insert(session);
                                            DbProps.Set(db, "LastSessionChange", DateTime.UtcNow);
                                        }
                                    }
                                    else
                                    {
                                        Log(logprefix + "* could not find WTS session #" + _wtsSessionId);
                                    }
                                }
                                else
                                {
                                    Log(logprefix + "* could not parse session ID from event log: " + xml);
                                }
                            }
                            else
                            {
                                Log(logprefix + "* could not read event log: " + xml);
                            }
                        }
                    }
                    break;

                // SessionLogoff
                case SessionChangeReason.SessionLogoff:
                    wtsInfo = WTS.QuerySessionInfo(wtsSessionId);
                    if (wtsInfo != null)
                    {
                        using (var db = new LiteDatabase("Filename=" + Utils.MyPath("RdpMon.db") + ";utc=true"))
                        {
                            var table      = db.GetCollection <Session>("Session");
                            var sessionUID = Session.GetSessionUid(wtsSessionId, wtsInfo.LogonTime);
                            var session    = table.FindById(sessionUID);
                            if (session != null)
                            {
                                session.End = DateTime.UtcNow;
                                table.Update(session);
                            }
                            DbProps.Set(db, "LastSessionChange", DateTime.UtcNow);
                        }
                    }
                    else
                    {
                        Log(logprefix + "* could not find WTS session #" + wtsSessionId);
                    }
                    break;

                // Other events
                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Log(logprefix + "* exception: " + ex.ToString());
            }
        }
        }  //ETWTraceInBackground_Start_SYSTEM()

        private void ETWTraceInBackground_DoWork_SYSTEM(object sender, DoWorkEventArgs e)
        {
            // This is the background thread
            int              count    = 0;
            string           etwclass = e.Argument as string;
            BackgroundWorker worker   = sender as BackgroundWorker;

            Thread.CurrentThread.Name = "ETWReaderSYSTEM";
            //Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;

            try
            {
                string         sQuery                 = "*[System/Level>0]";
                EventLogQuery  Q_Operational          = new EventLogQuery(etwclass, PathType.LogName, sQuery);
                EventBookmark  Ev_OperationalBookmark = null;
                EventLogReader R_Operational;
                R_Operational = new EventLogReader(Q_Operational); // Walk through existing list to create a bookmark
                R_Operational.Seek(System.IO.SeekOrigin.End, 0);
                for (EventRecord eventInstance = R_Operational.ReadEvent();
                     null != eventInstance;
                     eventInstance = R_Operational.ReadEvent())
                {
                    Ev_OperationalBookmark = eventInstance.Bookmark;
                }
                R_Operational.Dispose();
                WaitingForEventStart_SYSTEM = false;

                worker.ReportProgress(count++);

                while (!worker.CancellationPending && !PleaseStopCollecting)
                {
                    Thread.Sleep(1000);
                    R_Operational = new EventLogReader(Q_Operational, Ev_OperationalBookmark);
                    for (EventRecord eventInstance = R_Operational.ReadEvent();
                         null != eventInstance;
                         eventInstance = R_Operational.ReadEvent())
                    {
                        Ev_OperationalBookmark = eventInstance.Bookmark;
                        try
                        {
                            DateTime  et    = eventInstance.TimeCreated.GetValueOrDefault();
                            EventItem eItem = new EventItem((int)et.Ticks, et.Ticks, et.Ticks, et, eventInstance.ProcessId.ToString(), (int)eventInstance.ProcessId, (int)eventInstance.ThreadId,
                                                            eventInstance.LogName, "System", eventInstance.Id.ToString(), eventInstance.LevelDisplayName, eventInstance.FormatDescription(), "");
                            //SYSTEM_ITEM item = new SYSTEM_ITEM(eventInstance.LevelDisplayName, eventInstance.FormatDescription(), eventInstance.ProviderName, eventInstance.Id, eventInstance.ProcessId);
                            worker.ReportProgress(count++, eItem);
                        }
                        catch
                        {
                            // app provider might be virtual or missing
                            string leveldisplayname = "";
                            string stuff            = "Formatter not available. Details:";
                            int    ProcessId        = -1;
                            int    ThreadId         = -1;
                            switch (eventInstance.Level)
                            {
                            case 1:
                                leveldisplayname = "Critical";
                                break;

                            case 2:
                                leveldisplayname = "Error";
                                break;

                            case 3:
                                leveldisplayname = "Warning";
                                break;

                            case 4:
                                leveldisplayname = "Information";
                                break;

                            default:
                                break;
                            }
                            foreach (EventProperty p in eventInstance.Properties)
                            {
                                stuff += p.Value.ToString() + "  ";
                            }
                            if (eventInstance.ProcessId != null)
                            {
                                ProcessId = (int)eventInstance.ProcessId;
                            }
                            if (eventInstance.ThreadId != null)
                            {
                                ThreadId = (int)eventInstance.ThreadId;
                            }
                            DateTime  et    = eventInstance.TimeCreated.GetValueOrDefault();
                            EventItem eItem = new EventItem((int)et.Ticks, et.Ticks, et.Ticks, et, eventInstance.ProcessId.ToString(), (int)eventInstance.ProcessId, (int)eventInstance.ThreadId,
                                                            eventInstance.LogName, "System", eventInstance.Id.ToString(), leveldisplayname, stuff, "");
                            worker.ReportProgress(count++, eItem);
                        }
                    }
                    R_Operational.Dispose();
                }
            }
            catch
            {
                WaitingForEventStart_SYSTEM = false;
            }
        } // ETWTraceInBackground_DoWork_SYSTEM()
Ejemplo n.º 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");
                }
            }
        }
Ejemplo n.º 15
0
        public void EventLogRecord_CheckProperties_RemainSame()
        {
            if (PlatformDetection.IsWindows7) // Null events in PowerShell log
            {
                return;
            }

            SecurityIdentifier userId;
            byte?             version, level;
            short?            opcode;
            Guid?             providerId, activityId, relatedActivityId;
            int?              processId, threadId, qualifiers, task;
            long?             keywords, recordId;
            string            providerName, machineName, containerLog;
            DateTime?         timeCreated;
            IEnumerable <int> matchedQueryIds;
            EventBookmark     bookmark, bookmarkArg = Helpers.GetBookmark("Application", PathType.LogName);

            var query = new EventLogQuery("Application", PathType.LogName, "*[System]")
            {
                ReverseDirection = true
            };
            var eventLog = new EventLogReader(query, bookmarkArg);

            using (eventLog)
            {
                using (var record = (EventLogRecord)eventLog.ReadEvent())
                {
                    userId            = record.UserId;
                    version           = record.Version;
                    opcode            = record.Opcode;
                    providerId        = record.ProviderId;
                    processId         = record.ProcessId;
                    recordId          = record.RecordId;
                    threadId          = record.ThreadId;
                    qualifiers        = record.Qualifiers;
                    level             = record.Level;
                    keywords          = record.Keywords;
                    task              = record.Task;
                    providerName      = record.ProviderName;
                    machineName       = record.MachineName;
                    timeCreated       = record.TimeCreated;
                    containerLog      = record.ContainerLog;
                    matchedQueryIds   = record.MatchedQueryIds;
                    activityId        = record.ActivityId;
                    relatedActivityId = record.RelatedActivityId;
                    bookmark          = record.Bookmark;
                }
            }

            using (eventLog = new EventLogReader(query, bookmarkArg))
            {
                using (var record = (EventLogRecord)eventLog.ReadEvent())
                {
                    Assert.Equal(userId, record.UserId);
                    Assert.Equal(version, record.Version);
                    Assert.Equal(opcode, record.Opcode);
                    Assert.Equal(providerId, record.ProviderId);
                    Assert.Equal(processId, record.ProcessId);
                    Assert.Equal(recordId, record.RecordId);
                    Assert.Equal(threadId, record.ThreadId);
                    Assert.Equal(qualifiers, record.Qualifiers);
                    Assert.Equal(level, record.Level);
                    Assert.Equal(keywords, record.Keywords);
                    Assert.Equal(task, record.Task);
                    Assert.Equal(providerName, record.ProviderName);
                    Assert.Equal(machineName, record.MachineName);
                    Assert.Equal(timeCreated, record.TimeCreated);
                    Assert.Equal(containerLog, record.ContainerLog);
                    Assert.Equal(matchedQueryIds, record.MatchedQueryIds);
                    Assert.Equal(activityId, record.ActivityId);
                    Assert.Equal(relatedActivityId, record.RelatedActivityId);
                    Assert.NotNull(record.Bookmark);
                    Assert.NotEqual(bookmark, record.Bookmark);
                }
            }
        }
Ejemplo n.º 16
0
        private static void GetEvents(
            string filePath,
            string computerFqdn,
            string logName,
            IReadOnlyList <int> eventIds,
            IReadOnlyList <int> eventIdToSuppress,
            DateTime startDate,
            DateTime endDate)
        {
            Console.WriteLine("{0} - {1} FilePath: {2} Computer: {3} LogName: {4} EventIds: {5} EventIdsToSuppress: {6} Start Date: {7} End Date: {8}",
                              DateTime.Now.YMDHMSFriendly(), ObjectExtensions.CurrentMethodName(),
                              !string.IsNullOrWhiteSpace(filePath) ? filePath : "N/A",
                              !string.IsNullOrWhiteSpace(computerFqdn) ? computerFqdn : "N/A",
                              !string.IsNullOrWhiteSpace(logName) ? logName : "N/A",
                              (eventIds.Count > 0) ? eventIds.ToDelimitedString() : "<All Events>",
                              (eventIdToSuppress.Count > 0) ? eventIdToSuppress.ToDelimitedString() : "<No Events>",
                              startDate.YMDFriendly(), endDate.YMDFriendly());

            long eventsProcessed  = 0;
            var  stopwatch        = Stopwatch.StartNew();
            var  eventReadTimeout = TimeSpan.FromMinutes(5);

            if (!string.IsNullOrWhiteSpace(filePath))
            {
                if (!filePath.EndsWith(".EVTX", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine($"{DateTime.Now.YMDHMSFriendly()} - {ObjectExtensions.CurrentMethodName()} File: {filePath} if not .XML, file must be an .EVTX file type. Exiting.");
                    return;
                }
            }

            try {
                #region Construct event query filter
                var path = !string.IsNullOrWhiteSpace(logName)
                    ? logName
                    : filePath;

                var eventIdsFilter = new StringBuilder();
                if (eventIds.Count > 0)
                {
                    eventIdsFilter.Append("(");
                    for (int index = 0; index < eventIds.Count; index++)
                    {
                        eventIdsFilter.Append($"EventID={eventIds[index]}");
                        if (index < eventIds.Count - 1)
                        {
                            eventIdsFilter.Append(" or ");
                        }
                    }
                    eventIdsFilter.Append(") and ");
                }

                var query = $"*[System[{eventIdsFilter.ToString()}TimeCreated[@SystemTime&gt;='{startDate.YMDFriendly()}T00:00:00.000Z' and @SystemTime&lt;'{endDate.Add(TimeSpan.FromDays(1)).YMDFriendly()}T00:00:00.000Z']]]";

                var suppressionQuery = string.Empty;
                if (eventIdToSuppress.Count > 0)
                {
                    var eventIdsToSuppressFilter = new StringBuilder();
                    eventIdsToSuppressFilter.Append("(");
                    for (int index = 0; index < eventIdToSuppress.Count; index++)
                    {
                        eventIdsToSuppressFilter.Append($"EventID={eventIdToSuppress[index]}");
                        if (index < eventIdToSuppress.Count - 1)
                        {
                            eventIdsToSuppressFilter.Append(" or ");
                        }
                    }
                    eventIdsToSuppressFilter.Append(")");

                    suppressionQuery = $"<Suppress Path=\"{path}\">*[System[{eventIdsToSuppressFilter.ToString()}]]</Suppress>";
                }

                var fullQuery = new StringBuilder();

                fullQuery.Append("<QueryList>");
                fullQuery.Append($"<Query Id=\"0\" Path=\"{path}\">");
                fullQuery.Append($"<Select Path=\"{path}\">{query}</Select>");
                if (!string.IsNullOrWhiteSpace(suppressionQuery))
                {
                    fullQuery.Append(suppressionQuery);
                }
                fullQuery.Append("</Query>");
                fullQuery.Append("</QueryList>");

                Console.WriteLine($"{DateTime.Now.YMDHMSFriendly()} - {ObjectExtensions.CurrentMethodName()} Event query: {fullQuery}");
                #endregion

                EventLogQuery   eventLogQuery = null;
                EventLogSession session       = null;

                try {
                    if (!string.IsNullOrWhiteSpace(computerFqdn))
                    {
                        eventLogQuery         = new EventLogQuery(logName, PathType.LogName, fullQuery.ToString());
                        session               = new EventLogSession(computerFqdn);
                        eventLogQuery.Session = session;
                    }
                    else
                    {
                        eventLogQuery = new EventLogQuery(filePath, PathType.FilePath, fullQuery.ToString());
                    }

                    eventLogQuery.ReverseDirection = EventLogQueryReverseDirection;

                    using (var eventLogReader = new EventLogReader(eventLogQuery)) {
                        EventRecord eventRecord    = null;
                        string      eventRecordXml = string.Empty;

                        do
                        {
                            eventRecord    = null;
                            eventRecordXml = string.Empty;

                            #region Read event from event log
                            try {
                                eventRecord = eventLogReader.ReadEvent(eventReadTimeout);
                                if (eventRecord == null)
                                {
                                    break;
                                }
                                eventsProcessed++;
                                eventRecordXml = eventRecord.ToXml();
                                if (string.IsNullOrWhiteSpace(eventRecordXml))
                                {
                                    continue;
                                }
                                if (GetEventFromXml(eventRecordXml) != 0)
                                {
                                    continue;
                                }
                            }
                            catch (XmlException e) {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"Error parsing event record Xml:{eventRecordXml ?? "NULL"}");
                                Console.WriteLine(e.VerboseExceptionString());
                                Console.ResetColor();
                                continue;
                            }
                            catch (EventLogException e) {
                                if (Regex.IsMatch(e.Message, "The array bounds are invalid", RegexOptions.IgnoreCase))
                                {
                                    continue;
                                }
                                if (Regex.IsMatch(e.Message, "The data area passed to a system call is too small", RegexOptions.IgnoreCase))
                                {
                                    continue;
                                }
                                throw;
                            }
                            #endregion

                            #region Log statistics
                            if (eventsProcessed % 5000 == 0)
                            {
                                Console.WriteLine($"{DateTime.Now.YMDHMSFriendly()} Events processed: {eventsProcessed}");
                            }
                            #endregion
                        } while (eventRecord != null);
                    }
                }
                finally {
                    if (session != null)
                    {
                        try {
                            session.Dispose();
                        }
                        catch { }
                    }
                }
            }
            catch (Exception e) {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error parsing events");
                Console.WriteLine(e.VerboseExceptionString());
                Console.ResetColor();
                throw;
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        ///
        /// </summary>
        protected void InitialStatusGet()
        {
            try
            {
                /** Leer la lista de eventos */
#if OLD_1
                EventLogQuery logquery = new EventLogQuery(LogName, FileInsteadLog ? PathType.FilePath : PathType.LogName);

                List <EventRecord> Entries = new List <EventRecord>();
                EventLogReader     elr     = new EventLogReader(logquery);
                EventRecord        entry;
                while ((entry = elr.ReadEvent()) != null)
                {
                    if (entry.Id == DownEventId || entry.Id == UpEventId)
                    {
                        Entries.Add(entry);
                    }
                }
#endif
#if OLD
                /** Separarlos */
                List <EventRecord> last_lan1_ev_down = Entries.Where(e => DownEventId == (e.Id) && e.ToXml().Contains(Lan1Device)).OrderByDescending(e => e.TimeCreated).ToList();
                List <EventRecord> last_lan2_ev_down = Entries.Where(e => DownEventId == (e.Id) && e.ToXml().Contains(Lan2Device)).OrderByDescending(e => e.TimeCreated).ToList();
                List <EventRecord> last_lan1_ev_up   = Entries.Where(e => UpEventId == (e.Id) && e.ToXml().Contains(Lan1Device)).OrderByDescending(e => e.TimeCreated).ToList();
                List <EventRecord> last_lan2_ev_up   = Entries.Where(e => UpEventId == (e.Id) && e.ToXml().Contains(Lan2Device)).OrderByDescending(e => e.TimeCreated).ToList();

                long last_lan1_down = last_lan1_ev_down.Count == 0 ? DateTime.MinValue.Ticks : last_lan1_ev_down[0].TimeCreated.Value.Ticks;
                long last_lan2_down = last_lan2_ev_down.Count == 0 ? DateTime.MinValue.Ticks : last_lan2_ev_down[0].TimeCreated.Value.Ticks;
                long last_lan1_up   = last_lan1_ev_up.Count == 0 ? DateTime.MinValue.Ticks : last_lan1_ev_up[0].TimeCreated.Value.Ticks;
                long last_lan2_up   = last_lan2_ev_up.Count == 0 ? DateTime.MinValue.Ticks : last_lan2_ev_up[0].TimeCreated.Value.Ticks;

                Lan1Status = last_lan1_up > last_lan1_down ? LanStatus.Up : LanStatus.Down;
                Lan2Status = last_lan2_up > last_lan2_down ? LanStatus.Up : LanStatus.Down;
#elif OLD_1
                for (int lan = 0; lan < NICList.Count; lan++)
                {
                    string             LanDevice        = NICList[lan].DeviceId;
                    List <EventRecord> last_lan_ev_down = Entries.Where(e => DownEventId == (e.Id) && e.ToXml().Contains(LanDevice)).OrderByDescending(e => e.TimeCreated).ToList();
                    List <EventRecord> last_lan_ev_up   = Entries.Where(e => UpEventId == (e.Id) && e.ToXml().Contains(LanDevice)).OrderByDescending(e => e.TimeCreated).ToList();

                    long last_lan_down = last_lan_ev_down.Count == 0 ? DateTime.MinValue.Ticks : last_lan_ev_down[0].TimeCreated.Value.Ticks;
                    long last_lan_up   = last_lan_ev_up.Count == 0 ? DateTime.MinValue.Ticks : last_lan_ev_up[0].TimeCreated.Value.Ticks;

                    NICList[lan].Status = last_lan_up > last_lan_down ? LanStatus.Up : LanStatus.Down;
                }
#else
                for (int lan = 0; lan < NICList.Count; lan++)
                {
                    string             LanDevice        = NICList[lan].DeviceId;
                    List <EventRecord> last_lan_ev_down = _LogEntries.Where(e => DownEventId == (e.Id) && e.ToXml().Contains(LanDevice)).OrderByDescending(e => e.TimeCreated).ToList();
                    List <EventRecord> last_lan_ev_up   = _LogEntries.Where(e => UpEventId == (e.Id) && e.ToXml().Contains(LanDevice)).OrderByDescending(e => e.TimeCreated).ToList();

                    long last_lan_down = last_lan_ev_down.Count == 0 ? DateTime.MinValue.Ticks : last_lan_ev_down[0].TimeCreated.Value.Ticks;
                    long last_lan_up   = last_lan_ev_up.Count == 0 ? DateTime.MinValue.Ticks : last_lan_ev_up[0].TimeCreated.Value.Ticks;

                    NICList[lan].Status = last_lan_up > last_lan_down ? LanStatus.Up : LanStatus.Down;
                }
#endif
            }
            catch (Exception x)
            {
                _Logger.Error(String.Format("NICEventMonitor InitialStatusGet Exception {0}", x.Message), x);
                RaiseMessageError(x.Message);
            }
        }
Ejemplo n.º 18
0
 internal EventLogReaderAdapter(EventLogQuery query)
 {
     this.reader = new EventLogReader(query);
 }
Ejemplo n.º 19
0
        private static bool GetEntries(ref List <EventEntry> eventList, string logName, EventLogSession session, DateTime startTime, DateTime endTime, int maxLevel, bool bQuiet)
        {         // read all event log entries matching in EventEntry list
            string eventQuery;

            if (maxLevel == 0)
            {
                // query for all information levels
                eventQuery = string.Format("*[System/TimeCreated/@SystemTime > '{0}'] and *[System/TimeCreated/@SystemTime <= '{1}']", startTime.ToUniversalTime().ToString("o"), endTime.ToUniversalTime().ToString("o"));
            }
            else
            {
                // level: LogAlways - 0, Critical - 1, Error - 2, Warning - 3, Informational - 4, Verbose - 5
                // there are different levels for auditing logs!
                eventQuery = string.Format("*[System/TimeCreated/@SystemTime > '{0}'] and *[System/TimeCreated/@SystemTime <= '{1}'] and *[System/Level <= {2}]", startTime.ToUniversalTime().ToString("o"), endTime.ToUniversalTime().ToString("o"), maxLevel.ToString());
            }

            // define event log query
            EventLogQuery eventLogQuery = new EventLogQuery(logName, PathType.LogName, eventQuery);

            eventLogQuery.Session = session;

            try
            {             // start query
                EventLogReader eventLogReader = new EventLogReader(eventLogQuery);

                int count = 0;
                for (EventRecord eventRecord = eventLogReader.ReadEvent(); eventRecord != null; eventRecord = eventLogReader.ReadEvent())
                {                 // enumerate all found events
                    count++;
                    // read Event details
                    DateTime timeCreated = DateTime.Now;
                    if (eventRecord.TimeCreated.HasValue)
                    {
                        timeCreated = eventRecord.TimeCreated.Value;
                    }

                    string eventLevel;
                    try {
                        eventLevel = eventRecord.LevelDisplayName;
                        if (eventRecord.Level == 0)
                        {
                            eventLevel = "LogAlways";
                        }
                    }
                    catch {
                        eventLevel = "Unknown";
                    }

                    try
                    {
                        if (!String.IsNullOrEmpty(eventRecord.FormatDescription()))
                        {                         // create log entry in list
                            eventList.Add(new EventEntry(timeCreated, logName, eventRecord.Id, eventRecord.ProviderName, eventLevel, eventRecord.FormatDescription()));
                        }
                        else
                        {                         // description not available, try to interpret raw data
                            string rawDescription = "";
                            foreach (EventProperty eventProperty in eventRecord.Properties)
                            {
                                rawDescription += eventProperty.Value.ToString();
                            }
                            // create log entry in list
                            eventList.Add(new EventEntry(timeCreated, logName, eventRecord.Id, eventRecord.ProviderName, eventLevel, rawDescription));
                        }
                    }
                    catch (Exception e)
                    {                     // create log entry in list with error message
                        eventList.Add(new EventEntry(timeCreated, logName, eventRecord.Id, eventRecord.ProviderName, eventLevel, "### Error reading the event log entry: " + e.Message));
                    }
                }

                if (!bQuiet)
                {
                    Console.WriteLine("Processed event log \"" + logName + "\": " + count + " entries");
                }
                return(true);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error opening the event log \"" + logName + "\": " + e.Message);
                return(false);
            }
        }
Ejemplo n.º 20
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);
        }
Ejemplo n.º 21
0
        private void Run()
        {
            try
            {
                //Init Worker Thread
                LoadConfiguration();

                //prepare datastructures
                Dictionary <string, List <LogTask> > requiredEventTypesToLogTasks = new Dictionary <string, List <LogTask> >();
                foreach (LogTask l in _logTasks)
                {
                    foreach (string s in l.EventPath)
                    {
                        if (!requiredEventTypesToLogTasks.ContainsKey(s))
                        {
                            requiredEventTypesToLogTasks[s] = new List <LogTask>();
                        }

                        requiredEventTypesToLogTasks[s].Add(l);
                    }
                }

                var eventTypesToLastEvent        = new Dictionary <string, DateTime>();
                var eventTypesToMaxAge           = new Dictionary <string, int>();
                var eventTypesToNewEvents        = new Dictionary <string, List <EventRecord> >();
                var eventTypesToTimeFramedEvents = new Dictionary <string, List <EventRecord> >();

                //load structure so that only required events are read
                foreach (string requiredEventType in requiredEventTypesToLogTasks.Keys)
                {
                    eventTypesToLastEvent.Add(requiredEventType, DateTime.Now);
                    eventTypesToMaxAge.Add(requiredEventType, 0);
                    foreach (LogTask t in requiredEventTypesToLogTasks[requiredEventType])
                    {
                        if (!t.OnlyNew && eventTypesToMaxAge[requiredEventType] < t.EventAge)
                        {
                            eventTypesToMaxAge[requiredEventType] = t.EventAge;
                        }
                    }
                }


                //start monitoring the logs
                while (true)
                {
                    DateTime scanStart = DateTime.Now;

                    if (_verbose)
                    {
                        Dump("Scanning the logs now.", EventLogEntryType.Information, true);
                    }

                    DateTime referenceTimeForTimeFramedEvents = DateTime.Now;
                    try
                    {
                        eventTypesToNewEvents.Clear();
                        eventTypesToTimeFramedEvents.Clear();

                        //first read all relevant events (events that are required by any of the tasks)
                        foreach (string requiredEventType in requiredEventTypesToLogTasks.Keys)
                        {
                            eventTypesToNewEvents.Add(requiredEventType, new List <EventRecord>());
                            eventTypesToTimeFramedEvents.Add(requiredEventType, new List <EventRecord>());

                            var eventLogQuery = new EventLogQuery(requiredEventType, PathType.LogName)
                            {
                                ReverseDirection = true
                            };

                            try
                            {
                                var         eventLogReader = new EventLogReader(eventLogQuery);
                                EventRecord r;

                                while ((r = eventLogReader.ReadEvent()) != null)
                                {
                                    if (!r.TimeCreated.HasValue)
                                    {
                                        continue;
                                    }

                                    bool canbreak = false;

                                    //fill new event list
                                    if (r.TimeCreated > eventTypesToLastEvent[requiredEventType])
                                    {
                                        eventTypesToNewEvents[requiredEventType].Add(r);
                                        eventTypesToLastEvent[requiredEventType] = r.TimeCreated.Value;
                                    }
                                    else
                                    {
                                        canbreak = true;
                                    }

                                    //fill time framed event list
                                    if (r.TimeCreated > referenceTimeForTimeFramedEvents.Subtract(new TimeSpan(0, 0, eventTypesToMaxAge[requiredEventType])))
                                    {
                                        eventTypesToTimeFramedEvents[requiredEventType].Add(r);
                                    }
                                    else if (canbreak)
                                    {
                                        break;
                                    }
                                }
                            }
                            catch (EventLogNotFoundException)
                            {
                                Dump($"Event Log {requiredEventType} was not found, tasks that require these events will not work", EventLogEntryType.Warning);
                            }
                        }

                        if (_verbose)
                        {
                            Dump($"Scanning finished in {DateTime.Now.Subtract(scanStart).TotalMilliseconds}[ms] ", EventLogEntryType.Information, true);
                        }

                        //then supply the events to the requesting tasks
                        foreach (string key in requiredEventTypesToLogTasks.Keys)
                        {
                            foreach (LogTask t in requiredEventTypesToLogTasks[key])
                            {
                                if (t.OnlyNew)
                                {
                                    t.ProvideEvents(eventTypesToNewEvents[key]);
                                }
                                else
                                {
                                    var eventsForThisTask = new List <EventRecord>();
                                    foreach (EventRecord e in eventTypesToTimeFramedEvents[key])
                                    {
                                        if (e.TimeCreated > referenceTimeForTimeFramedEvents.Subtract(new TimeSpan(0, 0, t.EventAge)))
                                        {
                                            eventsForThisTask.Add(e);
                                        }
                                    }

                                    if (_verbose)
                                    {
                                        Dump($"Provided {eventsForThisTask.Count} events for {t.Name}", EventLogEntryType.Information, true);
                                    }
                                    if (eventsForThisTask.Count > 0)
                                    {
                                        DateTime start = DateTime.Now;

                                        t.ProvideEvents(eventsForThisTask);

                                        if (DateTime.Now.Subtract(start).TotalMilliseconds > 500)
                                        {
                                            Dump($"Warning: Task {t.Name} takes a lot of resources. This can make your server vulnerable to DOS attacks. Try better boosters.", EventLogEntryType.Warning);
                                        }
                                    }
                                }
                            }
                        }

                        List <IPAddress> blackList = new List <IPAddress>();

                        //let the tasks poll which ips they want to have blocked / or permanently banned
                        foreach (LogTask t in _logTasks)
                        {
                            if (t is IPBlockingLogTask ipTask)
                            {
                                foreach (IPAddress perma in ipTask.GetPermaBanVictims())
                                {
                                    SetPermanentBan(perma);
                                }

                                List <IPAddress> blockedIPs = ipTask.GetTempBanVictims();

                                if (_verbose)
                                {
                                    Dump($"Polled {t.Name} and got {blockedIPs.Count} temporary and {_permaBannedIPs.Count} permanent ban(s)", EventLogEntryType.Information, true);
                                }

                                foreach (IPAddress blockedIP in blockedIPs)
                                {
                                    if (!blackList.Contains(blockedIP))
                                    {
                                        blackList.Add(blockedIP);
                                    }
                                }
                            }
                        }

                        _lastPolledTempBans = blackList;
                        DoBan();
                    }
                    catch (Exception executionException)
                    {
                        Dump(executionException, EventLogEntryType.Error);
                    }

                    //wait for next iteration or kill signal
                    try
                    {
                        Thread.Sleep(Constants.ThreadSleep);
                    }
                    catch (ThreadInterruptedException)
                    {
                    }

                    //check if need to terminate
                    bool terminate;
                    lock (_syncObject)
                    {
                        terminate = _stop;
                    }
                    if (terminate)
                    {
                        try
                        {
                            FirewallAPI.ClearIPBanList();
                        }
                        catch (Exception ex)
                        {
                            Dump(ex, EventLogEntryType.Warning);
                        }
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                Dump(e, EventLogEntryType.Error);
                Stop();
            }
        }
Ejemplo n.º 22
0
        public override IEnumerable <CommandDTOBase?> Execute(string[] args)
        {
            const string eventId         = "4648";
            string?      userFilterRegex = null;

            // grab events from the last X days - 7 for default, 30 for "-full" collection
            // Always use the user-supplied value, if specified
            var lastDays = 7;

            if (args.Length >= 1)
            {
                if (!int.TryParse(args[0], out lastDays))
                {
                    WriteError("Argument is not an integer");

                    yield break;
                }
            }
            else
            {
                if (!Runtime.FilterResults)
                {
                    lastDays = 30;
                }
            }

            WriteHost("Listing 4648 Explicit Credential Events - A process logged on using plaintext credentials");

            if (args.Length >= 2)
            {
                userFilterRegex = args[1];
                WriteHost($"Username Filter: {userFilterRegex}");
            }
            WriteHost("Output Format:");
            WriteHost("  --- TargetUser,ProcessResults,SubjectUser,IpAddress ---");
            WriteHost("  <Dates the credential was used to logon>\n\n");


            var startTime = DateTime.Now.AddDays(-lastDays);
            var endTime   = DateTime.Now;

            if (!SecurityUtil.IsHighIntegrity())
            {
                WriteError("Unable to collect. Must be an administrator.");
                yield break;
            }

            var query = $@"*[System/EventId={eventId}] and *[System[TimeCreated[@SystemTime >= '{startTime.ToUniversalTime():o}']]] and *[System[TimeCreated[@SystemTime <= '{endTime.ToUniversalTime():o}']]]";

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

            var logReader = new EventLogReader(eventsQuery);

            for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
            {
                //string subjectUserSid = eventDetail.Properties[0].Value.ToString();
                var subjectUserName   = eventDetail.Properties[1].Value.ToString();
                var subjectDomainName = eventDetail.Properties[2].Value.ToString();
                //var subjectLogonId = eventDetail.Properties[3].Value.ToString();
                //var logonGuid = eventDetail.Properties[4].Value.ToString();
                var targetUserName   = eventDetail.Properties[5].Value.ToString();
                var targetDomainName = eventDetail.Properties[6].Value.ToString();
                //var targetLogonGuid = eventDetail.Properties[7].Value.ToString();
                //var targetServerName = eventDetail.Properties[8].Value.ToString();
                //var targetInfo = eventDetail.Properties[9].Value.ToString();
                //var processId = eventDetail.Properties[10].Value.ToString();
                var processName = eventDetail.Properties[11].Value.ToString();
                var ipAddress   = eventDetail.Properties[12].Value.ToString();
                //var IpPort = eventDetail.Properties[13].Value.ToString();

                // Ignore the current machine logging on and
                if (Runtime.FilterResults && Regex.IsMatch(targetUserName, Environment.MachineName) ||
                    Regex.IsMatch(targetDomainName, @"^(Font Driver Host|Window Manager)$"))
                {
                    continue;
                }

                if (userFilterRegex != null && !Regex.IsMatch(targetUserName, userFilterRegex))
                {
                    continue;
                }

                yield return(new ExplicitLogonEventsDTO()
                {
                    TimeCreated = eventDetail.TimeCreated,
                    SubjectUser = subjectUserName,
                    SubjectDomain = subjectDomainName,
                    TargetUser = targetUserName,
                    TargetDomain = targetDomainName,
                    Process = processName,
                    IpAddress = ipAddress
                });
            }
        }
Ejemplo n.º 23
0
        private static void READ_WindowsEventLog_API(string Eventlog_FullName, long RecordID_From_Last_Read, EventLog_File EventLogName)
        {
            try
            {
                EventLogQuery  eventsQuery      = new EventLogQuery(Eventlog_FullName, PathType.LogName);
                EventLogReader EventLogtoReader = new EventLogReader(eventsQuery);

                EventLog_Entry SWELF_Eventlog;

                while (GET_EventLogEntry_From_API(EventLogtoReader) != null)
                {
                    try
                    {
                        SWELF_Eventlog = new EventLog_Entry();
                        if (Windows_EventLog_from_API.RecordId.Value > RecordID_From_Last_Read)
                        {
                            SWELF_Eventlog.CreatedTime      = Windows_EventLog_from_API.TimeCreated.Value; //if this doesnt work we have issues that we cant fix
                            SWELF_Eventlog.EventLog_Seq_num = Windows_EventLog_from_API.RecordId.Value;    //if this doesnt work we have issues that we cant fix
                            SWELF_Eventlog.EventID          = Windows_EventLog_from_API.Id;                //if this doesnt work we have issues that we cant fix
                            SWELF_Eventlog.LogName          = Windows_EventLog_from_API.LogName;
                            try
                            {
                                SWELF_Eventlog.ComputerName = Windows_EventLog_from_API.MachineName;
                            }
                            catch (Exception e)
                            {
                                SWELF_Eventlog.ComputerName = Settings.ComputerName;
                            }

                            try
                            {
                                SWELF_Eventlog.Severity = Windows_EventLog_from_API.LevelDisplayName;
                            }
                            catch (Exception e)
                            {
                                try
                                {
                                    SWELF_Eventlog.Severity = Windows_EventLog_from_API.OpcodeDisplayName;
                                }
                                catch
                                {
                                    SWELF_Eventlog.Severity = Windows_EventLog_from_API.Level.Value.ToString();//if this doesnt work we have issues that we cant fix
                                }
                            }

                            try
                            {
                                SWELF_Eventlog.TaskDisplayName = Windows_EventLog_from_API.TaskDisplayName;
                            }
                            catch (Exception e)
                            {
                                SWELF_Eventlog.TaskDisplayName = Windows_EventLog_from_API.ProviderName;//if this doesnt work we have issues that we cant fix
                            }

                            try
                            {
                                if (Settings.AppConfig_File_Args.ContainsKey(Settings.SWELF_AppConfig_Args[16]))
                                {
                                    SWELF_Eventlog.EventData = "CreationDate=" + SWELF_Eventlog.CreatedTime + "\r\nEventLog_Seq_Number=" + SWELF_Eventlog.EventLog_Seq_num + "\r\nEventID=" + SWELF_Eventlog.EventID + "\r\nSeverity=" + SWELF_Eventlog.Severity + "\r\nEventLogName=" + SWELF_Eventlog.LogName + "\r\n\r\n" + Windows_EventLog_from_API.FormatDescription().ToLower();
                                }
                                else
                                {
                                    SWELF_Eventlog.EventData = Windows_EventLog_from_API.FormatDescription().ToLower();
                                }
                            }
                            catch (Exception e)
                            {
                                if (Settings.AppConfig_File_Args.ContainsKey(Settings.SWELF_AppConfig_Args[16]))
                                {
                                    SWELF_Eventlog.EventData = "CreationDate=" + SWELF_Eventlog.CreatedTime + "\r\nEventLog_Seq_Number=" + SWELF_Eventlog.EventLog_Seq_num + "\r\nEventID=" + SWELF_Eventlog.EventID + "\r\nSeverity=" + SWELF_Eventlog.Severity + "\r\nEventLogName=" + SWELF_Eventlog.LogName + "\r\n\r\n" + Windows_EventLog_from_API.ToXml();
                                }
                                else
                                {
                                    SWELF_Eventlog.EventData = Windows_EventLog_from_API.ToXml();//if this doesnt work we have issues that we cant fix
                                }
                            }

                            try
                            {
                                SWELF_Eventlog.GET_XML_of_Log = Windows_EventLog_from_API.ToXml();
                                if (string.IsNullOrEmpty(SWELF_Eventlog.GET_XML_of_Log))
                                {
                                    SWELF_Eventlog.GET_XML_of_Log = "ERROR READING. Windows_EventLog_from_API.ToXml()";
                                }
                            }
                            catch (Exception e)
                            {
                                SWELF_Eventlog.GET_XML_of_Log = "ERROR READING. Windows_EventLog_from_API.ToXml() Exception Thrown";
                            }

                            try
                            {
                                SWELF_Eventlog.GET_FileHash();
                            }
                            catch (Exception e)
                            {
                                //unable to get file hashs from log
                            }
                            try
                            {
                                SWELF_Eventlog.GET_IP_FromLogFile();
                            }
                            catch (Exception e)
                            {
                                //unable to get IP values from log
                            }

                            try
                            {
                                EventLogName.EventlogMissing = Sec_Checks.CHECK_If_EventLog_Missing(EventLogName, SWELF_Eventlog);
                            }
                            catch (Exception e)
                            {
                                EventLogName.EventlogMissing = true;
                            }

                            try
                            {
                                EventLogName.ID_Number_Of_Individual_log_Entry_EVENTLOG = Windows_EventLog_from_API.RecordId.Value;
                            }
                            catch (Exception e)
                            {
                                EventLogName.ID_Number_Of_Individual_log_Entry_EVENTLOG = 0;
                            }
                            EventLogName.Enqueue_Log(SWELF_Eventlog);
                        }
                    }
                    catch (Exception e)
                    {
                        Error_Operation.Log_Error("INDEX_Record_FROM_API() Missing Event Log(s) Due To Exception with log format while reading in eventlogs.", "EventLog='" + Eventlog_FullName + "' " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
                        MissingLogInFileDueToException = true;
                    }
                }

                try
                {
                    if (Settings.AppConfig_File_Args.ContainsKey(Settings.SWELF_AppConfig_Args[12]) || Settings.AppConfig_File_Args.ContainsKey(Settings.SWELF_AppConfig_Args[11]))
                    {
                        Settings.IP_List_EVT_Logs.AddRange(Settings.IP_List_EVT_Logs.Distinct().ToList());
                        Settings.Hashs_From_EVT_Logs.AddRange(Settings.Hashs_From_EVT_Logs.Distinct().ToList());
                    }
                }
                catch (Exception e)
                {
                    Error_Operation.Log_Error("Settings.IP_List_EVT_Logs.AddRange() OR Settings.Hashs_From_EVT_Logs.AddRange()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
                }
                MissingLogInFileDueToException = false;
            }
            catch (Exception e)
            {
                Error_Operation.Log_Error("READ_WindowsEventLog_API() Missing All Event Log(s) Due To Exception. ", "EventLog='" + Eventlog_FullName + "' " + e.Message.ToString() + " " + Eventlog_FullName + " " + RecordID_From_Last_Read + " " + EventLogName.First_EventLogID_From_Check + " " + EventLogName.Last_EventLogID_From_Check + " " + EventLogName.Contents_of_EventLog.Count, e.StackTrace.ToString(), Error_Operation.LogSeverity.FailureAudit);
                MissingLogInFileDueToException = true;
            }
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            txb_eventLastDate.Text = string.Empty;
            txb_eventData.Text     = string.Empty;
            eventCount             = 0;

            eventLog        = cb_eventLog.Text;
            eventLevel      = cb_eventLavel.Text;
            eventId         = txb_eventId.Text;
            eventDataSearch = txb_eventDataSearch.Text;
            //eventDataSearch = "Wolf.Playout.exe";

            string        query       = "*[System/EventID=" + eventId + " and " + "System/Level=" + eventLevel + "]";
            EventLogQuery eventsQuery = new EventLogQuery(eventLog, PathType.LogName, query);

            try
            {
                EventLogReader logReader = new EventLogReader(eventsQuery);

                for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent())
                {
                    if (eventdetail.FormatDescription().Contains(eventDataSearch))
                    {
                        txb_eventLastDate.Text = eventdetail.TimeCreated.ToString();
                        txb_eventData.Text     = eventdetail.FormatDescription();
                        eventCount++;

                        //MessageBox.Show(
                        //eventdetail.TimeCreated.ToString() + "\n" +
                        //eventdetail.FormatDescription()
                        //);
                        //string eventXml = eventdetail.ToXml();
                    }
                }
                txb_eventCount.Text = eventCount.ToString();
            }
            catch (EventLogNotFoundException ex)
            {
                MessageBox.Show("Error while reading the event logs:\n\n" + ex.Message);
                return;
            }

            timer.Interval = new TimeSpan(Convert.ToInt16(txb_timerH.Text), Convert.ToInt16(txb_timerM.Text), Convert.ToInt16(txb_timerS.Text));
            DateTime dt = new DateTime(2010, 1, 1);

            if (eventCount > 0)
            {
                if (txb_eventLastDate.Text.Trim() != "")
                {
                    dt = DateTime.Parse(txb_eventLastDate.Text); //son hata zamanı.
                }
            }
            TimeSpan ts = DateTime.Now - dt; //son hata zamanından sonra geçen süre.
            //TimeSpan ts =  DateTime.Now.Subtract(dt);

            if (ts < timer.Interval) //son timer periyodu içinde yeni bir hata olmuş ise.
            {
                //MessageBox.Show(
                // dt.ToString() + "\n" +
                // DateTime.Now.ToString() + "\n\n" +
                // ts.ToString() + "\n" +
                // timer.Interval.ToString()
                //);

                eventCountNew++;
                txb_eventCountNew.Text       = eventCountNew.ToString();
                txb_eventCountNew.Foreground = new SolidColorBrush(Colors.Red);
                txb_eventLastDate.Foreground = new SolidColorBrush(Colors.Red);

                processKill(txb_eventDataSearch.Text.Trim());

                Thread.Sleep(500);
                System.Windows.Forms.Application.DoEvents();

                processStart(txb_eventDataSearch.Text.Trim());
            }
        }
Ejemplo n.º 25
0
        private void read_single_log_thread(log_info log)
        {
            string query_string = "*";

            if (provider_name != "")
            {
                query_string = "*[System/Provider/@Name=\"" + provider_name + "\"]";
            }

            logger.Info("event_log new thread - reading from " + log.log_type);

            int max_event_count = int.MaxValue;

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

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

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

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

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

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

                logger.Info("event_log reading from " + log.log_type + " complete - read " + log.cur_log_count_ + " records");

                lock (this)
                    log.listening_for_new_events_ = true;

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

                    watcher.Enabled = true;
                    while (!log.disposed_)
                    {
                        Thread.Sleep(100);
                    }
                    watcher.Enabled = false;
                }
            } catch (Exception e) {
                logger.Error("can't create event log " + log.log_type + "/" + remote_machine_name + " : " + e.Message);
                errors_.add("Can't create Log " + log.log_type + " on machine " + remote_machine_name + ", Reason=" + e.Message);
            }

            logger.Info("event_log reading from " + log.log_type + " watching for new events COMPLETE");
        }
Ejemplo n.º 26
0
        public static void HarvestTGTs(int intervalMinutes, string registryBasePath)
        {
            // First extract all TGTs then monitor the event log (indefinitely) for 4624 logon events
            //  every 'intervalMinutes' and dumps TGTs JUST for the specific logon IDs (LUIDs) based on the event log.
            // On each interval, renew any tickets that are about to expire and refresh the cache.
            // End result: every "intervalMinutes" a set of currently valid TGT .kirbi files are dumped to console

            if (!Helpers.IsHighIntegrity())
            {
                Console.WriteLine("\r\n[X] You need to have an elevated context to dump other users' Kerberos tickets :( \r\n");
                return;
            }

            Console.WriteLine("[*] Action: TGT Harvesting (w/ auto-renewal)");
            Console.WriteLine("\r\n[*] Monitoring every {0} minutes for 4624 logon events\r\n", intervalMinutes);

            // used to keep track of LUIDs we've already dumped
            var seenLUIDs = new Dictionary <ulong, bool>();

            // get the current set of TGTs
            List <KRB_CRED> creds = LSA.ExtractTGTs(new Interop.LUID());

            while (true)
            {
                // check for 4624 logon events in the past "intervalSeconds"
                string         queryString = String.Format("*[System[EventID=4624 and TimeCreated[timediff(@SystemTime) <= {0}]]]", intervalMinutes * 60 * 1000);
                EventLogQuery  eventsQuery = new EventLogQuery("Security", PathType.LogName, queryString);
                EventLogReader logReader   = new EventLogReader(eventsQuery);

                for (EventRecord eventInstance = logReader.ReadEvent(); eventInstance != null; eventInstance = logReader.ReadEvent())
                {
                    // if there's an event, extract out the logon ID (LUID) for the session
                    string   eventMessage = eventInstance.FormatDescription();
                    DateTime eventTime    = (DateTime)eventInstance.TimeCreated;

                    int    startIndex = eventMessage.IndexOf("New Logon:");
                    string message    = eventMessage.Substring(startIndex);

                    // extract out relevant information from the event log message
                    var   acctNameExpression   = new Regex(string.Format(@"\n.*Account Name:\s*(?<name>.+?)\r\n"));
                    Match acctNameMatch        = acctNameExpression.Match(message);
                    var   acctDomainExpression = new Regex(string.Format(@"\n.*Account Domain:\s*(?<domain>.+?)\r\n"));
                    Match acctDomainMatch      = acctDomainExpression.Match(message);

                    if (acctNameMatch.Success)
                    {
                        var   srcNetworkExpression = new Regex(string.Format(@"\n.*Source Network Address:\s*(?<address>.+?)\r\n"));
                        Match srcNetworkMatch      = srcNetworkExpression.Match(message);

                        string logonName         = acctNameMatch.Groups["name"].Value;
                        string accountDomain     = "";
                        string srcNetworkAddress = "";
                        try
                        {
                            accountDomain = acctDomainMatch.Groups["domain"].Value;
                        }
                        catch { }
                        try
                        {
                            srcNetworkAddress = srcNetworkMatch.Groups["address"].Value;
                        }
                        catch { }

                        // ignore SYSTEM logons and other defaults
                        if (!Regex.IsMatch(logonName, @"SYSTEM|LOCAL SERVICE|NETWORK SERVICE|UMFD-[0-9]+|DWM-[0-9]+|ANONYMOUS LOGON", RegexOptions.IgnoreCase))
                        {
                            Console.WriteLine("\r\n[+] {0} - 4624 logon event for '{1}\\{2}' from '{3}'", eventTime, accountDomain, logonName, srcNetworkAddress);

                            var   expression2 = new Regex(string.Format(@"\n.*Logon ID:\s*(?<id>.+?)\r\n"));
                            Match match2      = expression2.Match(message);

                            if (match2.Success)
                            {
                                try
                                {
                                    // check if we've seen this LUID before
                                    Interop.LUID luid = new Interop.LUID(match2.Groups["id"].Value);
                                    if (!seenLUIDs.ContainsKey((ulong)luid))
                                    {
                                        seenLUIDs[luid] = true;
                                        // if we haven't seen it, extract any TGTs for that particular logon ID and add to the cache
                                        List <KRB_CRED> newCreds = LSA.ExtractTGTs(luid);
                                        creds.AddRange(newCreds);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("[X] Exception: {0}", e.Message);
                                }
                            }
                        }
                    }
                }

                for (int i = creds.Count - 1; i >= 0; i--)
                {
                    DateTime endTime   = TimeZone.CurrentTimeZone.ToLocalTime(creds[i].enc_part.ticket_info[0].endtime);
                    DateTime renewTill = TimeZone.CurrentTimeZone.ToLocalTime(creds[i].enc_part.ticket_info[0].renew_till);

                    // check if the ticket is going to expire before the next interval checkin
                    if (endTime < DateTime.Now.AddMinutes(intervalMinutes))
                    {
                        // check if the ticket's renewal limit will be valid within the next interval
                        if (renewTill < DateTime.Now.AddMinutes(intervalMinutes))
                        {
                            // renewal limit under checkin interval, so remove the ticket from the cache
                            creds.RemoveAt(i);
                        }
                        else
                        {
                            // renewal limit after checkin interval, so renew the TGT
                            string userName   = creds[i].enc_part.ticket_info[0].pname.name_string[0];
                            string domainName = creds[i].enc_part.ticket_info[0].prealm;

                            Console.WriteLine("[*] Renewing TGT for {0}@{1}", userName, domainName);
                            byte[]   bytes       = Renew.TGT(creds[i], false, "", false);
                            KRB_CRED renewedCred = new KRB_CRED(bytes);
                            creds[i] = renewedCred;
                        }
                    }
                }

                Console.WriteLine("\r\n[*] {0} - Current usable TGTs:\r\n", DateTime.Now);
                LSA.DisplayTGTs(creds);
                if (registryBasePath != null)
                {
                    LSA.SaveTicketsToRegistry(creds, registryBasePath);
                }
                System.Threading.Thread.Sleep(intervalMinutes * 60 * 1000);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// ReadServiceFabricWindowsEventLog().
        /// </summary>
        public void ReadServiceFabricWindowsEventLog()
        {
            string sfOperationalLogSource      = "Microsoft-ServiceFabric/Operational";
            string sfAdminLogSource            = "Microsoft-ServiceFabric/Admin";
            string systemLogSource             = "System";
            string sfLeaseAdminLogSource       = "Microsoft-ServiceFabric-Lease/Admin";
            string sfLeaseOperationalLogSource = "Microsoft-ServiceFabric-Lease/Operational";

            var range2Days = DateTime.UtcNow.AddDays(-1);
            var format     = range2Days.ToString(
                "yyyy-MM-ddTHH:mm:ss.fffffff00K",
                CultureInfo.InvariantCulture);
            var datexQuery = string.Format(
                "*[System/TimeCreated/@SystemTime >='{0}']",
                format);

            // Critical and Errors only.
            string xQuery = "*[System/Level <= 2] and " + datexQuery;

            // SF Admin Event Store.
            var evtLogQuery = new EventLogQuery(sfAdminLogSource, PathType.LogName, xQuery);

            using (var evtLogReader = new EventLogReader(evtLogQuery))
            {
                for (var eventInstance = evtLogReader.ReadEvent();
                     eventInstance != null;
                     eventInstance = evtLogReader.ReadEvent())
                {
                    this.Token.ThrowIfCancellationRequested();
                    this.evtRecordList.Add(eventInstance);
                }
            }

            // SF Operational Event Store.
            evtLogQuery = new EventLogQuery(sfOperationalLogSource, PathType.LogName, xQuery);
            using (var evtLogReader = new EventLogReader(evtLogQuery))
            {
                for (var eventInstance = evtLogReader.ReadEvent();
                     eventInstance != null;
                     eventInstance = evtLogReader.ReadEvent())
                {
                    this.Token.ThrowIfCancellationRequested();
                    this.evtRecordList.Add(eventInstance);
                }
            }

            // SF Lease Admin Event Store.
            evtLogQuery = new EventLogQuery(sfLeaseAdminLogSource, PathType.LogName, xQuery);
            using (var evtLogReader = new EventLogReader(evtLogQuery))
            {
                for (var eventInstance = evtLogReader.ReadEvent();
                     eventInstance != null;
                     eventInstance = evtLogReader.ReadEvent())
                {
                    this.Token.ThrowIfCancellationRequested();
                    this.evtRecordList.Add(eventInstance);
                }
            }

            // SF Lease Operational Event Store.
            evtLogQuery = new EventLogQuery(sfLeaseOperationalLogSource, PathType.LogName, xQuery);
            using (var evtLogReader = new EventLogReader(evtLogQuery))
            {
                for (var eventInstance = evtLogReader.ReadEvent();
                     eventInstance != null;
                     eventInstance = evtLogReader.ReadEvent())
                {
                    this.Token.ThrowIfCancellationRequested();
                    this.evtRecordList.Add(eventInstance);
                }
            }

            // System Event Store.
            evtLogQuery = new EventLogQuery(systemLogSource, PathType.LogName, xQuery);
            using (var evtLogReader = new EventLogReader(evtLogQuery))
            {
                for (var eventInstance = evtLogReader.ReadEvent();
                     eventInstance != null;
                     eventInstance = evtLogReader.ReadEvent())
                {
                    this.Token.ThrowIfCancellationRequested();
                    this.evtRecordList.Add(eventInstance);
                }
            }
        }
Ejemplo n.º 28
0
        public static void Monitor4624(int intervalSeconds, string targetUser, string registryBasePath = null)
        {
            // monitors the event log (indefinitely) for 4624 logon events every 'intervalSeconds' and dumps TGTs JUST for the specific
            //  logon IDs (LUIDs) based on the event log. Can optionally only extract for a targeted user.

            if (!Helpers.IsHighIntegrity())
            {
                Console.WriteLine("\r\n[X] You need to have an elevated context to dump other users' Kerberos tickets :( \r\n");
                return;
            }

            // used to keep track of LUIDs we've already dumped
            var seenLUIDs = new Dictionary <ulong, bool>();

            Console.WriteLine("[*] Action: TGT Monitoring");
            Console.WriteLine("[*] Monitoring every {0} seconds for 4624 logon events", intervalSeconds);

            if (!String.IsNullOrEmpty(targetUser))
            {
                Console.WriteLine("[*] Target user : {0}", targetUser);
                targetUser = targetUser.Replace("$", "\\$");
            }
            Console.WriteLine();


            while (true)
            {
                // check for 4624 logon events in the past "intervalSeconds"
                string         queryString = String.Format("*[System[EventID=4624 and TimeCreated[timediff(@SystemTime) <= {0}]]]", intervalSeconds * 1000);
                EventLogQuery  eventsQuery = new EventLogQuery("Security", PathType.LogName, queryString);
                EventLogReader logReader   = new EventLogReader(eventsQuery);

                for (EventRecord eventInstance = logReader.ReadEvent(); eventInstance != null; eventInstance = logReader.ReadEvent())
                {
                    // if there's an event, extract out the logon ID (LUID) for the session
                    string   eventMessage = eventInstance.FormatDescription();
                    DateTime eventTime    = (DateTime)eventInstance.TimeCreated;

                    int    startIndex = eventMessage.IndexOf("New Logon:");
                    string message    = eventMessage.Substring(startIndex);

                    // extract out relevant information from the event log message
                    var   acctNameExpression   = new Regex(string.Format(@"\n.*Account Name:\s*(?<name>.+?)\r\n"));
                    Match acctNameMatch        = acctNameExpression.Match(message);
                    var   acctDomainExpression = new Regex(string.Format(@"\n.*Account Domain:\s*(?<domain>.+?)\r\n"));
                    Match acctDomainMatch      = acctDomainExpression.Match(message);

                    if (acctNameMatch.Success)
                    {
                        var   srcNetworkExpression = new Regex(string.Format(@"\n.*Source Network Address:\s*(?<address>.+?)\r\n"));
                        Match srcNetworkMatch      = srcNetworkExpression.Match(message);

                        string logonName         = acctNameMatch.Groups["name"].Value;
                        string accountDomain     = "";
                        string srcNetworkAddress = "";
                        try
                        {
                            accountDomain = acctDomainMatch.Groups["domain"].Value;
                        }
                        catch { }
                        try
                        {
                            srcNetworkAddress = srcNetworkMatch.Groups["address"].Value;
                        }
                        catch { }

                        // ignore SYSTEM logons and other defaults
                        if (!Regex.IsMatch(logonName, @"SYSTEM|LOCAL SERVICE|NETWORK SERVICE|UMFD-[0-9]+|DWM-[0-9]+|ANONYMOUS LOGON", RegexOptions.IgnoreCase))
                        {
                            Console.WriteLine("\r\n[+] {0} - 4624 logon event for '{1}\\{2}' from '{3}'", eventTime, accountDomain, logonName, srcNetworkAddress);
                            // filter if we're targeting a specific user
                            if (String.IsNullOrEmpty(targetUser) || (Regex.IsMatch(logonName, targetUser, RegexOptions.IgnoreCase)))
                            {
                                var   expression2 = new Regex(string.Format(@"\n.*Logon ID:\s*(?<id>.+?)\r\n"));
                                Match match2      = expression2.Match(message);

                                if (match2.Success)
                                {
                                    try
                                    {
                                        // check if we've seen this LUID before
                                        Interop.LUID luid = new Interop.LUID(match2.Groups["id"].Value);
                                        if (!seenLUIDs.ContainsKey((ulong)luid))
                                        {
                                            seenLUIDs[luid] = true;
                                            // if we haven't seen it, extract any TGTs for that particular logon ID
                                            LSA.ListKerberosTicketData(luid, "krbtgt", true, registryBasePath);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("[X] Exception: {0}", e.Message);
                                    }
                                }
                            }
                        }
                    }
                }
                System.Threading.Thread.Sleep(intervalSeconds * 1000);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Get the WER entries for VS and VS related EXEs from the Event Log and write them to a file
        /// </summary>
        internal static void TryWriteWatsonEntriesToFile(string filePath)
        {
            try
            {
                // Use a HashSet to make sure the entries we add aren't duplicates (calls the Equals override from FeedbackItemWatsonEntry)
                var watsonEntries = new HashSet <FeedbackItemWatsonEntry>();

                // We need to search in the Application Event Log, since that's where Watson logs entries
                var eventLogQuery = new EventLogQuery(EventLogName, PathType.LogName)
                {
                    // Read events in descending order, so we can get either the last 5 entries or the past day of entries, whichever has a bigger count
                    ReverseDirection = true
                };

                var         eventLogReader = new EventLogReader(eventLogQuery);
                EventRecord eventLogRecord;
                var         watsonEntriesCount = 0;
                while ((eventLogRecord = eventLogReader.ReadEvent()) != null)
                {
                    // We only want the last 5 entries or the past day of entries, whichever has a bigger count
                    if (IsLastDayOrLastFiveRecentEntry(eventLogRecord, watsonEntriesCount))
                    {
                        // Filter the entries by Watson specific ones for VS EXEs
                        if (IsValidWatsonEntry(eventLogRecord))
                        {
                            var entry = new FeedbackItemWatsonEntry(eventLogRecord);
                            watsonEntries.Add(entry);

                            // If the entry doesn't have a valid BucketId, we don't want it to count towards the maxCount we send
                            if (!string.IsNullOrWhiteSpace(GetEventRecordPropertyToString(eventLogRecord, FaultBucketIndex)))
                            {
                                watsonEntriesCount++;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (watsonEntries.Any())
                {
                    var watsonEntriesStringBuilder = new StringBuilder();
                    foreach (var entry in watsonEntries)
                    {
                        watsonEntriesStringBuilder.AppendLine($"Event Time (UTC): {entry.EventTime}");
                        watsonEntriesStringBuilder.AppendLine($"Application Name: {entry.ApplicationName}");
                        watsonEntriesStringBuilder.AppendLine($"Application Version: {entry.ApplicationVersion}");
                        watsonEntriesStringBuilder.AppendLine($"Faulting Module: {entry.FaultingModule}");
                        watsonEntriesStringBuilder.AppendLine($"Faulting Module Version: {entry.FaultingModuleVersion}");
                        watsonEntriesStringBuilder.AppendLine($"Event Name: {entry.EventName}");
                        watsonEntriesStringBuilder.AppendLine($"Cab Id: {entry.CabId}");
                        watsonEntriesStringBuilder.AppendLine($"Fault Bucket: {entry.FaultBucket}");
                        watsonEntriesStringBuilder.AppendLine($"Hashed Bucket: {entry.HashedBucket}");
                        watsonEntriesStringBuilder.AppendLine($"Watson Report Id: {entry.WatsonReportId}");
                        watsonEntriesStringBuilder.AppendLine();
                    }

                    File.WriteAllText(filePath, watsonEntriesStringBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                File.WriteAllText(filePath, ex.ToString());
            }
        }
        public override IEnumerable <CommandDTOBase?> Execute(string[] args)
        {
            if (!SecurityUtil.IsHighIntegrity())
            {
                WriteError("Unable to collect. Must be an administrator/in a high integrity context.");
                yield break;
            }

            var NTLMv1Users   = new HashSet <string>();
            var NTLMv2Users   = new HashSet <string>();
            var KerberosUsers = new HashSet <string>();

            // grab events from the last X days - 10 for workstations, 30 for "-full" collection
            // Always use the user-supplied value, if specified
            var lastDays = 10;

            if (Shlwapi.IsWindowsServer())
            {
                lastDays = 1;
            }

            string?userRegex = null;

            if (args.Length >= 1)
            {
                if (!int.TryParse(args[0], out lastDays))
                {
                    throw new ArgumentException("Argument is not an integer");
                }
            }

            if (args.Length >= 2)
            {
                userRegex = args[1];
            }

            WriteVerbose($"Listing 4624 Account Logon Events for the last {lastDays} days.\n");

            if (userRegex != null)
            {
                WriteVerbose($"Username Filter: {userRegex}");
            }

            var startTime = DateTime.Now.AddDays(-lastDays);
            var endTime   = DateTime.Now;

            var query       = $@"*[System/EventID=4624] and *[System[TimeCreated[@SystemTime >= '{startTime.ToUniversalTime():o}']]] and *[System[TimeCreated[@SystemTime <= '{endTime.ToUniversalTime():o}']]]";
            var eventsQuery = new EventLogQuery("Security", PathType.LogName, query)
            {
                ReverseDirection = true
            };
            var logReader = new EventLogReader(eventsQuery);

            WriteHost("  TimeCreated,TargetUser,LogonType,IpAddress,SubjectUsername,AuthenticationPackageName,LmPackageName,TargetOutboundUser");

            for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
            {
                //var subjectUserSid = eventDetail.Properties[0].Value.ToString();
                var subjectUserName   = eventDetail.Properties[1].Value.ToString();
                var subjectDomainName = eventDetail.Properties[2].Value.ToString();
                //var subjectLogonId = eventDetail.Properties[3].Value.ToString();
                //var targetUserSid = eventDetail.Properties[4].Value.ToString();
                var targetUserName   = eventDetail.Properties[5].Value.ToString();
                var targetDomainName = eventDetail.Properties[6].Value.ToString();
                //var targetLogonId = eventDetail.Properties[7].Value.ToString();
                //var logonType = eventDetail.Properties[8].Value.ToString();
                var logonType = $"{(SECURITY_LOGON_TYPE)(int.Parse(eventDetail.Properties[8].Value.ToString()))}";
                //var logonProcessName = eventDetail.Properties[9].Value.ToString();
                var authenticationPackageName = eventDetail.Properties[10].Value.ToString();
                //var workstationName = eventDetail.Properties[11].Value.ToString();
                //var logonGuid = eventDetail.Properties[12].Value.ToString();
                //var transmittedServices = eventDetail.Properties[13].Value.ToString();
                var lmPackageName = eventDetail.Properties[14].Value.ToString();
                lmPackageName = lmPackageName == "-" ? "" : lmPackageName;
                //var keyLength = eventDetail.Properties[15].Value.ToString();
                //var processId = eventDetail.Properties[16].Value.ToString();
                //var processName = eventDetail.Properties[17].Value.ToString();
                var ipAddress = eventDetail.Properties[18].Value.ToString();
                //var ipPort = eventDetail.Properties[19].Value.ToString();
                //var impersonationLevel = eventDetail.Properties[20].Value.ToString();
                //var restrictedAdminMode = eventDetail.Properties[21].Value.ToString();

                var targetOutboundUserName   = "******";
                var targetOutboundDomainName = "-";
                if (eventDetail.Properties.Count > 22)  // Not available on older versions of Windows
                {
                    targetOutboundUserName   = eventDetail.Properties[22].Value.ToString();
                    targetOutboundDomainName = eventDetail.Properties[23].Value.ToString();
                }
                //var VirtualAccount = eventDetail.Properties[24].Value.ToString();
                //var TargetLinkedLogonId = eventDetail.Properties[25].Value.ToString();
                //var ElevatedToken = eventDetail.Properties[26].Value.ToString();

                // filter out SYSTEM, computer accounts, local service accounts, UMFD-X accounts, and DWM-X accounts (for now)
                var userIgnoreRegex = "^(SYSTEM|LOCAL SERVICE|NETWORK SERVICE|UMFD-[0-9]+|DWM-[0-9]+|ANONYMOUS LOGON|" + Environment.MachineName + "\\$)$";
                if (userRegex == null && Regex.IsMatch(targetUserName, userIgnoreRegex, RegexOptions.IgnoreCase))
                {
                    continue;
                }

                var domainIgnoreRegex = "^(NT VIRTUAL MACHINE)$";
                if (userRegex == null && Regex.IsMatch(targetDomainName, domainIgnoreRegex, RegexOptions.IgnoreCase))
                {
                    continue;
                }


                // Handle the user filter
                if (userRegex != null && !Regex.IsMatch(targetUserName, userRegex, RegexOptions.IgnoreCase))
                {
                    continue;
                }

                // Analyze the output
                if (logonType == "Network")
                {
                    var accountName = $"{targetDomainName}\\{targetUserName}";
                    if (authenticationPackageName == "NTLM")
                    {
                        switch (lmPackageName)
                        {
                        case "NTLM V1":
                            NTLMv1Users.Add(accountName);
                            break;

                        case "NTLM V2":
                            NTLMv2Users.Add(accountName);
                            break;
                        }
                    }
                    else if (authenticationPackageName == "Kerberos")
                    {
                        KerberosUsers.Add(accountName);
                    }
                }

                yield return(new LogonEventsDTO(
                                 eventDetail.TimeCreated?.ToUniversalTime(),
                                 targetUserName,
                                 targetDomainName,
                                 logonType,
                                 ipAddress,
                                 subjectUserName,
                                 subjectDomainName,
                                 authenticationPackageName,
                                 lmPackageName,
                                 targetOutboundUserName,
                                 targetOutboundDomainName
                                 ));
            }


            // TODO: Move all of this into a Foramtter class
            if (NTLMv1Users.Count > 0 || NTLMv2Users.Count > 0)
            {
                WriteHost("\n  Other accounts authenticate to this machine using NTLM! NTLM-relay may be possible");
            }

            if (NTLMv1Users.Count > 0)
            {
                WriteHost("\n  Accounts authenticate to this machine using NTLM v1!");
                WriteHost("  You can obtain these accounts' **NTLM** hashes by sniffing NTLM challenge/responses and then cracking them!");
                WriteHost("  NTLM v1 authentication is 100% broken!\n");

                PrintUserSet(NTLMv1Users);
            }

            if (NTLMv2Users.Count > 0)
            {
                WriteHost("\n  Accounts authenticate to this machine using NTLM v2!");
                WriteHost("  You can obtain NetNTLMv2 for these accounts by sniffing NTLM challenge/responses.");
                WriteHost("  You can then try and crack their passwords.\n");

                PrintUserSet(NTLMv2Users);
            }

            if (KerberosUsers.Count > 0)
            {
                WriteHost("\n  The following users have authenticated to this machine using Kerberos.\n");
                PrintUserSet(KerberosUsers);
            }
        }