コード例 #1
0
        public static string runScanScript(string scriptName, string serverName, string serverPort, string userName, string userPassword, string scriptParameter, int thread)
        {
            NexposeAdhocScanLog = ConfigurationManager.AppSettings["NexposeAdhocScanErrorLog"];
            Llog = log4net.LogManager.GetLogger(NexposeAdhocScanLog);
            log4netConfigFile = ConfigurationManager.AppSettings["Log4netConfig"];
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(log4netConfigFile));
            saveSiteLog = ConfigurationManager.AppSettings["saveSiteErrorLog"];
            Logger      = log4net.LogManager.GetLogger(saveSiteLog);

            //Library.WriteErrorLog(logFilePath, "Thread " + thread + ": Below parameter received:");
            //Library.WriteErrorLog(logFilePath, "Thread " + thread + ": "  + scriptName);
            //Library.WriteErrorLog(logFilePath, "Thread " + thread + ":" + serverName);
            //Library.WriteErrorLog(logFilePath, "Thread " + thread + ":" + serverPort);
            //Library.WriteErrorLog(logFilePath, "Thread " + thread + ":" + userName);
            //Library.WriteErrorLog(logFilePath, "Thread " + thread + ":" + userPassword);
            //Library.WriteErrorLog(logFilePath, "Thread " + thread + ":" + scriptParameter);
            using (Process p = new Process())
            {
                try
                {
                    ProcessStartInfo info = new ProcessStartInfo(rubyPath + @"bin\ruby.exe");
                    //Library.WriteErrorLog(programLogFilePath, userPassword);
                    string password = userPassword.TrimEnd(Environment.NewLine.ToCharArray());
                    info.Arguments = scriptName + " " + serverName + " " + serverPort + " " + userName + " " + userPassword + " " + scriptParameter; // set args
                    //Library.WriteErrorLog(programLogFilePath, info.Arguments);
                    //Debug.WriteLine(info.Arguments);
                    info.RedirectStandardInput  = true;
                    info.RedirectStandardOutput = true;
                    info.UseShellExecute        = false;
                    p.StartInfo = info;
                    p.Start();
                    string output = p.StandardOutput.ReadToEnd();
                    p.WaitForExit();
                    return(output);
                    // process output
                }
                catch (Exception ex)
                {
                    //Library.WriteErrorLog(logFilePath, "Thread " + thread + ": Failed to trigger ruby script: " + scriptName);
                    //Library.WriteErrorLog(logFilePath, "Thread " + thread + ": " + ex.ToString());
                    Llog.Warn("Thread " + thread + ": Failed to trigger ruby script: " + scriptName);
                    Llog.Warn("Thread " + thread + ": " + ex.ToString());
                    string subject = "Failed to trigger ruby script " + scriptName;
                    string body    = ex.ToString();
                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                    return("-1");
                }
            }
        }
コード例 #2
0
 public static string runSiteScript(string scriptName, string serverName, string serverPort, string userName, string userPassword, string scriptParameter)
 {
     //Library.WriteErrorLog(logFileSaveSitePath, "Below parameter received:");
     //Library.WriteErrorLog(logFileSaveSitePath, scriptName);
     //Library.WriteErrorLog(logFileSaveSitePath, serverName);
     //Library.WriteErrorLog(logFileSaveSitePath, serverPort);
     //Library.WriteErrorLog(logFileSaveSitePath, userNmame);
     //Library.WriteErrorLog(logFileSaveSitePath, userPassword);
     //Library.WriteErrorLog(logFileSaveSitePath, scriptParameter);
     using (Process p = new Process())
     {
         try
         {
             ProcessStartInfo info = new ProcessStartInfo(rubyPath + @"bin\ruby.exe");
             //Library.WriteErrorLog(programLogFilePath, userPassword);
             string password = userPassword.TrimEnd(Environment.NewLine.ToCharArray());
             info.Arguments = scriptName + " " + serverName + " " + serverPort + " " + userName + " " + userPassword + " " + scriptParameter; // set args
             //Library.WriteErrorLog(programLogFilePath, info.Arguments);
             //Debug.WriteLine(info.Arguments);
             info.RedirectStandardInput  = true;
             info.RedirectStandardOutput = true;
             info.UseShellExecute        = false;
             p.StartInfo = info;
             p.Start();
             string output = p.StandardOutput.ReadToEnd();
             p.WaitForExit();
             return(output);
             // process output
         }
         catch (Exception ex)
         {
             //Library.WriteErrorLog(logFilePath, "Failed to trigger ruby script: " + scriptName);
             //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());
             Logger.Warn("Failed to trigger ruby script: " + scriptName);
             Logger.Warn(ex.ToString());
             string subject = "Failed to trigger ruby script " + scriptName;
             string body    = ex.ToString();
             Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
             return("-1");
         }
     }
 }
コード例 #3
0
        public static int getSite()
        {
            saveSiteLog       = ConfigurationManager.AppSettings["saveSiteErrorLog"];
            Llog              = log4net.LogManager.GetLogger(saveSiteLog);
            log4netConfigFile = ConfigurationManager.AppSettings["Log4netConfig"];
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(log4netConfigFile));


            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
            byte[] bytesAlreadyEncrypted = null;
            try
            {
                bytesAlreadyEncrypted = File.ReadAllBytes(passworFile);
            }
            catch (Exception ex)
            {
                //Library.WriteErrorLog(logFileSaveSitePath, "failed to read the password file");
                //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());

                Llog.Info("failed to read the password file");
                Llog.Info(ex.ToString());

                string subject = "CCSVM SaveSites: Failed to read the password file";
                string body    = ex.ToString();
                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                return(-1);
            }
            byte[] bytesDecrypted      = new CryptoLibrary().AES_Decrypt(bytesAlreadyEncrypted, passwordBytes);
            string ccsVMServerPassword = Encoding.UTF8.GetString(bytesDecrypted);
            //Library.WriteErrorLog(logFileSaveSitePath, "userPassword:"******"Included IP List file path: " + includedFilePath);
            //Library.WriteErrorLog(logFileSaveSitePath, "Excluded IP List file path: " + excludedFilePath);

            Llog.Info("Included IP List file path: " + includedFilePath);
            Llog.Info("Excluded IP List file path: " + excludedFilePath);



            string month = "";

            if (today.Month < 10)
            {
                month = "0" + today.Month;
            }
            string day = "";

            if (today.Day < 10)
            {
                day = "0" + today.Day;
            }
            string includedFilePathNew = Path.GetDirectoryName(includedFilePath) + "\\" + Path.GetFileNameWithoutExtension(includedFilePath) + "-" + today.Year + month + day + Path.GetExtension(includedFilePath);
            string excludedFilePathNew = Path.GetDirectoryName(excludedFilePath) + "\\" + Path.GetFileNameWithoutExtension(excludedFilePath) + "-" + today.Year + month + day + Path.GetExtension(excludedFilePath);
            string includedFilePathTmp = includedFilePath + "-old";
            string excludedFilePathTmp = excludedFilePath + "-old";
            bool   getIncluded         = false;
            bool   getExcluded         = false;
            bool   processIncluded     = false;
            bool   processExcluded     = false;
            bool   otherError          = false; //error code -2

            //Library.WriteErrorLog(logFileSaveSitePath, "New Included IP List file path: " + includedFilePathNew);
            //Library.WriteErrorLog(logFileSaveSitePath, "Calling included ruby script: " + getSiteIncluded + " " + includedFilePathNew);

            Llog.Info("New Included IP List file path: " + includedFilePathNew);
            Llog.Info("Calling included ruby script: " + getSiteIncluded + " " + includedFilePathNew);

            string resultIncluded = CallRuby.runSiteScript(getSiteIncluded, ccsVMServerIP, ccsVMServerPort, ccsVMServerUser, ccsVMServerPassword, includedFilePathNew);

            Llog.Info("Calling included ruby script result: " + resultIncluded);

            //Library.WriteErrorLog(logFileSaveSitePath, "Calling included ruby script result: " + resultIncluded);

            if (resultIncluded.Contains("getsuccess"))
            {
                getIncluded = true;
                if (File.Exists(includedFilePathNew))
                {
                    //Library.WriteErrorLog(logFileSaveSitePath, "Calling ruby script successfully");
                    //Library.WriteErrorLog(logFileSaveSitePath, "Starting to replace the included csv file");

                    Llog.Info("Calling ruby script successfully");
                    Llog.Info("Starting to replace the included csv file");

                    FileStream streamIncluded = null;
                    while (true)
                    {
                        //remove old file
                        if (File.Exists(includedFilePathTmp))
                        {
                            //Library.WriteErrorLog(logFileSaveSitePath, "Clean up old file: " + includedFilePathTmp);
                            Llog.Info("Clean up old file: " + includedFilePathTmp);

                            try
                            {
                                File.Delete(includedFilePathTmp);
                            }
                            catch (Exception ex)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "Failed to remove old file: " + includedFilePathTmp);
                                //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());

                                Llog.Error("Failed to remove old file: " + includedFilePathTmp);
                                Llog.Error(ex.ToString());

                                string subject = "CCSVM SaveSites: Failed to remove old file";
                                string body    = includedFilePathTmp + ": " + ex.ToString();
                                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                otherError = true;
                                return(-2);
                            }
                        }
                        //replace the file
                        if (File.Exists(includedFilePath))
                        {
                            try
                            {
                                streamIncluded = File.Open(includedFilePath, FileMode.Open, FileAccess.Read, FileShare.None);
                                streamIncluded.Close();
                                streamIncluded = null;
                                try
                                {
                                    File.Move(includedFilePath, includedFilePathTmp);
                                    //Library.WriteErrorLog(logFileSaveSitePath, "File successfully backup as: " + includedFilePathTmp);
                                    Llog.Info("File successfully backup as: " + includedFilePathTmp);
                                }
                                catch (Exception ex)
                                {
                                    //Library.WriteErrorLog(logFileSaveSitePath, "Failed to backup : " + includedFilePath);
                                    //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());

                                    Llog.Error("Failed to backup : " + includedFilePath);
                                    Llog.Error(ex.ToString());

                                    string subject = "CCSVM SaveSites: Failed to backup included csv file";
                                    string body    = includedFilePath + ": " + ex.ToString();
                                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                    otherError = true;
                                    return(-2);
                                }
                            }
                            catch (Exception)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "File in use, sleep for 5 seconds: " + includedFilePath);
                                Llog.Error("File in use, sleep for 5 seconds: " + includedFilePath);
                                System.Threading.Thread.Sleep(5000);
                                continue;
                            }
                            //replace with the new file
                            try
                            {
                                File.Move(includedFilePathNew, includedFilePath);
                            }
                            catch (Exception ex)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "Failed to move the new file: " + includedFilePathNew);
                                Llog.Error("Failed to move the new file: " + includedFilePathNew);
                                Llog.Error(ex.ToString());
                                //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());
                                string subject = "CCSVM SaveSites: Failed to move the new file";
                                string body    = includedFilePathNew + ": " + ex.ToString();
                                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                otherError = true;
                                return(-2);
                            }
                            processIncluded = true;
                            break;
                        }
                        else
                        {
                            //Library.WriteErrorLog(logFileSaveSitePath, "File not exist: " + includedFilePath);
                            Llog.Info("File not exist: " + includedFilePath);

                            try
                            {
                                File.Move(includedFilePathNew, includedFilePath);
                            }
                            catch (Exception ex)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "Failed to move the new file: " + includedFilePathNew);
                                //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());
                                Llog.Error("Failed to move the new file: " + includedFilePathNew);
                                Llog.Error(ex.ToString());
                                string subject = "CCSVM SaveSites: Failed to move the new file";
                                string body    = includedFilePathNew + ": " + ex.ToString();
                                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                return(-2);
                            }
                            break;
                        }
                    }
                }
                else
                {
                    Llog.Error("Calling included ruby script failed with unknown reason, check logs");
                    //Library.WriteErrorLog(logFileSaveSitePath, "Calling included ruby script failed with unknown reason, check logs");

                    //Library.WriteErrorLog(logFileSaveSitePath, resultIncluded);
                }
            }
            else
            {
                Llog.Error("Calling included ruby script failed with unknown reason, check logs");
                //Library.WriteErrorLog(logFileSaveSitePath, "Calling included ruby script failed with unknown reason, check logs");

                //Library.WriteErrorLog(logFileSaveSitePath, resultIncluded);
            }

            //processing for excluded ip list
            //Library.WriteErrorLog(logFileSaveSitePath, "New Excluded IP List file path: " + excludedFilePathNew);
            //Library.WriteErrorLog(logFileSaveSitePath, "Calling excluded ruby script: " + getSiteExcluded + " " + excludedFilePathNew);
            Llog.Info("New Excluded IP List file path: " + excludedFilePathNew);
            Llog.Info("Calling excluded ruby script: " + getSiteExcluded + " " + excludedFilePathNew);

            string resultExcluded = CallRuby.runSiteScript(getSiteExcluded, ccsVMServerIP, ccsVMServerPort, ccsVMServerUser, ccsVMServerPassword, excludedFilePathNew);

            //Library.WriteErrorLog(logFileSaveSitePath, "Calling excluded ruby script result: " + resultExcluded);
            Llog.Info("Calling excluded ruby script result: " + resultExcluded);
            if (resultExcluded.Contains("getsuccess"))
            {
                getExcluded = true;
                if (File.Exists(excludedFilePathNew))
                {
                    //Library.WriteErrorLog(logFileSaveSitePath, "Calling excluded ruby script successfully");
                    //Library.WriteErrorLog(logFileSaveSitePath, "Starting to replace the excluded csv file");
                    Llog.Info("Calling excluded ruby script successfully");
                    Llog.Info("Starting to replace the excluded csv file");

                    FileStream streamExcluded = null;
                    while (true)
                    {
                        //remove old file
                        if (File.Exists(excludedFilePathTmp))
                        {
                            //Library.WriteErrorLog(logFileSaveSitePath, "Clean up old file: " + excludedFilePathTmp);
                            Llog.Info("Clean up old file: " + excludedFilePathTmp);

                            try
                            {
                                File.Delete(excludedFilePathTmp);
                            }
                            catch (Exception ex)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "Failed to remove old file: " + excludedFilePathTmp);
                                //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());
                                Llog.Error("Failed to remove old file: " + excludedFilePathTmp);
                                Llog.Error(ex.ToString());

                                string subject = "CCSVM SaveSites: Failed to remove old file";
                                string body    = excludedFilePathTmp + ": " + ex.ToString();
                                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                otherError = true;
                                return(-2);
                            }
                        }
                        //replace the file
                        if (File.Exists(excludedFilePath))
                        {
                            try
                            {
                                streamExcluded = File.Open(excludedFilePath, FileMode.Open, FileAccess.Read, FileShare.None);
                                streamExcluded.Close();
                                streamExcluded = null;
                                try
                                {
                                    File.Move(excludedFilePath, excludedFilePathTmp);
                                    Llog.Info("File successfully backup as: " + excludedFilePathTmp);
                                    //Library.WriteErrorLog(logFileSaveSitePath, "File successfully backup as: " + excludedFilePathTmp);
                                }
                                catch (Exception ex)
                                {
                                    //Library.WriteErrorLog(logFileSaveSitePath, "Failed to backup : " + excludedFilePath);
                                    //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());

                                    Llog.Error("Failed to backup : " + excludedFilePath);
                                    Llog.Error(ex.ToString());

                                    string subject = "CCSVM SaveSites: Failed to backup file";
                                    string body    = excludedFilePath + ": " + ex.ToString();
                                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                    otherError = true;
                                    return(-2);
                                }
                            }
                            catch (Exception)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "File in use, sleep for 5 seconds: " + excludedFilePath);
                                Llog.Info("File in use, sleep for 5 seconds: " + excludedFilePath);

                                System.Threading.Thread.Sleep(5000);
                                continue;
                            }

                            //replace with the new file
                            try
                            {
                                File.Move(excludedFilePathNew, excludedFilePath);
                            }
                            catch (Exception ex)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "Failed to move the new file: " + excludedFilePathNew);
                                //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());
                                Llog.Error("Failed to move the new file: " + excludedFilePathNew);
                                Llog.Error(ex.ToString());

                                string subject = "CCSVM SaveSites: Failed to move the new file";
                                string body    = excludedFilePathNew + ": " + ex.ToString();
                                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                otherError = true;
                                return(-2);
                            }
                            processExcluded = true;
                            break;
                        }
                        else
                        {
                            //Library.WriteErrorLog(logFileSaveSitePath, "File not exist: " + excludedFilePath);
                            Llog.Error("File not exist: " + excludedFilePath);


                            try
                            {
                                File.Move(excludedFilePathNew, excludedFilePath);
                            }
                            catch (Exception ex)
                            {
                                //Library.WriteErrorLog(logFileSaveSitePath, "Failed to move the new file: " + excludedFilePathNew);
                                //Library.WriteErrorLog(logFileSaveSitePath, ex.ToString());
                                Llog.Error("Failed to move the new file: " + excludedFilePathNew);
                                Llog.Error(ex.ToString());
                                string subject = "CCSVM SaveSites: Failed to move the new file";
                                string body    = excludedFilePathNew + ": " + ex.ToString();
                                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                                return(-2);
                            }
                            break;
                        }
                    }
                }
                else
                {
                    //Library.WriteErrorLog(logFileSaveSitePath, "Calling excluded ruby script failed with unknown reason, check logs");
                    Llog.Error("Calling excluded ruby script failed with unknown reason, check logs");
                }
            }
            else
            {
                //Library.WriteErrorLog(logFileSaveSitePath, "Calling excluded ruby script failed with unknown reason, check logs");
                Llog.Error("Calling excluded ruby script failed with unknown reason, check logs");
            }

            //Library.WriteErrorLog(logFileSaveSitePath, "Finish running");
            Llog.Info("Finish running");

            if (otherError)
            {
                return(-2);
            }
            else
            {
                if (getIncluded & getExcluded)
                {
                    if (processIncluded & processExcluded)
                    {
                        return(2);
                    }
                    else
                    {
                        return(1);
                    }
                }
                else
                {
                    return(-1);
                }
            }
        }
コード例 #4
0
        private void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            timer1.Enabled = false;
            //DateTime today = new DateTime();
            //keep track the running scans
            int currentRunningScans = 0;

            //Library.WriteErrorLog(logFilePath, "Timer for Adhoc Scan ticked");
            //Get email csv files
            //Library.WriteErrorLog(logFilePath, "Starting to check new adhoc scan emails");

            Llog.Info("Timer for Adhoc Scan ticked");
            Llog.Info("Starting to check new adhoc scan emails");

            //int csvFileCountNew = 0;
            //try
            //{
            //    //return new email count
            //    // 0 means no new emails
            //    // -1 means not able to open Outlook
            //    // -2 means unknow error
            //    //csvFileCountNew = SaveAttachment.getEmails();
            //    //int csvFileCountNew = 0;
            //    if (csvFileCountNew > 0)
            //    {
            //        Library.WriteErrorLog(logFilePath, "Total new adhoc scan requests:  " + csvFileCountNew);
            //    }
            //    else if (csvFileCountNew == 0)
            //    {
            //        Library.WriteErrorLog(logFilePath, "No new adhoc scan request: " + csvFileCountNew);
            //    }
            //    else if (csvFileCountNew < 0)
            //    {
            //        Library.WriteErrorLog(logFilePath, "Error during processing save attachments: " + csvFileCountNew);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Library.WriteErrorLog(logFilePath, "Failed to check new emails: " + ex.ToString());
            //    string subject = "CCSVM AdhocScan: Failed to check new emails";
            //    string body = "Failed to check new emails " + ex.ToString();
            //    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
            //}
            //reading email folder
            string[] csvFiles = { };
            //string[] csvColumns = { "SharepointRecordID", "AssetIP", "Requester", "RequesterEmailID", "RequesterComments", "Country", "ScanTemplate" };
            string[] csvColumns = { "SharepointRecordID", "AssetIP", "Requester", "RequesterEmailID", "Country", "ScanTemplate" };
            try
            {
                //Library.WriteErrorLog(logFilePath, "Search for csv files in folder:  " + csvFilePath);
                Llog.Info("Search for csv files in folder:  " + csvFilePath);

                string[] getcsvFiles = Directory.GetFiles(csvFilePath, "*CCSVM_Adhoc_Scan*.csv*");
                //Library.WriteErrorLog(logFilePath, "Total csv files found: " + getcsvFiles.Length);
                Llog.Info("Total csv files found: " + getcsvFiles.Length);

                for (int i = 0; i < getcsvFiles.Length; i++)
                {
                    if (!getcsvFiles[i].Contains("-"))
                    {
                        //Library.WriteErrorLog(logFilePath, "csv file: " + getcsvFiles[i] + " doesn't contain timestamp, appending timestamp");
                        Llog.Info("csv file: " + getcsvFiles[i] + " doesn't contain timestamp, appending timestamp");

                        getcsvFiles[i] = getcsvFiles[i] + "-" + GetTimestamp(DateTime.Now);
                    }
                }
                foreach (string item in getcsvFiles)
                {
                    //Library.WriteErrorLog(logFilePath, "csv file: " + item);
                    Llog.Info("csv file: " + item);
                }
                csvFiles = getcsvFiles;
            }
            catch (Exception ex)
            {
                //Library.WriteErrorLog(logFilePath, "Failed to get csv file list from directory: " + csvFilePath);
                //Library.WriteErrorLog(logFilePath, ex.ToString());
                Llog.Error("Failed to get csv file list from directory: " + csvFilePath);
                Llog.Error(ex.ToString());
                string subject = "CCSVM AdhocScan: Failed to get csv file list from directory";
                string body    = "Failed to get csv file list from directory: " + csvFilePath;
                Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
            }
            //Start scanning and get reports
            //define the maximum current running scans
            Thread[] childThreads = new Thread[maxRunningScans];
            var      watch        = new System.Diagnostics.Stopwatch();

            int       j          = 0;
            int       totalScans = 0;
            AdhocScan AdhocScan  = new AdhocScan();

            if (csvFiles.Count() == 0)
            {
                //Library.WriteErrorLog(logFilePath, "No csv files found");
                Llog.Info("No csv files found");
            }
            else
            {
                while (true)
                {
                    currentRunningScans = 0;
                    //checking for running scans
                    for (int i = 0; i < maxRunningScans; i++)
                    {
                        try
                        {
                            if (childThreads[i].IsAlive)
                            {
                                //assign the thread which not alive, use the next available
                                currentRunningScans++;
                            }
                        }
                        catch (Exception)
                        {
                            //Library.WriteErrorLog(logFilePath, "Thread: " + i + " not running or not exist");
                        }
                    }

                    Llog.Info("Current running scans: " + currentRunningScans);
                    //Library.WriteErrorLog(logFilePath, "Current running scans: " + currentRunningScans);

                    if (currentRunningScans == maxRunningScans)
                    {
                        //already hit max running scans, sleep 5s
                        Llog.Info("Hit max running scans count, sleep for 60s");
                        //Library.WriteErrorLog(logFilePath, "Hit max running scans count, sleep for 60s");


                        Thread.Sleep(60000);

                        continue;
                    }
                    else if (totalScans == csvFiles.Count())
                    {
                        //all the csv files have been processed
                        //check if any thread running
                        if (currentRunningScans > 0)
                        {
                            //TimeSpan timeSpan = watch.Elapsed;
                            //string a = "Time: " + timeSpan.Minutes + "m ";
                            //Library.WriteErrorLog(logFilePath, a);
                            //int proccessing = timeSpan.Minutes;


                            for (int i = 0; i < maxRunningScans; i++)
                            {
                                try
                                {
                                    if (childThreads[i].IsAlive)
                                    {
                                        Llog.Info("Thread " + i + ": still running");
                                        //Library.WriteErrorLog(logFilePath, "Thread " + i + ": still running");
                                    }
                                }
                                catch (Exception)
                                {
                                    //Library.WriteErrorLog(logFilePath, "Thread: " + i + " not running or not exist");
                                }
                            }
                            Llog.Info("Threads not finish running, sleep for 60s");
                            //Library.WriteErrorLog(logFilePath, "Threads not finish running, sleep for 60s");

                            Thread.Sleep(60000);
                            continue;
                        }
                        else
                        {
                            Llog.Info("All threads finish running");
                            Llog.Info("All the csv files have been processed");
                            //Library.WriteErrorLog(logFilePath, "All threads finish running");
                            //Library.WriteErrorLog(logFilePath, "All the csv files have been processed");
                            break;
                        }
                    }
                    else if (totalScans < csvFiles.Count())
                    {
                        Llog.Info("Start to trigger Adhoc Scan for csv file: " + csvFiles[totalScans]);
                        //Library.WriteErrorLog(logFilePath, "Start to trigger Adhoc Scan for csv file: " + csvFiles[totalScans]);

                        //set the free thread to scan
                        if (totalScans >= maxRunningScans)
                        {
                            for (int k = 0; k < maxRunningScans; k++)
                            {
                                try
                                {
                                    if (!childThreads[k].IsAlive)
                                    {
                                        //assign the thread which not alive, use the next available
                                        j = totalScans % maxRunningScans + k;
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                    //Library.WriteErrorLog(logFilePath, "Thread: " + k + " not running or not exist");
                                }
                            }
                        }
                        else
                        {
                            j = totalScans;
                        }
                        try
                        {
                            ThreadStart childref       = null;
                            string      currentCsvFile = csvFiles[totalScans];
                            int         currentThread  = j;
                            childref        = new ThreadStart(() => AdhocScan.runScan(currentCsvFile, currentThread));
                            childThreads[j] = new Thread(childref);
                            Llog.Info("Created thead " + currentThread + ":" + currentCsvFile);
                            //Library.WriteErrorLog(logFilePath, "Created thead " + currentThread + ":" + currentCsvFile);

                            //watch.Start();

                            Random rnd      = new Random();
                            int    interval = rnd.Next(10, 61);
                            Llog.Info("Starting new scan in " + interval + " seconds under thread: " + j);
                            //Library.WriteErrorLog(logFilePath, "Starting new scan in " + interval + " seconds under thread: " + j);

                            System.Threading.Thread.Sleep(interval * 1000); //wait for a random time and start next thread
                            childThreads[j].Start();
                            totalScans++;
                        }
                        catch (Exception ex)
                        {
                            //Library.WriteErrorLog(logFilePath, "Failed to start thread: " + ex.ToString());
                            //Library.WriteErrorLog(logFilePath, "Retry...");
                            Llog.Error("Failed to start thread: " + ex.ToString());
                            Llog.Error("Retry...");
                        }
                    }
                }
            }

            //Library.CheckErrorLogSize(logFilePath);
            //Library.CheckErrorLogSize(csvProcessedLogPath);
            //Library.CheckErrorLogSize(csvFailedProcessLogPath);
            timer1.Enabled = true;
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: waikhean/Nexpose_AdhocScan
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            string programPath           = ConfigurationManager.AppSettings["programPath"];
            string logPath               = ConfigurationManager.AppSettings["logPath"];
            string logFileSize           = ConfigurationManager.AppSettings["logFileSize"];
            string emailServer           = ConfigurationManager.AppSettings["smtpServer"];
            string emailPort             = ConfigurationManager.AppSettings["smtpServerPort"];
            string logFileName           = ConfigurationManager.AppSettings["logFileName"];
            string logFilePath           = logPath + logFileName;
            string rubyPath              = ConfigurationManager.AppSettings["rubyPath"];
            string reportPath            = ConfigurationManager.AppSettings["reportPath"];
            string emailAddressFrom      = ConfigurationManager.AppSettings["emailAddress"];
            string adminEmailAddress     = ConfigurationManager.AppSettings["adminEmailAddress"];
            string adhocScanReportScript = rubyPath + @"scripts\run_adhoc_scan_reports.rb";
            string includedFilePath      = ConfigurationManager.AppSettings["csvFileinclude"];
            string excludedFilePath      = ConfigurationManager.AppSettings["csvFileExclude"];
            string ccsVMServerIP         = ConfigurationManager.AppSettings["ccsVMServerIP"];
            string ccsVMServerPort       = ConfigurationManager.AppSettings["ccsVMServerPort"];
            string ccsVMServerUser       = ConfigurationManager.AppSettings["ccsVMServerUser"];
            string passworFile           = ConfigurationManager.AppSettings["ccsVMServerPassword"];
            // string csvFilePath = ConfigurationManager.AppSettings["csvFilePath"];
            string csvFilePathFailed    = ConfigurationManager.AppSettings["csvFilePathFailed"];
            string csvFilePathProcessed = ConfigurationManager.AppSettings["csvFilePathProcessed"];
            string getSiteIncluded      = rubyPath + @"scripts\get_site_included_range.rb";
            string getSiteExcluded      = rubyPath + @"scripts\get_site_excluded_range.rb";
            string tempLogFilePath      = Directory.GetCurrentDirectory().ToString() + @"\" + logFileName;

            //to check whether all the path existis


            try
            {
                saveSiteLog = ConfigurationManager.AppSettings["saveSiteErrorLog"];
                Logger      = log4net.LogManager.GetLogger(saveSiteLog);

                NexposeAdhocScanLog = ConfigurationManager.AppSettings["NexposeAdhocScanErrorLog"];
                Llog = log4net.LogManager.GetLogger(NexposeAdhocScanLog);
                log4netConfigFile = ConfigurationManager.AppSettings["Log4netConfig"];
                log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(log4netConfigFile));

                if (!(Directory.Exists(programPath)))
                {
                    Llog.Info("programPath doesn't exist: " + programPath);
                    try
                    {
                        Directory.CreateDirectory(programPath);
                        Llog.Info("Created folder: " + programPath);
                    }
                    catch (Exception ex)
                    {
                        Llog.Info(ex.ToString());
                        string subject = "CCSVM SaveSites: Failed to create folder: " + programPath;
                        string body    = ex.ToString();
                        Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                        Environment.Exit(1);
                    }
                }

                if (!(Directory.Exists(logPath)))
                {
                    Llog.Info("logPath doesn't exist: " + logPath);
                    try
                    {
                        Directory.CreateDirectory(logPath);
                        Llog.Info("Created folder: " + logPath);
                    }
                    catch (Exception ex)
                    {
                        Llog.Info(ex.ToString());
                        string subject = "CCSVM SaveSites: Failed to create folder: " + logPath;
                        string body    = ex.ToString();
                        Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                        Environment.Exit(1);
                    }
                }

                if (!(Directory.Exists(rubyPath)))
                {
                    Llog.Info("Failed to find ruby folder: " + rubyPath);
                    string subject = "CCSVM SaveSites: Failed to find ruby folder";
                    string body    = "Failed to find ruby folder: " + rubyPath;
                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                    Environment.Exit(1);
                }

                if (!File.Exists(passworFile))

                {
                    //Library.WriteErrorLog(logFilePath, "Failed to find the password file: " + passworFile);
                    Llog.Error("Failed to find the password file: " + passworFile);

                    string subject = "CCSVM SaveSites: Failed to find the password file";
                    string body    = "Failed to find the password file: " + passworFile;
                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                    Environment.Exit(1);
                }

                if (!(File.Exists(adhocScanReportScript)))
                {
                    //Library.WriteErrorLog(logPath, "Cannot find ruby script: " + adhocScanReportScript);
                    Llog.Error("Cannot find ruby script: " + adhocScanReportScript);

                    string subject = "CCSVM SaveSites: Cannot find ruby script";
                    string body    = "Cannot find ruby script" + adhocScanReportScript;
                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                    Environment.Exit(1);
                }

                if (!(File.Exists(getSiteIncluded)))
                {
                    //Library.WriteErrorLog(logPath, "Cannot find ruby script: " + getSiteIncluded);
                    Llog.Error("Cannot find ruby script: " + getSiteIncluded);

                    string subject = "CCSVM SaveSites: Cannot find ruby script";
                    string body    = "Cannot find ruby script" + getSiteIncluded;
                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                    Environment.Exit(1);
                }

                if (!(File.Exists(getSiteExcluded)))
                {
                    //Library.WriteErrorLog(logFilePath, "Cannot find ruby script: " + getSiteExcluded);
                    Llog.Error("Cannot find ruby script: " + getSiteExcluded);
                    string subject = "CCSVM SaveSites: Cannot find ruby script";
                    string body    = "Cannot find ruby script" + getSiteExcluded;
                    Library.sendEmail(emailAddressFrom, adminEmailAddress, subject, body);
                    Environment.Exit(1);
                }


                //Library.WriteErrorLog(logFilePath, "========================================================================");
                //Library.WriteErrorLog(logFilePath, "All required files and folders exists, starting CCSVM Adhoc Scan service");

                Llog.Info("========================================================================");
                Llog.Info("All required files and folders exists, starting CCSVM Adhoc Scan service");

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new ccsvmadhocscan()
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                Llog.Error("Exception during start CCSVM Adhoc Scan service: " + ex.ToString());

                Environment.Exit(1);
            }
        }