Example #1
0
        private void CheckForRun()
        {
            if (isProcessing == false && nextRun <= DateTime.Now)
            {
                EventLogger.DebugEntry("Creating complex thread", EventLogEntryType.Information);

                ThreadHolder exportThread = new ThreadHolder();
                Guid         guid         = Guid.NewGuid();

                exportThread.scanThread = new ScanThread(this, guid);
                // Here you can add the resuming, on certain conditions
                // In my case I insert data to myThread which contains all the necessary objects to continue processing from the last halt
                // exportThread.myThread = new MyThreadComplex(this, guid, threadType, 3);

                if (CreateWorkerThread(exportThread, guid))
                {
                    isProcessing = true;
                    EventLogger.DebugEntry("Creating complex thread - successful", EventLogEntryType.Information);
                }
                else
                {
                    EventLogger.Entry("Creating complex thread - failed", EventLogEntryType.Error);
                }
            }
        }
Example #2
0
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            runningWorkers -= 1;
            List <String> res = (List <String>)e.Result;

            if (!(e.Error == null))
            {
                EventLogger.Entry("Service Error: !" + e.Error.Message + "\r\n\r\n" + e.Error.StackTrace, EventLogEntryType.Error);
            }
            else
            {
                EventLogger.DebugEntry("Service Information: Done!", EventLogEntryType.Information);
                // send mail
                SendMail m = new SendMail();
                m.generateReport(res);
                res.Clear();
            }
            while (runningWorkers < 8 && workerCounter < maxWorker)
            {
                BackgroundWorker newWorker = startWorker();
                newWorker.RunWorkerAsync(++lastWorkerStarted);
            }
            BackgroundWorker bw = (BackgroundWorker)sender;

            bw.Dispose();
        }
Example #3
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            try {
                if (System.Environment.UserInteractive)
                {
                    if (args.Length > 0)
                    {
                        switch (args[0])
                        {
                        case "-install": {
                            ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                            break;
                        }

                        case "-uninstall":
                            ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                            break;
                        }
                    }
                }
                else
                {
                    ServiceBase[] ServicesToRun =
                    {
                        new MainScanService()
                    };
                    ServiceBase.Run(ServicesToRun);
                }
            } catch (Exception e) {
                EventLogger.Entry("Service Error:  - Main crashed - " + e, EventLogEntryType.Error);
            }
        }
Example #4
0
 private void bw_DoWork(object sender, DoWorkEventArgs e)
 {
     try {
         BackgroundWorker worker           = sender as BackgroundWorker;
         List <string>    files            = (List <string>)e.Argument;
         List <string>    possibleInfected = Properties.Settings.Default.EvilStrings.Cast <string>().ToList();
         // Regex malicious = new Regex(@"(mail|eval|base64_decode|str_rot13|chmod|fwrite|exec|passthru|shell_exec|system|proc_open|popen|curl_exec|curl_multi_exec|show_source|fsockopen|pfsockopen|stream_socket_client) *\(");
         foreach (string file in files)
         {
             if (MaliciousHashes.checkHash(file.create(true)))
             {
                 infectedFiles.Add(file);
             }
             string evilString          = "";
             int    evilLine            = 0;
             IEnumerable <string> lines = System.IO.File.ReadLines(file);
             foreach (string line in lines)
             {
                 evilLine++;
                 if (possibleInfected.Any(x => { evilString = x;
                                                 return(line.Contains(x)); }))
                 {
                     infectedFiles.Add(file + " <-- <b>Found possible evil string (" + evilString + " on line: " + evilLine + ")</b>");
                 }
                 //foreach(Match match in malicious.Matches(line)) {
                 //    infectedFiles.Add(file + " <-- <b>Found possible evil string (" + match.Value + " on line: " + evilLine + ")</b>");
                 //}
             }
         }
     } catch (Exception ex) {
         EventLogger.Entry("Service Error: " + ex.Message + "\r\n\r\n" + ex.StackTrace + "\r\n\r\n" + ex.Source, EventLogEntryType.Error);
     }
     allDone++;
 }
Example #5
0
 protected override void OnStop()
 {
     try {
         ServiceExecution.GetInstance().StopServiceExecution();
         thread.Join();
         EventLogger.DebugEntry("Service stopped", EventLogEntryType.Information);
     } catch (Exception e) {
         EventLogger.Entry("Service Error: Stopping - " + e, EventLogEntryType.Error);
     }
 }
Example #6
0
        public void StartServiceExecution()
        {
            try {
                currentState = State.Running;

                while (currentState == State.Running)
                {
                    if (!connectionActive)
                    {
                        connectionActive = true;
                        EventLogger.DebugEntry("Main-Loop", EventLogEntryType.Information);
                        IPAddress ipAd = IPAddress.Parse(Properties.Settings.Default.IPAddress);
                        myList = new TcpListener(ipAd, 19358);

                        myList.Start();

                        s = myList.AcceptSocket();

                        byte[] b = new byte[100];
                        int    k = s.Receive(b);

                        if (compareBytes(b, GetBytes("startScan", 100)))
                        {
                            CheckForRun();
                        }
                    }
                    EventLogger.DebugEntry("Main-Loop - Sleep", EventLogEntryType.Information);
                }


                while (currentState == State.Shutting_Down)
                {
                    using (LockHolder <Dictionary <Guid, ThreadHolder> > lockObj =
                               new LockHolder <Dictionary <Guid, ThreadHolder> >(runningThreads, 1000)) {
                        if (lockObj.LockSuccessful)
                        {
                            foreach (ThreadHolder currentThread in runningThreads.Values)
                            {
                                // Now break the processing of the complex thread
                                currentThread.scanThread.BreakOperation();
                            }

                            // If no more threads are left, set the state to stopped
                            if (runningThreads.Count == 0)
                            {
                                currentState = State.Stopped;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                EventLogger.Entry("Service Error: " + e, EventLogEntryType.Error);
            }
        }
Example #7
0
 protected override void OnStart(string[] args)
 {
     try {
         thread = new Thread(ServiceExecution.GetInstance().StartServiceExecution)
         {
             Name = "Service Executer"
         };
         thread.Start();
         EventLogger.DebugEntry("Service started", EventLogEntryType.Information);
     } catch (Exception e) {
         EventLogger.Entry("Service Error: Starting - " + e, EventLogEntryType.Error);
     }
 }
Example #8
0
 public Worker(StringCollection servers)
 {
     try {
         EventLogger.DebugEntry("Service Start: Service started", EventLogEntryType.SuccessAudit);
         List <String> list = new List <String>();
         list      = servers.Cast <String>().ToList();
         maxWorker = list.Count;
         for (int i = 0; i < maxWorkersRunning && i < list.Count; i++)
         {
             BackgroundWorker bw = startWorker();
             bw.RunWorkerAsync(list[++lastWorkerStarted]);
         }
     } catch (Exception ex) {
         EventLogger.Entry("!Service Error: Worker error, could not start first itteration!;  " + ex.StackTrace + " \r\n\r\nServers count: " + servers.Count, EventLogEntryType.Error);
     }
 }
Example #9
0
        public void Process(bool resumeProcessing = false)
        {
            startTime = DateTime.Now;

            try {
                if (resumeProcessing)
                {
                    ResumeProcessingData();
                }
                else
                {
                    ProcessingData();
                }
            } catch (Exception e) {
                EventLogger.Entry("Service Error: Thread crashed - " + e, EventLogEntryType.Error);
            } finally {
                // Make sure, the thread gets closed
                // Add exeption-handling before, if needed!!!
                serviceExecution.ThreadFinished(threadId);
            }
        }
Example #10
0
        public void StartServiceExecution()
        {
            try {
                currentState = State.Running;

                while (currentState == State.Running)
                {
                    EventLogger.DebugEntry("Main-Loop", EventLogEntryType.Information);
                    Thread.Sleep(10000);
                    CheckForRun();

                    EventLogger.DebugEntry("Main-Loop - Sleep", EventLogEntryType.Information);
                    Thread.Sleep(Properties.Settings.Default.interval * 1000 * 60);
                }


                while (currentState == State.Shutting_Down)
                {
                    using (LockHolder <Dictionary <Guid, ThreadHolder> > lockObj =
                               new LockHolder <Dictionary <Guid, ThreadHolder> >(runningThreads, 1000)) {
                        if (lockObj.LockSuccessful)
                        {
                            foreach (ThreadHolder currentThread in runningThreads.Values)
                            {
                                // Now break the processing of the complex thread
                                currentThread.scanThread.BreakOperation();
                            }

                            // If no more threads are left, set the state to stopped
                            if (runningThreads.Count == 0)
                            {
                                currentState = State.Stopped;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                EventLogger.Entry("Service Error: " + e + "\r\n\r\n" + e.StackTrace, EventLogEntryType.Error);
            }
        }
Example #11
0
        private void CheckForRun()
        {
            if (isProcessing == false)
            {
                EventLogger.DebugEntry("Creating complex thread", EventLogEntryType.Information);

                ThreadHolder exportThread = new ThreadHolder();
                Guid         guid         = Guid.NewGuid();

                exportThread.scanThread = new ScanThread(this, guid);

                if (CreateWorkerThread(exportThread, guid))
                {
                    isProcessing = true;
                    EventLogger.DebugEntry("Creating complex thread - successful", EventLogEntryType.Information);
                }
                else
                {
                    EventLogger.Entry("Creating complex thread - failed", EventLogEntryType.Error);
                }
            }
        }
Example #12
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            String           value  = (String)e.Argument;

            try {
                List <String> res     = new List <String>();
                TcpClient     tcpclnt = new TcpClient();

                tcpclnt.Connect(value, 19358);
                // use the ipaddress as in the server program

                String str = "startScan";
                Stream stm = tcpclnt.GetStream();

                ASCIIEncoding asen = new ASCIIEncoding();
                byte[]        ba   = asen.GetBytes(str);

                stm.Write(ba, 0, ba.Length);
                byte[] bb        = new byte[512];
                int    k         = 0;
                String tmpString = "";
                do
                {
                    k         = stm.Read(bb, 0, 512);
                    tmpString = new String(asen.GetChars(bb));
                    tmpString = tmpString.Replace("\0", string.Empty);
                    res.Add(tmpString);
                } while(tmpString != "done");

                tcpclnt.Close();
                e.Result = res;
            } catch (Exception ex) {
                EventLogger.Entry("Service Error: TCP Client connect error " + ex.StackTrace + "\r\n" + ex.Message + "\r\n\r\n" + ex.Data + "\r\n\r\ncurrentWorker: " + workerCounter, EventLogEntryType.Error);
            }
        }
Example #13
0
        public ScanServiceServer()
        {
            try {
                InitializeComponent();

                finalExit = true;

                if (!EventLog.SourceExists("ScanServiceServer"))
                {
                    EventLog.CreateEventSource("ScanServiceServer", "");
                }

                ScanServiceServerEventLog.Source = "ScanServiceServer";
                ScanServiceServerEventLog.Log    = "";

                ServiceExecution.GetInstance().scanService = this;

                EventLogger.log = ScanServiceServerEventLog;

                // ServiceExecution.GetInstance().myService = this;
            } catch (Exception e) {
                EventLogger.Entry("Service Error: Init - " + e, EventLogEntryType.Error);
            }
        }