Beispiel #1
0
        private static void SET_WindowsEventLog_Location()
        {
            try
            {
                if (!EventLog.SourceExists(SWELF_EventLog_Name))
                {
                    EventLog.CreateEventSource(SWELF_PROC_Name.ProcessName, SWELF_EventLog_Name);
                    SWELF_EvtLog_OBJ.Source = SWELF_EventLog_Name;

                    if (Reg_Operation.CHECK_Eventlog_SWELF_Reg_Key_Exists(Reg_Operation.EventLog_Base_Key + "\\" + SWELF_EventLog_Name))
                    {
                        Reg_Operation.SET_Event_Log_MaxSize(SWELF_EventLog_Name);
                    }
                }
                else
                {
                    SWELF_EvtLog_OBJ.Source = SWELF_EventLog_Name;
                }
            }
            catch (Exception e)
            {
                EventLog.CreateEventSource(SWELF_PROC_Name.ProcessName, SWELF_EventLog_Name);
                Error_Operation.Log_Error("SET_WindowsEventLog_Loc() ", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Critical);
                SWELF_EvtLog_OBJ.Source = SWELF_EventLog_Name;
            }
        }
Beispiel #2
0
        private static bool SEND_Data_from_File_UDP(string Log_File_Data, UdpClient client)
        {
            bool Data_Sent = true;

            try
            {
                for (int x = 0; x < Settings.Log_Forwarders_HostNames.Count; ++x)
                {
                    try
                    {
                        byte[] sendBytes = GET_Encoding_to_Return(Log_File_Data);
                        client.Send(sendBytes, sendBytes.Length);
                    }
                    catch (Exception e)
                    {
                        Data_Sent = false;
                        Settings.Logs_Sent_to_ALL_Collectors = false;
                        Error_Operation.Log_Error("SEND_Data_from_File_UDP(Log_File_Data)", "SWELF NETWORK ERROR: " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                    }
                }
                Settings.Logs_Sent_to_ALL_Collectors = true;
                Reg_Operation.ADD_or_CHANGE_SWELF_Reg_Key(Reg_Operation.REG_KEY.Logs_Last_Sent, DateTime.Now.ToString());
            }
            catch (Exception e)
            {
                Data_Sent = false;
                Settings.Logs_Sent_to_ALL_Collectors = false;
                Error_Operation.Log_Error("SEND_Data_from_File(string Log_File_Data)", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
            }
            return(Data_Sent);
        }
Beispiel #3
0
        internal void READ_EventLog(string Eventlog_FullName, long PlaceKeeper_EventRecordID = 1)
        {
            long EVTlog_PlaceHolder = PlaceKeeper_EventRecordID;

            try
            {
                if (EVTlog_PlaceHolder <= 1)
                {
                    EVTlog_PlaceHolder = Settings.EventLog_w_PlaceKeeper[Eventlog_FullName];
                }
            }
            catch (Exception e)
            {
                EVTlog_PlaceHolder = 1;
            }

            if (Settings.CHECK_If_EventLog_Exsits(Eventlog_FullName))
            {
                EventLog_Log_API = new EventLog_File(Eventlog_FullName, PlaceKeeper_EventRecordID);

                long First_EventID = EventLog_Log_API.First_EventLogID_From_Check;
                long Last_EventID  = EventLog_Log_API.Last_EventLogID_From_Check;

                if (PlaceKeeper_EventRecordID > First_EventID && PlaceKeeper_EventRecordID < Last_EventID)//Normal operation placekkeeper in middle of log file
                {
                    EVTlog_PlaceHolder = PlaceKeeper_EventRecordID;
                    READ_WindowsEventLog_API(Eventlog_FullName, EVTlog_PlaceHolder, EventLog_Log_API);
                    Settings.EventLog_w_PlaceKeeper[Eventlog_FullName] = Last_EventID;
                }
                else if (Last_EventID == PlaceKeeper_EventRecordID)//no logs added
                {
                    EVTlog_PlaceHolder = PlaceKeeper_EventRecordID;
                }
                else if (PlaceKeeper_EventRecordID <= 1)
                {
                    EVTlog_PlaceHolder = First_EventID;
                    READ_WindowsEventLog_API(Eventlog_FullName, EVTlog_PlaceHolder, EventLog_Log_API);
                    EventLog_SWELF.WRITE_Warning_EventLog("Logging as EventLog Source 1st run for Eventlog named '" + Eventlog_FullName + "' on machine named '" + Settings.ComputerName + "' due to PlaceKeeper_EventRecordID<=1");
                    Settings.EventLog_w_PlaceKeeper[Eventlog_FullName] = Last_EventID;
                }
                else if (First_EventID > PlaceKeeper_EventRecordID)//missed all logs and missing log files send alert for missing log files
                {
                    EVTlog_PlaceHolder = First_EventID;
                    READ_WindowsEventLog_API(Eventlog_FullName, EVTlog_PlaceHolder, EventLog_Log_API);
                    EventLog_SWELF.WRITE_FailureAudit_Error_To_EventLog("Missed " + (First_EventID - PlaceKeeper_EventRecordID) + " logs from '" + Eventlog_FullName + "' on machine '" + Settings.ComputerName + "' the first eventlog id was older than where app left off. Possible log file cycle/overwrite between runs. First event log id number in the log is " + First_EventID + " SWELF left off from last run at " + PlaceKeeper_EventRecordID);
                    Settings.EventLog_w_PlaceKeeper[Eventlog_FullName.ToLower()] = Last_EventID;
                }
                else//unknown/catch condition assume 1st run
                {
                    EVTlog_PlaceHolder = First_EventID;
                    READ_WindowsEventLog_API(Eventlog_FullName, EVTlog_PlaceHolder, EventLog_Log_API);
                    EventLog_SWELF.WRITE_Warning_EventLog("ERROR: App unable to determine app reading state in event log. App starting over. App not told to reset. '" + Eventlog_FullName + "' '" + Settings.ComputerName + "'. unknown/catch condition assume 1st run");
                    Settings.EventLog_w_PlaceKeeper[Eventlog_FullName] = Last_EventID;
                }
            }
            else
            {
                Error_Operation.Log_Error("READ_EventLog() if (Settings.FIND_EventLog_Exsits())", Eventlog_FullName + " EventLog does not exist.", "", Error_Operation.LogSeverity.Informataion);
            }
        }
Beispiel #4
0
        internal static void READ_ALL_SWELF_Reg_Keys()
        {
            foreach (string RegKeyValue in BASE_SWELF_KEY.GetValueNames())
            {
                try
                {
                    if (String.IsNullOrEmpty(BASE_SWELF_KEY.GetValue(RegKeyValue).ToString()) == false)
                    {
                        Settings.REG_Keys.Add(RegKeyValue, READ_SWELF_Reg_Key(RegKeyValue));
                    }
                }
                catch (Exception e)
                {
                    if (e.Message.Contains("An item with the same key has already been added.") == false)
                    {
                        Error_Operation.Log_Error("READ_ALL_SWELF_Reg_Keys()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Verbose);
                    }
                }
            }

            if (CHECK_SWELF_Reg_Key_Exists(REG_KEY.Logs_Last_Sent) == false)
            {
                string Date = DateTime.Now.ToString();
                BASE_SWELF_KEY.SetValue(SWELF_Keys[(int)REG_KEY.Logs_Last_Sent], Crypto_Operation.Protect_Data_Value(Date));
                Settings.REG_Keys.Add(SWELF_Keys[20], Date);
            }
        }
Beispiel #5
0
 internal static object READ_Eventlog_SWELF_Reg_Key(string Key)
 {
     if (Settings.REG_Keys.Count > 1)
     {
         if (Settings.REG_Keys.ContainsKey(Key))
         {
             return(Settings.REG_Keys[Key]);
         }
     }
     else
     {
         if (CHECK_Eventlog_SWELF_Reg_Key_Exists(Key))
         {
             if (Crypto_Operation.CHECK_Value_Encrypted(Crypto_Operation.ObjectToByteArray(BASE_SWELF_KEY.GetValue(Key))))
             {
                 return(Crypto_Operation.UnProtect_Data_Value(Crypto_Operation.ObjectToByteArray(BASE_SWELF_KEY.GetValue(Key))));
             }
             else
             {
                 ADD_or_CHANGE_SWELF_Reg_Key(Key, Crypto_Operation.CONVERT_To_String_From_Bytes(Crypto_Operation.Protect_Data_Value(Crypto_Operation.ObjectToByteArray(BASE_SWELF_KEY.GetValue(Key))), 1));
                 return(Crypto_Operation.UnProtect_Data_Value(Crypto_Operation.ObjectToByteArray(BASE_SWELF_KEY.GetValue(Key))));
             }
         }
         else
         {
             Error_Operation.Log_Error("CHANGE_Reg_Key()", "Reg Key does not exist. RegKey=" + Key, "", Error_Operation.LogSeverity.Warning);
             return("");
         }
     }
     return("");
 }
Beispiel #6
0
        internal static bool CHECK_File_Encrypted(string FilePath)
        {
            try
            {
                FileInfo fi    = new FileInfo(FilePath);
                string   Check = File.ReadAllText(FilePath);

                if ((Check.Any(s => Crypto_Operation.Common_Encrypted_Chars.Contains(s)) && Check.Any(s => s >= 128)) && fi.Attributes.HasFlag(FileAttributes.Encrypted))
                {
                    return(true);//File Encrypted
                }
                else
                {
                    if ((Check.Any(s => Crypto_Operation.Common_Encrypted_Chars.Contains(s)) && Check.Any(s => s >= 128)) && fi.Attributes.HasFlag(FileAttributes.Encrypted) == false)
                    {
                        File.Encrypt(FilePath);
                        return(true);//File needed encrypted attrib and was encrypted
                    }
                    else
                    {
                        return(false);//File not encrypted
                    }
                }
            }
            catch (Exception e)
            {
                bool FileExists = File_Operation.CHECK_if_File_Exists(FilePath);
                if (FileExists == true && e.Message.Contains("Access to the path") && e.Message.Contains("denied"))
                {
                    //File_Operation.DELETE_File(FilePath);
                }
                Error_Operation.Log_Error("CHECK_File_Encrypted()", e.Message.ToString() + ". Is file on disk check=" + FileExists.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Verbose);
                return(false);//File NOT Encrypted
            }
        }
        private static void READ_Local_Log_Dirs_for_Powershell_or_IIS(string directory)
        {
            try
            {
                if (Directory.Exists(directory))
                {
                    string[] SubDirs = Directory.GetDirectories(directory);

                    for (int x = 0; x < SubDirs.Length; ++x)
                    {
                        string[] FilePaths = Directory.GetFiles(SubDirs[x]);

                        for (int c = 0; c < FilePaths.Length; ++c)
                        {
                            if (FilePaths[c].Contains(".txt") && (FilePaths[c].ToLower().Contains("powershell_transcript.") || FilePaths[c].ToLower().Contains("iis")))
                            {
                                string FileContent = File_Operation.READ_AllText(FilePaths.ElementAt(c));
                                File.Delete(FilePaths.ElementAt(c));
                                FileContents_From_FileReads.Add("DateTime=" + DateTime.Now.ToString(Settings.SWELF_Date_Time_Format) + "  " + FileContent);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Error_Operation.Log_Error("READ_Local_Log_Dirs() ", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
            }
        }
        internal static void READ_Local_Log_Dirs()
        {
            try
            {
                List <string> DirPaths = File_Operation.READ_File_In_List(File_Operation.GET_DirToMonitor_Path()).ToList();
                for (int z = 0; z < DirPaths.Count; ++z)
                {
                    if (Directory.Exists(DirPaths.ElementAt(z)))
                    {
                        if (DirPaths.ElementAt(z).ToLower().Contains("powershell") || DirPaths.ElementAt(z).ToLower().Contains("iis"))
                        {
                            READ_Local_Log_Dirs_for_Powershell_or_IIS(DirPaths.ElementAt(z));
                        }
                        else
                        {
                            string[] FilePaths = Directory.GetFiles(DirPaths.ElementAt(z));

                            for (int x = 0; x < FilePaths.Length - 1; ++x)
                            {
                                if (File_Operation.CHECK_if_File_Exists(FilePaths.ElementAt(x)) && (FilePaths.ElementAt(x).Contains(".txt") || FilePaths.ElementAt(x).Contains(".log")))
                                {
                                    string FileContent = File_Operation.READ_AllText(FilePaths.ElementAt(x));
                                    File.Delete(FilePaths.ElementAt(x));
                                    FileContents_From_FileReads.Add(FileContent);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Error_Operation.Log_Error("READ_Local_Log_Dirs() ", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
            }
        }
Beispiel #9
0
        internal static void Start_Output_Post_Run()
        {
            if (Settings.SWELF_Events_Of_Interest_Matching_EventLogs.Count > 0)
            {
                try
                {
                    if (Settings.output_csv && Program_Start_Args.Count >= 3 && (Settings.Log_Forwarders_HostNames.Count < 1))
                    {
                        File_Operation.Write_Ouput_CSV(Settings.CMDLine_Output_CSV, Settings.SWELF_Events_Of_Interest_Matching_EventLogs);
                    }
                    else
                    {
                        Log_Network_Forwarder.SEND_Logs(Settings.SWELF_Events_Of_Interest_Matching_EventLogs);
                    }
                }
                catch (Exception e)
                {
                    Error_Operation.Log_Error("Start_Output_Post_Run()  Network_Forwarder.SEND_Logs() File_Operation.Write_Ouput_CSV()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
                }

                if (Settings.Logs_Sent_to_ALL_Collectors)
                {
                    Start_Write_To_SWELF_EventLogs();
                }
                Sec_Checks.Post_Run_Sec_Checks();
            }
            Settings.UPDATE_EventLog_w_PlaceKeeper_File();
        }
Beispiel #10
0
 private static bool Check_Event_Log_Is_Blank(string EVT_Log_Name)
 {
     try
     {
         if (Settings.CHECK_If_EventLog_Exsits(EVT_Log_Name))
         {
             if (EventLogSession.GlobalSession.GetLogInformation(EVT_Log_Name, PathType.LogName).RecordCount.Value > 1)
             {
                 return(true);
             }
             else
             {
                 if (EventLogSession.GlobalSession.GetLogInformation(Settings.SWELF_EventLog_Name, PathType.LogName).RecordCount.Value > 0)
                 {
                     return(true);
                 }
                 else
                 {
                     LOG_SEC_CHECK_Fail("Check_Event_Log_Is_Blank() " + EVT_Log_Name + " Eventlog is empty.");
                     return(false);//FAILED
                 }
             }
         }
         else
         {
             return(false);//FAILED
         }
     }
     catch (Exception e)
     {
         Error_Operation.Log_Error("Check_Event_Log_Is_Blank()", "EventLogSession.GlobalSession.GetLogInformation(" + EVT_Log_Name + ", PathType.LogName). EventLog Name was " + EVT_Log_Name + ". Error message was " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
         return(true);//FAILED
     }
 }
Beispiel #11
0
        private static void Start_Searching_Logs(int Index)
        {
            try
            {
                Read_EventLog EVNT_Log = new Read_EventLog();

                Sec_Checks.Live_Run_Sec_Checks(Settings.EventLog_w_PlaceKeeper_List.ElementAt(Index));

                EVNT_Log.READ_EventLog(Settings.EventLog_w_PlaceKeeper_List.ElementAt(Index), Settings.EventLog_w_PlaceKeeper[Settings.EventLog_w_PlaceKeeper_List.ElementAt(Index)]);

                if (Data_Store.contents_of_EventLog.Count > 0)
                {
                    Search_EventLog search_Obj = new Search_EventLog();

                    Data_Store.SWELF_Events_Of_Interest_Matching_EventLogs = search_Obj.Search(Settings.EventLog_w_PlaceKeeper_List.ElementAt(Index));
                }
                Data_Store.contents_of_EventLog.Clear();
            }
            catch (Exception e)
            {
                if (e.Message == "Object reference not set to an instance of an object.")
                {
                    Error_Operation.Log_Error("Start_Read_Search_Write_Forward_EventLogs()", Settings.EventLog_w_PlaceKeeper_List.ElementAt(Index) + " " + e.Message.ToString() + " This error means the EventLog was not read or searched. \n", e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                }
                else if (e.Message.ToString().Contains("The process cannot access the file"))
                {
                    Error_Operation.Log_Error("Start_Read_Search_Write_Forward_EventLogs()", e.Message.ToString() + " OS File lock of vital resource at runtime." + " This error means the EventLog was not read or searched.\n", e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
                }
                else
                {
                    Error_Operation.Log_Error("Start_Read_Search_Write_Forward_EventLogs()", " " + Settings.EventLog_w_PlaceKeeper_List.ElementAt(Settings.Total_Threads_Run) + " x=" + (Settings.Total_Threads_Run).ToString() + " " + e.Message.ToString() + ". Check search Syntx." + " This error means the EventLog was not read or searched.\n", e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                }
            }
            GC.Collect();
        }
Beispiel #12
0
 internal static void SEND_Logs(Queue <EventLog_Entry> Event_logs)
 {
     if (Settings.Log_Forwarders_HostNames.Any(s => string.Equals(s, "127.0.0.1", StringComparison.OrdinalIgnoreCase)) == false && Settings.Log_Forwarders_HostNames.Any(s => string.IsNullOrEmpty(s)) == false)
     {
         if (Settings.AppConfig_File_Args[Settings.SWELF_AppConfig_Args[14]] == "tcp")//If user wants send logs tcp
         {
             for (int x = 0; x < Settings.Log_Forwarders_HostNames.Count; ++x)
             {
                 try
                 {
                     for (int y = 0; y < Event_logs.Count; ++y)
                     {
                         TcpClient     client = new TcpClient(Get_IP_from_Socket_string(Settings.Log_Forwarders_HostNames.ElementAt(x)), Settings.Log_Forwarders_Port.ElementAt(x));
                         NetworkStream stream = client.GetStream();
                         var           data   = GET_Encoding_to_Return(Event_logs.ElementAt(y));
                         stream.Write(data, 0, data.Length);
                         stream.Close();
                         client.Close();
                     }
                 }
                 catch (Exception e)
                 {
                     Settings.Logs_Sent_to_ALL_Collectors = false;
                     Error_Operation.Log_Error("SEND_Logs() [transport_protocol] == tcp", Settings.Log_Forwarders_HostNames.ElementAt(x) + " " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                 }
             }
             Settings.Logs_Sent_to_ALL_Collectors = true;
             Reg_Operation.ADD_or_CHANGE_SWELF_Reg_Key(Reg_Operation.REG_KEY.Logs_Last_Sent, DateTime.Now.ToString());
         }
         else//Default send logs UDP
         {
             for (int x = 0; x < Settings.Log_Forwarders_HostNames.Count; ++x)
             {
                 try
                 {
                     for (int y = 0; y < Event_logs.Count; ++y)
                     {
                         UdpClient client = new UdpClient(Get_IP_from_Socket_string(Settings.Log_Forwarders_HostNames.ElementAt(x)), Settings.Log_Forwarders_Port.ElementAt(x));
                         var       data   = GET_Encoding_to_Return(Event_logs.ElementAt(y));
                         client.Send(data, data.Length);
                         client.Close();
                     }
                 }
                 catch (Exception e)
                 {
                     Settings.Logs_Sent_to_ALL_Collectors = false;
                     Error_Operation.Log_Error("SEND_Logs() else//Default send logs UDP", Settings.Log_Forwarders_HostNames.ElementAt(x) + " " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Verbose);
                 }
             }
             Settings.Logs_Sent_to_ALL_Collectors = true;
             Reg_Operation.ADD_or_CHANGE_SWELF_Reg_Key(Reg_Operation.REG_KEY.Logs_Last_Sent, DateTime.Now.ToString());
         }
     }
 }
Beispiel #13
0
 internal static bool CHECK_if_File_Exists(string FilePath)
 {
     try
     {
         return(File.Exists(FilePath));
     }
     catch (Exception e)
     {
         Error_Operation.Log_Error("CHECK_if_File_Exists()", "FilePath=" + FilePath + " " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
         return(false);
     }
 }
Beispiel #14
0
        internal static bool SEND_Logs(string Log, string FilePath = "", bool DeleteWhenDone = false)
        {
            bool Data_Sent = true;

            if (Settings.Log_Forwarders_HostNames.Any(s => string.Equals(s, "127.0.0.1", StringComparison.OrdinalIgnoreCase)) == false && Settings.Log_Forwarders_HostNames.Any(s => string.IsNullOrEmpty(s)) == false)
            {
                if (Settings.AppConfig_File_Args[Settings.SWELF_AppConfig_Args[14]] == "tcp")//If user wants send logs tcp
                {
                    for (int x = 0; x < Settings.Log_Forwarders_HostNames.Count; ++x)
                    {
                        try
                        {
                            TcpClient     client = new TcpClient(Get_IP_from_Socket_string(Settings.Log_Forwarders_HostNames.ElementAt(x)), Settings.Log_Forwarders_Port.ElementAt(x));
                            NetworkStream stream = client.GetStream();
                            Byte[]        data   = GET_Encoding_to_Return(Log);
                            stream.Write(data, 0, data.Length);
                            stream.Close();
                            client.Close();
                        }
                        catch (Exception e)
                        {
                            Data_Sent = false;
                            Settings.Logs_Sent_to_ALL_Collectors = false;
                            Error_Operation.Log_Error("SEND_Logs() transport_protocol tcp", Settings.Log_Forwarders_HostNames.ElementAt(x) + " " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                        }
                    }
                    Settings.Logs_Sent_to_ALL_Collectors = true;
                    Reg_Operation.ADD_or_CHANGE_SWELF_Reg_Key(Reg_Operation.REG_KEY.Logs_Last_Sent, DateTime.Now.ToString());
                }
                else//Default send logs UDP
                {
                    for (int x = 0; x < Settings.Log_Forwarders_HostNames.Count; ++x)
                    {
                        try
                        {
                            UdpClient client = new UdpClient(Get_IP_from_Socket_string(Settings.Log_Forwarders_HostNames.ElementAt(x)), Settings.Log_Forwarders_Port.ElementAt(x));
                            Data_Sent = SEND_Data_from_File_UDP(Log, client);
                            client.Close();
                        }
                        catch (Exception e)
                        {
                            Data_Sent = false;
                            Settings.Logs_Sent_to_ALL_Collectors = false;
                            Error_Operation.Log_Error("SEND_Logs() Default send logs UDP", Settings.Log_Forwarders_HostNames.ElementAt(x) + " " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                        }
                    }
                    Settings.Logs_Sent_to_ALL_Collectors = true;
                    Reg_Operation.ADD_or_CHANGE_SWELF_Reg_Key(Reg_Operation.REG_KEY.Logs_Last_Sent, DateTime.Now.ToString());
                }
            }
            return(Data_Sent);
        }
Beispiel #15
0
 internal static bool CHECK_If_Running_as_Admin()
 {
     if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
     {
         return(true);
     }
     else
     {
         LOG_SEC_CHECK_Fail("Settings.CHECK_If_Running_as_Admin() " + Settings.ComputerName + " SWELF not running as admin and was unable to read eventlogs.");
         Error_Operation.Log_Error("CHECK_If_Running_as_Admin()", "Not Running SWELF as admin, this means SWELF wont run.", "", Error_Operation.LogSeverity.Critical);
         return(false);
     }
 }
Beispiel #16
0
        internal static void SEND_Logs(Queue <EventLog_Entry> Event_logs)
        {
            if (Settings.Log_Forwarders_HostNames.Any(s => string.Equals(s, "127.0.0.1", StringComparison.OrdinalIgnoreCase)) == false && Settings.Log_Forwarders_HostNames.Any(s => string.IsNullOrEmpty(s)) == false)
            {
                if (Settings.AppConfig_File_Args.ContainsKey(Settings.SWELF_AppConfig_Args[14]) == false)
                {
                    Settings.AppConfig_File_Args.Add(Settings.SWELF_AppConfig_Args[14], "udp");
                }

                if (Settings.AppConfig_File_Args[Settings.SWELF_AppConfig_Args[14]] == "tcp")//If user wants send logs tcp
                {
                    for (int x = 0; x < Settings.Log_Forwarders_HostNames.Count; ++x)
                    {
                        try
                        {
                            for (int y = 0; y < Event_logs.Count; ++y)
                            {
                                Socket_Client_TCP(Crypto_Operation.CONVERT_To_ASCII_Bytes(GET_Log_Output_Format(Event_logs.ElementAt(y))), x);
                            }
                        }
                        catch (Exception e)
                        {
                            Settings.Logs_Sent_to_ALL_Collectors = false;
                            Error_Operation.Log_Error("SEND_Logs() [transport_protocol] == tcp", Settings.Log_Forwarders_HostNames.ElementAt(x) + " " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
                        }
                    }
                    Settings.Logs_Sent_to_ALL_Collectors = true;
                    Reg_Operation.ADD_or_CHANGE_SWELF_Reg_Key(Reg_Operation.REG_KEY.Logs_Last_Sent, DateTime.Now.ToString());
                }
                else//Default send logs UDP
                {
                    for (int x = 0; x < Settings.Log_Forwarders_HostNames.Count; ++x)
                    {
                        try
                        {
                            for (int y = 0; y < Event_logs.Count; ++y)
                            {
                                Socket_Client_UDP(Crypto_Operation.CONVERT_To_ASCII_Bytes(GET_Log_Output_Format(Event_logs.ElementAt(y))), x);
                            }
                        }
                        catch (Exception e)
                        {
                            Settings.Logs_Sent_to_ALL_Collectors = false;
                            Error_Operation.Log_Error("SEND_Logs() else//Default send logs UDP", Settings.Log_Forwarders_HostNames.ElementAt(x) + " " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
                        }
                    }
                    Settings.Logs_Sent_to_ALL_Collectors = true;
                    Reg_Operation.ADD_or_CHANGE_SWELF_Reg_Key(Reg_Operation.REG_KEY.Logs_Last_Sent, DateTime.Now.ToString());
                }
            }
        }
Beispiel #17
0
 internal static void UnSecure_File(string FilePath, int RetryNumber = 0)
 {
     try
     {
         if (File_Operation.CHECK_File_Encrypted(FilePath) == true)
         {
             File.AppendAllText(FilePath, Decrypt_File_Contents(FilePath));
         }
         File.Decrypt(FilePath);
     }
     catch (Exception e)
     {
         if (RetryNumber == 0)
         {
             if (e.Message.ToString().Contains("The input data is not a complete block.") && File_Operation.CHECK_File_Encrypted(FilePath) == false)
             {
                 Encrypt_File_Contents(FilePath);
                 File.Encrypt(FilePath);
                 UnSecure_File(FilePath, 1);
             }
             else
             {
                 File.Decrypt(FilePath);
             }
         }
         if (e.Message.Contains("Padding"))
         {
             Sec_Checks.CHECK_Reg_vs_File_Config(FilePath);
         }
         else if (e.Message.Contains("The input data is not a complete block."))
         {
             if (FilePath.Contains(Settings.AppConfigFile_FileName) && Reg_Operation.CHECK_SWELF_Reg_Key_Exists(Reg_Operation.REG_KEY.ConsoleAppConfig_Contents))
             {
                 File.WriteAllText(Settings.GET_AppConfigFile_Path, Reg_Operation.READ_SWELF_Reg_Key(Reg_Operation.REG_KEY.ConsoleAppConfig_Contents));
             }
             else if (FilePath.Contains(Settings.SearchTermsFileName_FileName) && Reg_Operation.CHECK_SWELF_Reg_Key_Exists(Reg_Operation.REG_KEY.SearchTerms_File_Contents))
             {
                 File.WriteAllText(Settings.GET_AppConfigFile_Path, Reg_Operation.READ_SWELF_Reg_Key(Reg_Operation.REG_KEY.SearchTerms_File_Contents));
             }
             else
             {
                 //error is logic
             }
         }
         else
         {
             Error_Operation.Log_Error("UnLock_File()", e.Message.ToString() + " " + FilePath + "  retry=" + RetryNumber, "", Error_Operation.LogSeverity.FailureAudit);
         }
     }
 }
Beispiel #18
0
 private static void Start_Write_To_SWELF_EventLogs()
 {
     for (int z = 0; z < Settings.SWELF_Events_Of_Interest_Matching_EventLogs.Count; ++z)
     {
         try
         {
             EventLog_SWELF.WRITE_EventLog_From_SWELF_Search(Settings.SWELF_Events_Of_Interest_Matching_EventLogs.ElementAt(z));
         }
         catch (Exception e)
         {
             Error_Operation.Log_Error("Start_Write_To_SWELF_EventLogs()", "An EventLog " + Settings.SWELF_Events_Of_Interest_Matching_EventLogs.ElementAt(z).GET_XML_of_Log + " errored on write to SWELF Eventlog with the following error " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
         }
     }
 }
Beispiel #19
0
 internal static void DELETE_SWELF_Reg_Key(REG_KEY Key)
 {
     try
     {
         BASE_SWELF_KEY.DeleteValue(SWELF_Keys[(int)Key]);
     }
     catch (Exception e)
     {
         if (e.Message.Contains("No value exists with that name") == false)
         {
             Error_Operation.Log_Error("DELETE_SWELF_Reg_Key()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Verbose);
         }
     }
 }
Beispiel #20
0
 internal static string[] READ_File_In_StringArray(string FilePath)
 {
     if (CHECK_if_File_Exists(FilePath))
     {
         Crypto_Operation.UnSecure_File(FilePath);
         string[] Contents = File.ReadAllLines(FilePath);
         Crypto_Operation.Secure_File(FilePath);
         return(Contents);
     }
     else
     {
         Error_Operation.Log_Error("READ_File_In_StringArray()", "File not found " + FilePath, "", Error_Operation.LogSeverity.Informataion);
         return(File.ReadAllLines(FilePath));
     }
 }
Beispiel #21
0
        private static void CHECK_If_App_Has_Run_To_Long()
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            while (watch.Elapsed.Hours < 1)
            {
                Thread.Sleep(600000);
            }
            watch.Stop();
            var elapsedTime = watch.Elapsed;

            RanToLongTiner = true;
            Start_Output_Post_Run();
            Error_Operation.Log_Error("CHECK_If_App_Has_Run_To_Long()", "SWELF's time running on machine timer says that SWELF to long (" + elapsedTime.ToString() + ") this could be for many reasons. Most likely is that there are to many log sources your trying to read into SWELF or that some of the logs files are to large to be read in with all the other searchs. Try running SWELF in sequence. ", "", Error_Operation.LogSeverity.Critical);
            Environment.Exit((int)Error_Operation.EventID.SWELF_MAIN_APP_ERROR);
        }
Beispiel #22
0
 internal static void Write_IP_Output(List <string> IPs)
 {
     File.Delete(Settings.IPs_File_Path);
     File.Create(Settings.IPs_File_Path).Close();
     for (int x = 0; x < IPs.Count; ++x)
     {
         try
         {
             File.AppendAllText(Settings.IPs_File_Path, IPs.ElementAt(x) + "\n");
         }
         catch (Exception e)
         {
             Error_Operation.Log_Error("Write_IP_Output()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
         }
     }
     CHECK_File_Size(Settings.IPs_File_Path, .0002);
 }
Beispiel #23
0
        private static void Start_Run_Plugins()
        {
            try
            {
                Settings.Plugin_Search_Terms_Unparsed = Settings.Plugin_Search_Terms_Unparsed.Distinct().ToList();

                for (int x = 0; x < Settings.Plugin_Search_Terms_Unparsed.Count; ++x)
                {
                    EventLog_Entry PSLog = new EventLog_Entry();
                    PSLog.ComputerName    = Settings.ComputerName;
                    PSLog.EventID         = Convert.ToInt32(Error_Operation.EventID.Powershell_Plugin);
                    PSLog.LogName         = "SWELF PowerShell Plugin Output";
                    PSLog.Severity        = "Information";
                    PSLog.CreatedTime     = DateTime.Now;
                    PSLog.TaskDisplayName = "SWELF Powershell Plugin Output";
                    PSLog.SearchRule      = "SWELF_Powershell_Plugin=" + Settings.Plugin_Search_Terms_Unparsed.ElementAt(x);
                    PSLog.UserID          = Environment.UserName;

                    PSLog.EventData = Powershell_Plugin.Run_PS_Script(Settings.Plugin_Search_Terms_Unparsed.ElementAt(x).Split(Settings.SplitChar_SearchCommandSplit[0]).ElementAt(0), Settings.Plugin_Search_Terms_Unparsed.ElementAt(x).Split(Settings.SplitChar_SearchCommandSplit[0]).ElementAt(2));

                    if (PSLog.EventData.ToLower().Contains(Settings.Plugin_Search_Terms_Unparsed.ElementAt(x).Split(Settings.SplitChar_SearchCommandSplit[0]).ElementAt(1).ToLower()))
                    {
                        Settings.PS_Plugin_SWELF_Events_Of_Interest_Matching_EventLogs.Enqueue(PSLog);

                        try
                        {
                            EventLog_SWELF.WRITE_EventLog_From_SWELF_Search(Settings.PS_Plugin_SWELF_Events_Of_Interest_Matching_EventLogs.ElementAt(0));
                            Log_Network_Forwarder.SEND_Logs(Settings.PS_Plugin_SWELF_Events_Of_Interest_Matching_EventLogs);
                        }
                        catch (Exception e)
                        {
                            Error_Operation.Log_Error("Network_Forwarder.SEND_Logs(), EventLog_SWELF.WRITE_EventLog_From_SWELF_Search(), or Start_Run_Plugins()", Settings.EventLog_w_PlaceKeeper_List.ElementAt(x) + " HostEventLogAgent_Eventlog.WRITE_EventLog " + e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Warning);
                        }
                    }
                }
                Settings.PS_PluginDone = true;
                GC.Collect();
            }
            catch (Exception e)
            {
                Error_Operation.Log_Error("Powershell_Plugin.Run_PS_Script() ", e.StackTrace.ToString(), e.Message.ToString(), Error_Operation.LogSeverity.Warning);
                Error_Operation.SEND_Errors_To_Central_Location();
                Settings.PS_PluginDone = true;
            }
        }
        internal static string Run_PS_Script(String PowershellSciptLocation, string PowershellSciptArgs = "")
        {
            if (File_Operation.CHECK_if_File_Exists(PowershellSciptLocation))
            {
                ScriptContents = File_Operation.READ_AllText(PowershellSciptLocation);

                if (CallAntimalwareScanInterface(Get_SHA256(PowershellSciptLocation), ScriptContents) < 32768)
                {
                    powershellSciptLocation = PowershellSciptLocation;
                    powershellSciptArgs     = PowershellSciptArgs;

                    ProcessStartInfo startInfo = new ProcessStartInfo("powershell", "-ExecutionPolicy Bypass .\\" + Path.GetFileName(PowershellSciptLocation));
                    startInfo.WorkingDirectory       = Path.GetDirectoryName(PowershellSciptLocation);
                    startInfo.RedirectStandardOutput = true;
                    startInfo.RedirectStandardError  = true;
                    startInfo.LoadUserProfile        = true;
                    startInfo.UseShellExecute        = false;
                    startInfo.CreateNoWindow         = true;
                    Process process = new Process();
                    process.StartInfo = startInfo;
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    if (string.IsNullOrEmpty(output))
                    {
                        output += "\nPS Plugin ERROR: " + process.StandardError.ReadToEnd();
                    }
                    if (string.IsNullOrEmpty(ScriptContents) == false || string.IsNullOrWhiteSpace(ScriptContents) == false)
                    {
                        Settings.WhiteList_Search_Terms_Unparsed.Add(ScriptContents + "~" + "microsoft-windows-powershell/operational" + "~");
                        Settings.WhiteList_Search_Terms_Unparsed.Add(ScriptContents + "~" + "windows powershell" + "~");
                    }
                    return(output);
                }
                else
                {
                    Error_Operation.Log_Error("Run_PS_Script() POSSIBLE MALWARE DETECTED", "Script located at " + powershellSciptLocation + " SHA256=" + Get_SHA256(PowershellSciptLocation) + ". Script is Malware according to AMSI. SWELF converted the contents to Base64 1 time for the purpose of the log size. Malware Script Contents = " + Base64Encode(ScriptContents), "", Error_Operation.LogSeverity.Critical);
                    return("POSSIBLE MALWARE DETECTED - Script located at " + powershellSciptLocation + " SHA256=" + Get_SHA256(PowershellSciptLocation) + ". Script is Malware according to AMSI. SWELF converted the contents to Base64 1 time for the purpose of the log size. Malware Script Contents = " + Base64Encode(ScriptContents));
                }
            }
            else
            {
                Error_Operation.Log_Error("Run_PS_Script()", PowershellSciptLocation + " is not a valid file on " + Settings.ComputerName, "", Error_Operation.LogSeverity.Warning);
                return(PowershellSciptLocation + " is not a valid file on " + Settings.ComputerName);
            }
        }
        private static Dictionary <string, int> ReadLocalFiles_Log_File_Tracking = new Dictionary <string, int>();//Filepath,Line Number where it left off

        internal static void READ_Local_Log_Files()
        {
            List <string> FilePaths = File_Operation.READ_File_In_List(File_Operation.GET_FilesToMonitor_Path()).ToList();

            for (int z = 0; z < FilePaths.Count; ++z)
            {
                try
                {
                    string FileContent = File_Operation.READ_AllText(FilePaths.ElementAt(z));
                    File.Delete(FilePaths.ElementAt(z));
                    FileContents_From_FileReads.Add("DateTime = " + DateTime.Now.ToString(Settings.SWELF_Date_Time_Format) + "  " + FileContent);
                }
                catch (Exception e)
                {
                    Error_Operation.Log_Error("READ_Local_Log_Files() ", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                }
            }
        }
Beispiel #26
0
        internal static void SET_Event_Log_MaxSize(string LogName, long Size = 0)
        {
            if (Size == 0)
            {
                Size = Default_Size;
            }
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Eventlog\" + LogName, true);

            if (key == null)
            {
                Error_Operation.Log_Error("SET_Event_Log_MaxSize(string LogName)", "Registry key for this Event Log does not exist.", "", Error_Operation.LogSeverity.Warning);
            }
            else
            {
                key.SetValue("MaxSize", Convert.ToInt32(Size));
                Registry.LocalMachine.Close();
            }
        }
Beispiel #27
0
 internal static void UPDATE_Local_Config_With_Central_Config(string WebPath, string LocalPath, string FileName)
 {
     if (string.IsNullOrEmpty(Central_Config_File_Web_Cache))
     {
         File_Operation.DELETE_File(LocalPath);    //remove old config file
         Wclient.DownloadFile(WebPath, LocalPath); //if match read local files
     }
     else
     {
         File_Operation.DELETE_File(LocalPath);//remove old config file
         File_Operation.APPEND_AllTXT(LocalPath, Central_Config_File_Web_Cache);
     }
     Error_Operation.Log_Error("GET_Central_Config_File()", "Updated " + FileName + " from " + WebPath + ". It was downloaded to " + LocalPath, "", Error_Operation.LogSeverity.Verbose, Error_Operation.EventID.SWELF_Central_Config_Changed);//log change
     if (File_Operation.CHECK_File_Encrypted(LocalPath) == false)
     {
         Crypto_Operation.Secure_File(LocalPath);
     }
 }
Beispiel #28
0
 private static string READ_SWELF_Reg_Key(string Key)
 {
     try
     {
         if (CHECK_SWELF_Reg_Key_Exists(Key))
         {
             if (Crypto_Operation.CHECK_Value_Encrypted(Crypto_Operation.ObjectToByteArray(BASE_SWELF_KEY.GetValue(Key))))
             {
                 try
                 {
                     return(Crypto_Operation.UnProtect_Data_Value((byte[])BASE_SWELF_KEY.GetValue(Key)));
                 }
                 catch (Exception e)
                 {
                     if (e.Message.Contains("Unable to cast object of type 'System.String' to type 'System.Byte[]'."))
                     {
                         ADD_or_CHANGE_SWELF_Reg_Key(Key, (string)BASE_SWELF_KEY.GetValue(Key));
                     }
                     try
                     {
                         return(Crypto_Operation.UnProtect_Data_Value((byte[])BASE_SWELF_KEY.GetValue(Key)));
                     }
                     catch (Exception ex)
                     {
                         return("");
                     }
                 }
             }
             else
             {
                 return(Crypto_Operation.UnProtect_Data_Value((byte[])BASE_SWELF_KEY.GetValue(Key)));
             }
         }
         else
         {
             return("");
         }
     }
     catch (Exception e)
     {
         Error_Operation.Log_Error("READ_SWELF_Reg_Key()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Verbose);
         return("");
     }
 }
Beispiel #29
0
 internal static bool CHECK_Eventlog_SWELF_Reg_Key_Exists(string Key)
 {
     try
     {
         if (BASE_SWELF_KEY.GetValue(Key) != null)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception e)
     {
         Error_Operation.Log_Error("CHECK_Eventlog_SWELF_Reg_Key_Exists()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Verbose);
         return(false);
     }
 }
Beispiel #30
0
        internal static void WRITE_Default_Configs_Files_and_Reg()
        {
            File_Operation.Turnicate_File(GET_AppConfigFile_Path);
            File_Operation.Turnicate_File(GET_EventLogID_PlaceHolder_Path);
            File_Operation.Turnicate_File(GET_SearchTermsFile_Path);
            File_Operation.Turnicate_File(GET_WhiteList_SearchTermsFile_Path);
            File_Operation.Turnicate_File(GET_SearchTermsFile_PLUGIN_Path);

            File_Operation.CREATE_NEW_Files_And_Dirs(Config_File_Location, AppConfigFile_FileName, File_Operation.GET_Default_ConsoleAppConfig_File_Contents, true);
            File_Operation.CREATE_NEW_Files_And_Dirs(Config_File_Location, EventLogID_PlaceHolde_FileName, File_Operation.GET_Default_Eventlog_with_PlaceKeeper_File_Contents, true);

            File_Operation.CREATE_NEW_Files_And_Dirs(Search_File_Location, SearchTermsFileName_FileName, File_Operation.GET_Default_Logs_Search_File_Contents, true);
            File_Operation.CREATE_NEW_Files_And_Dirs(Search_File_Location, Search_WhiteList_FileName, "", true);

            File_Operation.CREATE_NEW_Files_And_Dirs(Plugin_Search_Location, SearchTermsFileName_FileName, File_Operation.GET_Default_Powershell_Plugins_File_Contents, true);

            Reg_Operation.WRITE_Default_SWELF_Reg_Keys();

            Error_Operation.Log_Error("WRITE_Default_Configs()", "SWELF created new default config files for all settings", "", Error_Operation.LogSeverity.FailureAudit);
        }