Esempio n. 1
0
        public void Run(string target, int jobID, string policy, string strategy)
        {
            Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Entering Run()");
            Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Target = {0} , JobID = {1} , Policy = {2}, Strategy = {3}", target, jobID, policy, strategy));

            OpenVasParser parser;

            parser = new OpenVasParser(target, jobID, policy, strategy);

            string status = XCommon.STATUS.FINISHED.ToString();

            if (parser.Parse() == false)
            {
                status = XCommon.STATUS.ERROR.ToString();
            }

            // =================================================
            // Change the status of the job to FINISHED or ERROR
            // =================================================

            Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Updating job {0} status to FINISHED", jobID));

            XORCISMEntities model = new XORCISMEntities();
            var             xJob  = from j in model.JOB
                                    where j.JobID == jobID
                                    select j;

            JOB xJ = xJob.FirstOrDefault();

            xJ.Status  = status;
            xJ.DateEnd = DateTime.Now;
            model.SaveChanges();

            Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Leaving Run()");
        }
Esempio n. 2
0
        //public void Run(string data, int jobID, int AccountID)
        public void Run(string target, int jobID, string policy, string strategy)
        {
            //WARNING: OLD CODE, should be reviewed/revised - JA

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS SCAN", "JobID:" + jobID + "Entering Run()");

            //Utils.Helper_Trace("XORCISM PROVIDER NESSUS SCAN", string.Format("Creating an instance of NessusParser for AccountID="+AccountID.ToString()));
            Utils.Helper_Trace("XORCISM PROVIDER NESSUS SCAN", string.Format("Target = {0} , JobID = {1} , Policy = {2}, Strategy = {3}", target, jobID, policy, strategy));

            //NessusParser NessusParser = new NessusParser(data,AccountID,jobID);
            NessusParser NessusParser = new NessusParser(target, jobID, policy, strategy);

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS SCAN", string.Format("JobID:" + jobID + " Parsing the data"));

            NessusParser.parse();

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS SCAN", "JobID:" + jobID + "Updating job status to FINISHED");

            XORCISMEntities model = new XORCISMEntities();
            var             xJob  = from j in model.JOB
                                    where j.JobID == jobID
                                    select j;

            JOB xJ = xJob.FirstOrDefault();

            xJ.Status = XCommon.STATUS.FINISHED.ToString();

            model.SaveChanges();
            Utils.Helper_Trace("XORCISM PROVIDER NESSUS SCAN", string.Format("End of data processing"));

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS SCAN", "Leaving Run()");
        }
Esempio n. 3
0
 public void UpdateJob(int JobId)
 {
     XORCISMEntities model = new XORCISMEntities();
     var Q = from o in model.JOB
             where o.JobID == JobId
             select o;
     JOB myJob = Q.FirstOrDefault();
     myJob.Status = XCommon.STATUS.FINISHED.ToString();
     myJob.DateEnd = DateTimeOffset.Now;
     model.SaveChanges();
 }
Esempio n. 4
0
        public void Run(string target, int jobID)
        {
            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", "Entering Run()");

            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", string.Format("Target = {0}", target));
            target = target.Replace("http://", "");
            target = target.Replace("https://", "");
            target = target.Replace("www.", "");
            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", string.Format("Clean Target = {0}", target));

            string MD5domain = HashMD5(target);

            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", string.Format("TargetMD5 = {0}", MD5domain));

            string url = "http://api.urlvoid.com/api.php?key=12345&domain=" + MD5domain;    //Hardcoded

            string          ResponseText = "";
            StreamReader    SR           = null;
            HttpWebResponse response     = null;
            HttpWebRequest  request      = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method = "GET";
            response       = (HttpWebResponse)request.GetResponse();
            SR             = new StreamReader(response.GetResponseStream());
            ResponseText   = SR.ReadToEnd();

            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", string.Format("Response status : [{0}]", response.StatusCode + " - " + response.StatusDescription));
            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", string.Format("Response headers : [{0}]", response.Headers.ToString()));
            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", string.Format("Response received : [{0}]", ResponseText));
            //[U]   domain or subdomain has not yet been scanned in URLVoid
            //[4]

            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", "Updating job status to FINISHED");

            XORCISMEntities model = new XORCISMEntities();
            var             xJob  = from j in model.JOB
                                    where j.JobID == jobID
                                    select j;

            JOB xJ = xJob.FirstOrDefault();

            xJ.Status  = XCommon.STATUS.FINISHED.ToString();
            xJ.DateEnd = DateTime.Now;
            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", "Job Finished at " + xJ.DateEnd.ToString());
            model.SaveChanges();

            Utils.Helper_Trace("XORCISM PROVIDER URLVOID", "Leaving Run()");
        }
Esempio n. 5
0
        private void Helper_SetJobStatus(int jobID, XCommon.STATUS status)
        {
            XORCISMEntities model;

            model = new XORCISMEntities();

            JOB job;

            job = model.JOB.FirstOrDefault(o => o.JobID == jobID);

            job.Status  = status.ToString();
            job.DateEnd = DateTimeOffset.Now;

            model.SaveChanges();
            //FREE MEMORY
            model.Dispose();
            job = null;
        }
Esempio n. 6
0
        //public void Run(string target, int jobID, string policy, string strategy)
        public void Run(string data, int jobID, int AccountID)
        {
            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "JobID:" + jobID + " Entering Run()");
            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Creating an instance of CenzicParser for AccountID=" + AccountID.ToString()));

            CenzicParser CenzicParser = new CenzicParser(data, AccountID, jobID);
            inerror = false;
            if (!inerror)
            {
                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + jobID + " Parsing the data"));
                CenzicParser.parse();
                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + jobID + " End of data processing"));

                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Updating job {0} status to FINISHED", jobID));

                CenzicParser.UpdateJob(jobID);

                XORCISMEntities model = new XORCISMEntities();
                var xJob = from j in model.JOB
                           where j.JobID == jobID
                           select j;

                JOB xJ = xJob.FirstOrDefault();
                xJ.Status = XCommon.STATUS.FINISHED.ToString();

                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "Changing the session to ServiceCategoryID=2");
                var xSession = from s in model.SESSION
                               where s.SessionID == xJ.SessionID
                               select s;
                SESSION xS = xSession.FirstOrDefault();
                xS.ServiceCategoryID = 2;

                model.SaveChanges();
            }
            else
            {
                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "JobID:" + jobID + " inerror");
            }
            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "JobID:" + jobID + " Leaving Run()");
        }
Esempio n. 7
0
        public void Run(string data, int jobID, int AccountID)
        {
            //WARNING: OLD CODE, should be reviewed and revised

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Entering Run()");

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Creating an instance of NessusParser for AccountID=" + AccountID.ToString()));

            NessusParser NessusParser = new NessusParser(data, AccountID, jobID);

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Parsing the data"));

            NessusParser.parse();

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Updating job status to FINISHED");

            XORCISMEntities model = new XORCISMEntities();
            var             xJob  = from j in model.JOB
                                    where j.JobID == jobID
                                    select j;

            JOB xJ = xJob.FirstOrDefault();

            xJ.Status = XCommon.STATUS.FINISHED.ToString();

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Changing the session to ServiceCategoryID=1");
            var xSession = from s in model.SESSION
                           where s.SessionID == xJ.SessionID
                           select s;
            SESSION xS = xSession.FirstOrDefault();

            xS.ServiceCategoryID = 1;


            model.SaveChanges();
            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("End of data processing"));

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Leaving Run()");
        }
Esempio n. 8
0
        public void Run(string data, int jobID, int AccountID)
        {
            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Entering Run()");

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("Creating an instance of SkipfishImportParser for AccountID=" + AccountID.ToString()));

            SkipfishImportParser SkipfishImportParser = new SkipfishImportParser(data, AccountID, jobID);

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("Parsing the data"));

            SkipfishImportParser.parse();

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Updating job status to FINISHED");

            XORCISMEntities model = new XORCISMEntities();
            var             xJob  = from j in model.JOB
                                    where j.JobID == jobID
                                    select j;

            JOB xJ = xJob.FirstOrDefault();

            xJ.Status = XCommon.STATUS.FINISHED.ToString();

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Changing the session to ServiceCategoryID=2");
            var xSession = from s in model.SESSION
                           where s.SessionID == xJ.SessionID
                           select s;
            SESSION xS = xSession.FirstOrDefault();

            xS.ServiceCategoryID = 2;       //HARDCODED


            model.SaveChanges();
            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("End of data processing"));

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Leaving Run()");
        }
Esempio n. 9
0
        public void parse()
        {
            Assembly a;

            a = Assembly.GetExecutingAssembly();

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Assembly location = " + a.Location);

            // ============================================
            // Parse the XML Document and populate the database
            // ============================================

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(m_data);

            XORCISMEntities model;

            model = new XORCISMEntities();

            string query = "/NessusClientData_v2/Report";

            XmlNode report;

            report = doc.SelectSingleNode(query);

            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Found {0} hosts to parse", report.ChildNodes.Count));

            foreach (XmlNode reportHost in report.ChildNodes)
            {
                string ipAddress;
                ipAddress = reportHost.Attributes["name"].InnerText;

                Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Handling host with IP {0}", ipAddress));

                // =============================================
                // If necessary, create an asset in the database
                // =============================================
                //TODO  ipaddressIPv4
                var myass = from ass in model.ASSET
                            where ass.ipaddressIPv4 == ipAddress //&& ass.AccountID == m_AccountID
                            select ass;
                ASSET asset = myass.FirstOrDefault();

                if (asset == null)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Creates a new entry in table ASSET for this IP");

                    asset = new ASSET();
                    //asset.AccountID = m_AccountID;
                    asset.AssetName        = ipAddress;
                    asset.AssetDescription = ipAddress;
                    //TODO  ipaddressIPv4
                    asset.ipaddressIPv4 = ipAddress;
                    asset.Enabled       = true;
                    //asset.JobID = m_JobId;

                    model.ASSET.Add(asset);
                    model.SaveChanges();
                }
                else
                {
                    Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "This IP already corresponds to an existing asset");
                }

                Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Creating ASSETINSESSION reference");
                ASSETSESSION assinsess = new ASSETSESSION();
                assinsess.AssetID   = asset.AssetID;
                assinsess.SessionID = model.JOB.Single(x => x.JobID == m_JobId).SessionID;
                model.ASSETSESSION.Add(assinsess);
                model.SaveChanges();

                Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "Update JOB with ASSETINSESSIONID");
                JOB daJob = model.JOB.Single(x => x.JobID == m_JobId);
                daJob.AssetSessionID = assinsess.AssetSessionID;
                model.SaveChanges();


                // =============================
                // Handles every ReportItem tag
                // =============================

                foreach (XmlNode n in reportHost.ChildNodes)
                {
                    //Hardcoded
                    if (n.Name.ToUpper() == "ReportItem".ToUpper() && n.ChildNodes != null && n.ChildNodes.Count > 0)
                    {
                        string protocol = n.Attributes["protocol"].InnerText.ToUpper();
                        int    port     = Convert.ToInt32(n.Attributes["port"].InnerText);
                        //svc_name
                        //pluginID
                        //pluginName
                        //pluginFamily
                        //risk_factor

                        VulnerabilityEndPoint vulnerabilityEndPoint = new VulnerabilityEndPoint();
                        vulnerabilityEndPoint.IpAdress = ipAddress;
                        vulnerabilityEndPoint.Protocol = protocol;
                        vulnerabilityEndPoint.Port     = port;

                        VulnerabilityFound vulnerabilityFound = new VulnerabilityFound();
                        vulnerabilityFound.ListItem      = Helper_GetCVE(n);
                        vulnerabilityFound.ListReference = Helper_GetREFERENCE(n);  //TODO: Helper_GetCVE and Helper_GetREFERENCE could be mixed for only 1 parsing
                        vulnerabilityFound.InnerXml      = n.OuterXml;
                        vulnerabilityFound.Description   = HelperGetChildInnerText(n, "description");
                        vulnerabilityFound.Solution      = HelperGetChildInnerText(n, "solution");
                        vulnerabilityFound.Title         = HelperGetChildInnerText(n, "synopsis");
                        vulnerabilityFound.rawresponse   = HelperGetChildInnerText(n, "plugin_output");
                        vulnerabilityFound.Result        = HelperGetChildInnerText(n, "plugin_output");
                        vulnerabilityFound.Severity      = n.Attributes["severity"].InnerText; //1
                        //vulnerabilityFound.Severity = HelperGetChildInnerText(n, "risk_factor");  //None  Low
                        if (HelperGetChildInnerText(n, "exploit_available") == "true")
                        {
                            vulnerabilityFound.Exploitable = true;
                        }
                        //exploitability_ease   Exploits are available
                        //exploit_framework_canvas
                        //exploit_framework_metasploit
                        //exploit_framework_core
                        //metasploit_name
                        //canvas_package

                        //cvss_vector
                        //cvss_temporal_score
                        try
                        {
                            vulnerabilityFound.CVSSBaseScore = float.Parse(HelperGetChildInnerText(n, "cvss_base_score"), System.Globalization.CultureInfo.InvariantCulture);
                        }
                        catch (Exception ex)
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Error parsing CVSS_BASE : Exception = {0}", ex.Message));
                            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("CVSS_BASE =", HelperGetChildInnerText(n, "cvss_base_score")));
                        }

                        bool   PatchUpgrade = false;
                        string MSPatch      = "";
                        string title;
                        string Solution;
                        //patch_publication_date
                        if (HelperGetChildInnerText(n, "patch_publication_date") != "")
                        {
                            PatchUpgrade = true;
                        }
                        title = n.Attributes["pluginName"].InnerText;
                        Regex objNaturalPattern = new Regex("MS[0-9][0-9]-[0-9][0-9][0-9]");
                        MSPatch = objNaturalPattern.Match(title).ToString();
                        if (MSPatch != "")
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", "MSPatch=" + MSPatch);
                            PatchUpgrade = true;
                        }

                        //Hardcoded
                        Solution = HelperGetChildInnerText(n, "solution");
                        if (Solution.Contains(" upgrade to "))
                        {
                            PatchUpgrade = true;
                        }
                        if (Solution.Contains("Upgrade "))
                        {
                            PatchUpgrade = true;
                        }
                        if (Solution.Contains("has released a set of patches"))
                        {
                            PatchUpgrade = true;
                        }
                        if (Solution.Contains("Apply the appropriate patch"))
                        {
                            PatchUpgrade = true;
                        }

                        //<patch_publication_date>

                        vulnerabilityFound.PatchUpgrade = PatchUpgrade;
                        vulnerabilityFound.MSPatch      = MSPatch;

                        // ===========
                        // Persistance
                        // ===========

                        Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("Persistance [{0}] [{1}] [{2}]", protocol, port, Helper_ListCVEToString(vulnerabilityFound.ListItem)));

                        int etat = VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, m_JobId, "nessus", model);
                        if (etat == -1)
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER NESSUS", string.Format("CANNOT IMPORT THIS ASSET !!!! "));
                        }
                    }
                }
            }

            // TODO
            // VulnerabilityPersistor.UpdateVulnerabilityJob(list_vulnerabilyFound,m_JobId,m_model);
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            //https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
            model.Configuration.AutoDetectChangesEnabled = false;
            model.Configuration.ValidateOnSaveEnabled    = false;

            int iCptYear = DateTime.Now.Year;

            //XORCISMEntities model = new XORCISMEntities();

            //int iVocabularySCIPID = 0;// 1044;  //SCIP
            #region vocabularyscip
            try
            {
                iVocabularySCIPID = model.VOCABULARY.Where(o => o.VocabularyName == "SCIP").Select(o => o.VocabularyID).FirstOrDefault();
            }
            catch (Exception ex)
            {
            }
            if (iVocabularySCIPID <= 0)
            {
                VOCABULARY oVocabulary = new VOCABULARY();
                oVocabulary.CreatedDate    = DateTimeOffset.Now;
                oVocabulary.VocabularyName = "SCIP";
                model.VOCABULARY.Add(oVocabulary);
                model.SaveChanges();
                iVocabularySCIPID = oVocabulary.VocabularyID;
                Console.WriteLine("DEBUG iVocabularySCIPID=" + iVocabularySCIPID);
            }
            #endregion vocabularyscip


            while (iCptYear > 2003)
            {
                string sURI = "refmap" + iCptYear;
                Console.WriteLine("DEBUG *************************************************************");
                Console.WriteLine("DEBUG " + DateTimeOffset.Now.ToString());
                Console.WriteLine("DEBUG Working on " + sURI);

                string sDownloadFileURL = "http://www.scip.ch/en/?vuldb." + sURI;
                iCptYear--;


                HttpWebRequest  webRequest  = null;
                HttpWebResponse webResponse = null;
                webRequest        = (HttpWebRequest)WebRequest.Create(new Uri(sDownloadFileURL));
                webRequest.Method = "GET";
                //webRequest.Credentials = CredentialCache.DefaultCredentials;
                //webRequest.Timeout = 20 * 60 * 1000;    //20 minutes
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                StreamReader SR            = new StreamReader(webResponse.GetResponseStream());
                string       sResponseText = SR.ReadToEnd();
                //Console.WriteLine(sResponseText);

                SR.Close();
                webResponse.Close();

                StreamWriter swStreamWriter = new StreamWriter(sURI + ".txt");
                swStreamWriter.Write(sResponseText);
                swStreamWriter.Close();



                StreamReader srStreamReader   = new StreamReader(sURI + ".txt");
                string       sLine            = srStreamReader.ReadLine();
                string       sTemp            = string.Empty;
                string       sCurrentVULDB    = string.Empty;
                string       sCurrentCVE      = string.Empty;
                int          iVulnerabilityID = 0;

                Regex myRegexVULDB = new Regex(@"<a href=\""\?vuldb\.[0-9](.*?)\"""); //TODO Review
                //Regex myRegexCVE = new Regex("CVE-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]");
                Regex myRegexCVE = new Regex(@"CVE-(19|20)\d\d-(0\d{3}|[1-9]\d{3,})");
                //https://cve.mitre.org/cve/identifiers/tech-guidance.html
                Regex myRegexSECTRACK = new Regex(@"securitytracker.com/id/(.*?)\"" ");     //TODO Review
                Regex myRegexSECUNIA  = new Regex(@"secunia.com/advisories/(.*?)\"" ");     //TODO Review
                Regex myRegexBID      = new Regex(@"securityfocus.com/bid/(.*?)\"" ");      //TODO Review
                Regex myRegexXFORCE   = new Regex(@"xforce.iss.net/xforce/xfdb/(.*?)\"" "); //TODO Review
                Regex myRegexOSVDB    = new Regex(@"osvdb.org/[0-9](.*?)\"" ");             //TODO Review

                while (sLine != null)
                {
                    sLine = sLine.Replace("securitytracker.com/id?", "securitytracker.com/id/");
                    //sLine = sLine.Replace("https://www.", "http://");
                    //sLine = sLine.Replace("http://www.", "http://");
                    sLine = sLine.Replace("osvdb.org/displayvuln.php?osvdbid=", "osvdb.org/");
                    sLine = sLine.Replace("osvdb.org/show/osvdb/", "osvdb.org/");
                    //TODO? microsoft.com MS

                    sTemp = myRegexVULDB.Match(sLine).ToString();
                    if (sTemp != "")
                    {
                        sTemp = sTemp.Replace("<a href=", "");
                        sTemp = sTemp.Replace("\"", "");
                        sTemp = sTemp.Replace("?vuldb.", "");
                        //TODO check if ok
                        sCurrentVULDB = sTemp;
                        Console.WriteLine("*************************************************************");
                        Console.WriteLine("DEBUG " + DateTimeOffset.Now.ToString());
                        Console.WriteLine("DEBUG SCIP VULDB:" + sCurrentVULDB);
                    }
                    else
                    {
                        sTemp = myRegexCVE.Match(sLine).ToString();
                        if (sTemp != "")
                        {
                            #region cve
                            sCurrentCVE = sTemp;
                            Console.WriteLine("DEBUG " + DateTimeOffset.Now.ToString());
                            Console.WriteLine("DEBUG CVE:" + sCurrentCVE);
                            //TODO double-check if it is real CVE-ID

                            try
                            {
                                iVulnerabilityID = vuln_nodel.VULNERABILITY.Where(o => o.VULReferential == "cve" && o.VULReferentialID == sCurrentCVE).Select(o => o.VulnerabilityID).FirstOrDefault();
                            }
                            catch (Exception exCVE)
                            {
                                //Console.WriteLine("Exception exCVE " + exCVE.Message + " " + exCVE.InnerException);
                            }
                            if (iVulnerabilityID <= 0)
                            {
                                try
                                {
                                    VULNERABILITY oVulnerability = new VULNERABILITY();
                                    oVulnerability.CreatedDate      = DateTimeOffset.Now;
                                    oVulnerability.VocabularyID     = iVocabularySCIPID;
                                    oVulnerability.VULReferential   = "cve";
                                    oVulnerability.VULReferentialID = sCurrentCVE;
                                    oVulnerability.timestamp        = DateTimeOffset.Now;
                                    vuln_nodel.VULNERABILITY.Add(oVulnerability);
                                    vuln_nodel.SaveChanges();

                                    iVulnerabilityID = oVulnerability.VulnerabilityID;
                                }
                                catch (System.Data.Entity.Validation.DbEntityValidationException e)
                                {
                                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                    foreach (var eve in e.EntityValidationErrors)
                                    {
                                        sb.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                                                    eve.Entry.Entity.GetType().Name,
                                                                    eve.Entry.State));
                                        foreach (var ve in eve.ValidationErrors)
                                        {
                                            sb.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                                                        ve.PropertyName,
                                                                        ve.ErrorMessage));
                                        }
                                    }
                                    //throw new DbEntityValidationException(sb.ToString(), e);
                                    Console.WriteLine("Exception DbEntityValidationExceptionUPDATECAPEC " + sb.ToString());
                                }
                                catch (Exception exSCIPCVE)
                                {
                                    Console.WriteLine("Exception exSCIPCVE " + exSCIPCVE.Message + " " + exSCIPCVE.InnerException);
                                }
                            }
                            else
                            {
                                //Update VULNERABILITY
                            }
                            Console.WriteLine("DEBUG " + DateTimeOffset.Now.ToString());
                            Console.WriteLine("DEBUG iVulnerabilityID=" + iVulnerabilityID);

                            sSource       = "SCIP";
                            sSourceID     = sCurrentVULDB;
                            sReferenceURL = "http://scip.ch/?vuldb." + sCurrentVULDB;
                            fAddReference(iVulnerabilityID);    //, sSource, sSourceID, sReferenceURL);
                            #endregion cve
                        }
                        else
                        {
                            //<td><a href="http://osvdb.org/3314" title="osvdb.org/3314">3314</a></td>
                            sTemp = myRegexOSVDB.Match(sLine).ToString();
                            if (sTemp != "")
                            {
                                #region osvdb
                                //Console.WriteLine(sTemp);
                                sSource   = "OSVDB";
                                sSourceID = sTemp.Replace("osvdb.org/", "");
                                sSourceID = sSourceID.Replace("/", "");
                                sSourceID = sSourceID.Replace("\"", "").Trim();
                                //Console.WriteLine(sSourceID);
                                try
                                {
                                    int iTest = int.Parse(sSourceID);
                                    sReferenceURL = "http://osvdb.org/" + sSourceID;
                                    Console.WriteLine("DEBUG " + sReferenceURL);

                                    fAddReference(iVulnerabilityID);    //, sSource, sSourceID, sReferenceURL);
                                }
                                catch (Exception exSCIPOSVDBID)
                                {
                                    Console.WriteLine("Exception exSCIPOSVDBID " + sSourceID + " " + exSCIPOSVDBID.Message + " " + exSCIPOSVDBID.InnerException);
                                }

                                //TODO see Import_all
                                //fRequestOSVDB();
                                #endregion osvdb
                            }
                            else
                            {
                                #region securitytracker
                                ////http://securitytracker.com/id?1028074
                                //http://securitytracker.com/id/1029599
                                sTemp = myRegexSECTRACK.Match(sLine).ToString();
                                if (sTemp != "")
                                {
                                    //Console.WriteLine(sTemp);
                                    sSource   = "SECTRACK";
                                    sSourceID = sTemp.Replace("securitytracker.com/id/", "");
                                    sSourceID = sSourceID.Replace("/", "");
                                    sSourceID = sSourceID.Replace("\"", "").Trim();
                                    //Console.WriteLine(sSourceID);
                                    sReferenceURL = "http://securitytracker.com/id/" + sSourceID;
                                    Console.WriteLine("DEBUG " + sReferenceURL);

                                    fAddReference(iVulnerabilityID);    //, sSource, sSourceID, sReferenceURL);
                                }
                                #endregion securitytracker
                                else
                                {
                                    #region secunia
                                    //http://secunia.com/advisories/58347
                                    sTemp = myRegexSECUNIA.Match(sLine).ToString();
                                    if (sTemp != "")
                                    {
                                        //Console.WriteLine(sTemp);
                                        sSource   = "SECUNIA";
                                        sSourceID = sTemp.Replace("secunia.com/advisories/", "");
                                        sSourceID = sSourceID.Replace("/", "");
                                        sSourceID = sSourceID.Replace("\"", "").Trim();
                                        //Console.WriteLine(sSourceID);
                                        sReferenceURL = "http://secunia.com/advisories/" + sSourceID;
                                        Console.WriteLine("DEBUG " + sReferenceURL);

                                        fAddReference(iVulnerabilityID);    //, sSource, sSourceID, sReferenceURL);
                                    }
                                    #endregion secunia
                                    else
                                    {
                                        #region securityfocus
                                        //http://securityfocus.com/bid/123
                                        sTemp = myRegexBID.Match(sLine).ToString();
                                        if (sTemp != "")
                                        {
                                            //Console.WriteLine(sTemp);
                                            sSource   = "BID";
                                            sSourceID = sTemp.Replace("securityfocus.com/bid/", "");
                                            sSourceID = sSourceID.Replace("/", "");
                                            sSourceID = sSourceID.Replace("\"", "").Trim();
                                            //Console.WriteLine(sSourceID);
                                            sReferenceURL = "http://securityfocus.com/bid/" + sSourceID;
                                            Console.WriteLine("DEBUG " + sReferenceURL);

                                            fAddReference(iVulnerabilityID);    //, sSource, sSourceID, sReferenceURL);
                                        }
                                        #endregion securityfocus
                                        else
                                        {
                                            #region xforce
                                            //http://xforce.iss.net/xforce/xfdb/123
                                            sTemp = myRegexXFORCE.Match(sLine).ToString();
                                            if (sTemp != "")
                                            {
                                                //Console.WriteLine(sTemp);
                                                sSource   = "XF";
                                                sSourceID = sTemp.Replace("xforce.iss.net/xforce/xfdb/", "");
                                                sSourceID = sSourceID.Replace("/", "");
                                                sSourceID = sSourceID.Replace("\"", "").Trim();
                                                //Console.WriteLine(sSourceID);
                                                sReferenceURL = "http://xforce.iss.net/xforce/xfdb/" + sSourceID;
                                                Console.WriteLine("DEBUG " + sReferenceURL);

                                                fAddReference(iVulnerabilityID);    //, sSource, sSourceID, sReferenceURL);
                                            }
                                            #endregion xforce
                                            else
                                            {
                                                //TODO
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    sLine = srStreamReader.ReadLine();
                }

                srStreamReader.Close();
            }

            //FREE
            try
            {
                model.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException e)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (var eve in e.EntityValidationErrors)
                {
                    sb.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                                eve.Entry.Entity.GetType().Name,
                                                eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        sb.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                                    ve.PropertyName,
                                                    ve.ErrorMessage));
                    }
                }
                //throw new DbEntityValidationException(sb.ToString(), e);
                Console.WriteLine("Exception DbEntityValidationExceptionFINALSAVE " + sb.ToString());
            }
            catch (Exception exFINALSAVE)
            {
                Console.WriteLine("Exception exFINALSAVE " + exFINALSAVE.Message + " " + exFINALSAVE.InnerException);
            }
            model.Dispose();
        }
Esempio n. 11
0
        static void Main()
        {
            XORCISMEntities model = new XORCISMEntities();

            //https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
            model.Configuration.AutoDetectChangesEnabled = false;
            model.Configuration.ValidateOnSaveEnabled    = false;

            int    iVocabularyCYBOXID = 0;     // 11;
            string sCYBOXVersion      = "2.1"; //HARDCODED TODO

            #region vocabularycybox
            try
            {
                iVocabularyCYBOXID = model.VOCABULARY.Where(o => o.VocabularyName == "CYBOX" && o.VocabularyVersion == sCYBOXVersion).Select(o => o.VocabularyID).FirstOrDefault();
            }
            catch (Exception ex)
            {
            }
            if (iVocabularyCYBOXID <= 0)
            {
                try
                {
                    VOCABULARY oVocabulary = new VOCABULARY();
                    oVocabulary.CreatedDate       = DateTimeOffset.Now;
                    oVocabulary.VocabularyName    = "CYBOX"; //HARDCODED
                    oVocabulary.VocabularyVersion = sCYBOXVersion;
                    model.VOCABULARY.Add(oVocabulary);
                    model.SaveChanges();
                    iVocabularyCYBOXID = oVocabulary.VocabularyID;
                    Console.WriteLine("DEBUG iVocabularyCYBOXID=" + iVocabularyCYBOXID);
                }
                catch (Exception ex)
                {
                }
            }
            #endregion vocabularycybox

            XmlDocument doc;
            doc = new XmlDocument();
            //TODO: download the file
            doc.Load(@"C:\nvdcve\cybox_default_vocabularies.xsd");  //HARDCODED
            //TODO: Validate XSD

            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);

            mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            XmlNodeList nodes1;
            nodes1 = doc.SelectNodes("/xs:schema/xs:simpleType", mgr);
            Console.WriteLine(nodes1.Count);



            foreach (XmlNode node in nodes1)    //enumeration
            {
                //Console.WriteLine("DEBUG node.Name="+node.Name);
                string sNodeName = node.Attributes["name"].InnerText;
                Console.WriteLine(sNodeName);

                if (sNodeName.Contains("Enum-"))    //HARDCODED
                {
                    bool bEnumerationProcessed = false;
                    //Get the EnumerationName and Version
                    //ActionNameEnum-1.1
                    string[] words               = sNodeName.Split('-');
                    string   sEnumerationName    = words[0];
                    string   sEnumerationVersion = words[1];

                    //Check if we have this EnumerationVersion in the database
                    //First check the Version
                    #region version
                    XORCISMModel.VERSION oVersion;
                    int iVersionID = 0;
                    try
                    {
                        iVersionID = model.VERSION.FirstOrDefault(o => o.VersionValue == sEnumerationVersion).VersionID;
                    }
                    catch (Exception ex)
                    {
                    }
                    if (iVersionID <= 0)
                    {
                        oVersion = new VERSION();
                        oVersion.VersionValue = sEnumerationVersion;
                        oVersion.VocabularyID = iVocabularyCYBOXID;
                        model.VERSION.Add(oVersion);
                        model.SaveChanges();
                        iVersionID = oVersion.VersionID;
                    }
                    else
                    {
                        //Update VERSION
                    }
                    #endregion version

                    #region enumerationversion
                    XORCISMModel.ENUMERATIONVERSION oEnumerationVersion;
                    int iEnumerationVersionID = 0;
                    try
                    {
                        iEnumerationVersionID = model.ENUMERATIONVERSION.FirstOrDefault(o => o.EnumerationName == sEnumerationName && o.VersionID == iVersionID).EnumerationVersionID;
                    }
                    catch (Exception ex)
                    {
                    }
                    if (iEnumerationVersionID <= 0)
                    {
                        oEnumerationVersion = new ENUMERATIONVERSION();
                        oEnumerationVersion.EnumerationName = sEnumerationName;
                        oEnumerationVersion.VersionID       = iVersionID;
                        oEnumerationVersion.VocabularyID    = iVocabularyCYBOXID;
                        model.ENUMERATIONVERSION.Add(oEnumerationVersion);
                        model.SaveChanges();
                        iEnumerationVersionID = oEnumerationVersion.EnumerationVersionID;
                    }
                    else
                    {
                        //Update ENUMERATIONVERSION
                    }
                    #endregion enumerationversion

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ActionTypeEnum"))   //HARDCODED
                    {
                        #region actiontype
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")            //HARDCODED
                            {
                                foreach (XmlNode nodeEnumeration in node2) //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.ACTIONTYPE myActionType;
                                    myActionType = model.ACTIONTYPE.FirstOrDefault(o => o.ActionTypeName == sEnumerationValue && o.EnumerationVersionID == iEnumerationVersionID);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myActionType == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new ACTIONTYPE " + sEnumerationValue);
                                        myActionType = new ACTIONTYPE();
                                        myActionType.ActionTypeName       = sEnumerationValue;
                                        myActionType.VocabularyID         = iVocabularyCYBOXID;
                                        myActionType.EnumerationVersionID = iEnumerationVersionID;
                                        model.ACTIONTYPE.Add(myActionType);
                                        model.SaveChanges();
                                    }
                                    else
                                    {
                                        //Update ACTIONTYPE
                                    }
                                    foreach (XmlNode node3 in nodeEnumeration)    //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)          //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation") //HARDCODED
                                            {
                                                Console.WriteLine("DEBUG documentation=" + node4.InnerText);
                                                myActionType.ActionTypeDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion actiontype
                        bEnumerationProcessed = true;
                    }

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ActionNameEnum"))
                    {
                        #region actionname
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.ACTIONNAME myActionName;
                                    myActionName = model.ACTIONNAME.FirstOrDefault(o => o.ActionNameName == sEnumerationValue && o.EnumerationVersionID == iEnumerationVersionID);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myActionName == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new ACTIONNAME " + sEnumerationValue);
                                        myActionName = new ACTIONNAME();
                                        myActionName.ActionNameName       = sEnumerationValue;
                                        myActionName.VocabularyID         = iVocabularyCYBOXID;
                                        myActionName.EnumerationVersionID = iEnumerationVersionID;
                                        model.ACTIONNAME.Add(myActionName);
                                        model.SaveChanges();
                                    }
                                    else
                                    {
                                        //Update ACTIONNAME
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                Console.WriteLine("DEBUG documentation=" + node4.InnerText);
                                                myActionName.ActionNameDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion actionname
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ActionArgumentNameEnum"))
                    {
                        #region actionargument
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.ACTIONARGUMENTNAME myActionArgumentName;
                                    myActionArgumentName = model.ACTIONARGUMENTNAME.FirstOrDefault(o => o.ActionArgumentNameName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myActionArgumentName == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new ACTIONARGUMENTNAME " + sEnumerationValue);
                                        myActionArgumentName = new ACTIONARGUMENTNAME();
                                        myActionArgumentName.ActionArgumentNameName = sEnumerationValue;
                                        myActionArgumentName.VocabularyID           = iVocabularyCYBOXID;
                                        model.ACTIONARGUMENTNAME.Add(myActionArgumentName);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myActionArgumentName.ActionArgumentNameDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion actionargument
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ActionObjectAssociationTypeEnum"))
                    {
                        #region actionobjectassociation
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.ACTIONOBJECTASSOCIATIONTYPE myActionObjectAssociationType;
                                    myActionObjectAssociationType = model.ACTIONOBJECTASSOCIATIONTYPE.FirstOrDefault(o => o.ActionObjectAssociationTypeName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myActionObjectAssociationType == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new ACTIONOBJECTASSOCIATIONTYPE " + sEnumerationValue);
                                        myActionObjectAssociationType = new ACTIONOBJECTASSOCIATIONTYPE();
                                        myActionObjectAssociationType.ActionObjectAssociationTypeName = sEnumerationValue;
                                        myActionObjectAssociationType.VocabularyID = iVocabularyCYBOXID;
                                        model.ACTIONOBJECTASSOCIATIONTYPE.Add(myActionObjectAssociationType);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myActionObjectAssociationType.ActionObjectAssociationTypeDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion actionobjectassociation
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ActionRelationshipTypeEnum"))
                    {
                        #region actionrelationtype
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.ACTIONRELATIONSHIPTYPE myActionRelationshipType;
                                    myActionRelationshipType = model.ACTIONRELATIONSHIPTYPE.FirstOrDefault(o => o.ActionRelationshipTypeName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myActionRelationshipType == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new ACTIONRELATIONSHIPTYPE " + sEnumerationValue);
                                        myActionRelationshipType = new ACTIONRELATIONSHIPTYPE();
                                        myActionRelationshipType.ActionRelationshipTypeName = sEnumerationValue;
                                        myActionRelationshipType.VocabularyID = iVocabularyCYBOXID;
                                        model.ACTIONRELATIONSHIPTYPE.Add(myActionRelationshipType);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myActionRelationshipType.ActionRelationshipTypeDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion actionrelationtype
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("EventTypeEnum"))
                    {
                        #region eventtype
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.EVENTTYPE myEventType;
                                    myEventType = model.EVENTTYPE.FirstOrDefault(o => o.EventTypeName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myEventType == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new EVENTTYPE " + sEnumerationValue);
                                        myEventType = new EVENTTYPE();
                                        myEventType.EventTypeName = sEnumerationValue;
                                        myEventType.VocabularyID  = iVocabularyCYBOXID;
                                        model.EVENTTYPE.Add(myEventType);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myEventType.EventTypeDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion eventtype
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ObjectRelationshipEnum"))
                    {
                        #region objectrelation
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.OBJECTRELATIONSHIP myObjectRelationship;
                                    myObjectRelationship = model.OBJECTRELATIONSHIP.FirstOrDefault(o => o.ObjectRelationshipName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myObjectRelationship == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new OBJECTRELATIONSHIP " + sEnumerationValue);
                                        myObjectRelationship = new OBJECTRELATIONSHIP();
                                        myObjectRelationship.ObjectRelationshipName = sEnumerationValue;
                                        myObjectRelationship.VocabularyID           = iVocabularyCYBOXID;
                                        model.OBJECTRELATIONSHIP.Add(myObjectRelationship);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myObjectRelationship.ObjectRelationshipDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion objectrelation
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ObjectStateEnum"))
                    {
                        #region objectstate
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.OBJECTSTATE myObjectState;
                                    myObjectState = model.OBJECTSTATE.FirstOrDefault(o => o.ObjectStateName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myObjectState == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new OBJECTSTATE " + sEnumerationValue);
                                        myObjectState = new OBJECTSTATE();
                                        myObjectState.ObjectStateName = sEnumerationValue;
                                        myObjectState.VocabularyID    = iVocabularyCYBOXID;
                                        model.OBJECTSTATE.Add(myObjectState);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myObjectState.ObjectStateDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion objectstate
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("CharacterEncodingEnum"))
                    {
                        #region characterencoding
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.CHARACTERENCODING myCharacterEncoding;
                                    myCharacterEncoding = model.CHARACTERENCODING.FirstOrDefault(o => o.CharacterEncodingName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myCharacterEncoding == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new CHARACTERENCODING " + sEnumerationValue);
                                        myCharacterEncoding = new CHARACTERENCODING();
                                        myCharacterEncoding.CharacterEncodingName = sEnumerationValue;
                                        myCharacterEncoding.VocabularyID          = iVocabularyCYBOXID;
                                        model.CHARACTERENCODING.Add(myCharacterEncoding);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myCharacterEncoding.CharacterEncodingDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion characterencoding
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("InformationSourceTypeEnum"))
                    {
                        #region infosourcetype
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.INFORMATIONSOURCETYPE myInformationSourceType;
                                    myInformationSourceType = model.INFORMATIONSOURCETYPE.FirstOrDefault(o => o.InformationSourceTypeName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myInformationSourceType == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new INFORMATIONSOURCETYPE " + sEnumerationValue);
                                        myInformationSourceType = new INFORMATIONSOURCETYPE();
                                        myInformationSourceType.InformationSourceTypeName = sEnumerationValue;
                                        myInformationSourceType.VocabularyID = iVocabularyCYBOXID;
                                        model.INFORMATIONSOURCETYPE.Add(myInformationSourceType);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myInformationSourceType.InformationSourceTypeDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion infosourcetype
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("HashNameEnum"))
                    {
                        #region hashname
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.HASHNAME myHashName;
                                    myHashName = model.HASHNAME.FirstOrDefault(o => o.HashingAlgorithmName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myHashName == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new HASHNAME " + sEnumerationValue);
                                        myHashName = new HASHNAME();
                                        myHashName.HashingAlgorithmName = sEnumerationValue;
                                        myHashName.VocabularyID         = iVocabularyCYBOXID;
                                        model.HASHNAME.Add(myHashName);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myHashName.HashingAlgorithmDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion hashname
                        bEnumerationProcessed = true;
                    }
                    //***

                    //***********************************************************************************************************************************
                    if (sNodeName.Contains("ToolTypeEnum"))
                    {
                        #region tooltype
                        foreach (XmlNode node2 in node)
                        {
                            //Console.WriteLine(node2.Name);
                            if (node2.Name == "xs:restriction")
                            {
                                foreach (XmlNode nodeEnumeration in node2)  //xs:enumeration
                                {
                                    string sEnumerationValue = nodeEnumeration.Attributes["value"].InnerText;
                                    XORCISMModel.TOOLTYPE myToolType;
                                    myToolType = model.TOOLTYPE.FirstOrDefault(o => o.ToolTypeName == sEnumerationValue);// && o.VocabularyID == iVocabularyCYBOXID);
                                    if (myToolType == null)
                                    {
                                        Console.WriteLine("DEBUG Adding new TOOLTYPE " + sEnumerationValue);
                                        myToolType = new TOOLTYPE();
                                        myToolType.ToolTypeName = sEnumerationValue;
                                        myToolType.VocabularyID = iVocabularyCYBOXID;
                                        model.TOOLTYPE.Add(myToolType);
                                        model.SaveChanges();
                                    }

                                    foreach (XmlNode node3 in nodeEnumeration) //xs:annotation
                                    {
                                        foreach (XmlNode node4 in node3)       //xs:documentation
                                        {
                                            if (node4.Name == "xs:documentation")
                                            {
                                                myToolType.ToolTypeDescription = node4.InnerText;
                                                model.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion tooltype
                        bEnumerationProcessed = true;
                    }
                    //***


                    if (!bEnumerationProcessed)
                    {
                        Console.WriteLine("ERROR Missing Code for " + sNodeName);
                        //sCurrentEnum = "";
                    }
                }
            }

            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());
        }
Esempio n. 12
0
        /* @default : port = "80"
         * @default : strategy | tunning ="x"
         */
        public void Run(string target, int jobID, string policy, string strategy)
        {
            Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "Entering Run()");
            Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("Target = {0} , JobID = {1} , Policy = {2}, Strategy = {3}", target, jobID, policy, strategy));
            string          targetmodified = target.ToLower().Replace("https://", "").Replace("http://", "");
            XORCISMEntities model          = new XORCISMEntities();

            /* On initialise une var */
            //SandcatParser sandcatParser = null;
            string   file = "";
            Assembly a;

            a    = Assembly.GetExecutingAssembly();
            file = string.Format("sandcat_{0}_{1}", DateTime.Now.Ticks, this.GetHashCode());
            Process process = new Process();

            try
            {
                //sandcatParser = new SandcatParser(target, jobID, policy, strategy);

                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "SANDCAT Assembly location = " + a.Location);

                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("JobID: {0} Results will be stored in directory [{1}]", jobID, file));

                string program;
                program = Path.GetDirectoryName(a.Location) + "\\sandcatmini-4.2.5.0\\SandcatCS.exe";   //HARDCODED

                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("Using sandcat at '{0}'", program));

                process.StartInfo.UseShellExecute = true;

                try
                {
                    process.StartInfo.FileName               = program;
                    process.StartInfo.Arguments              = " " + targetmodified + " -sn " + file; //HARDCODED
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = false;
                    process.StartInfo.CreateNoWindow         = true;
                    // process.EnableRaisingEvents = true;
                    // process.Exited += new EventHandler(Process_Exited);
                    process.Start();
                    // Process.Start(vProgram,vIAnnotationLocal.Folder + vIAnnotationLocal.EntryPoint);
                }
                catch (Win32Exception vException)
                {
                    if (vException.NativeErrorCode == ERROR_FILE_NOT_FOUND)
                    {
                        Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("ERROR_FILE_NOT_FOUND : Exception = {0}", vException.Message));
                        //return null;
                    }
                    else if (vException.NativeErrorCode == ERROR_ACCESS_DENIED)
                    {
                        Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("ERROR_ACCESS_DENIED : Exception = {0}", vException.Message));
                        //return null;
                    }
                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "JobID:" + jobID + "Exception RunningSandcat = " + ex.Message + " " + ex.InnerException);
                }

                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("sandcat is running"));
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "JobID:" + jobID + "Exception SandcatParser = " + ex.Message + " " + ex.InnerException);
            }

            try
            {
                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("Waiting for sandcat to finish"));

                process.WaitForExit(1800000);    //3 hours
            }
            catch (Exception vException)
            {
                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("TimeException = {0}", vException.Message));
                //return null;
            }

            Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "sandcat has finished");
            StreamReader SR        = process.StandardOutput;
            string       strOutput = SR.ReadToEnd();

            Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("Output: " + strOutput));

            //demo.testfire.net [80]_Vulns.log
            string resultfile;

            resultfile = Path.Combine(Path.GetDirectoryName(a.Location), "\\sandcatmini-4.2.5.0\\Rep\\" + file + "\\" + targetmodified + " [80]_Vulns.log");    //HARDCODED

            /*
             * "vname=search.aspx XSS",vpars=txtSearch,vlns=,vrisk=Medium,vpath=http://demo.testfire.net/search.aspx?txtSearch=[script]alert('Vulnerable')[/script],vstat=200,"f=Application Vuln.xrm"
             * "vname=comment.aspx XSS",vpars=name,vlns=,vrisk=Medium,"vpath=http://demo.testfire.net/comment.aspx?cfile=comments.txt&name=[script]alert('Vulnerable')[/script]&email_addr=&subject=Sandcat&comments=&submit= Submit&reset= Clear Form",vstat=200,"f=Application Vuln (2).xrm"
             * "vname=login.aspx XSS",vpars=uid,vlns=,vrisk=Medium,vpath=http://demo.testfire.net/bank/login.aspx?uid=[script]alert(document.cookie)[/script]&passw=&btnSubmit=Login,vstat=200,"f=Application Vuln (3).xrm"
             * "vname=default.aspx Directory Traversal",vpars=content,vlns=,vrisk=High,vpath=http://demo.testfire.net/default.aspx?content=../../../../../../../../boot.ini%00inside_contact.htm,vstat=200,"f=Application Vuln (4).xrm"
             */


            try
            {
                StreamReader myfilereader = new StreamReader(resultfile);
                string       ligne        = myfilereader.ReadLine();
                while (ligne != null)
                {
                    Console.WriteLine(ligne);

                    VulnerabilityFound    vulnerabilityFound    = new VulnerabilityFound();
                    VulnerabilityEndPoint vulnerabilityEndPoint = new VulnerabilityEndPoint();

                    vulnerabilityFound.InnerXml = ligne;

                    vulnerabilityEndPoint.IpAdress = target;
                    vulnerabilityEndPoint.Port     = 80;    //TODO: à voir
                    vulnerabilityEndPoint.Protocol = "TCP"; //HARDCODED
                    vulnerabilityEndPoint.Service  = "WWW";

                    string[] arInfo   = new string[7];
                    char[]   splitter = { ',' };
                    arInfo = ligne.Split(splitter);
                    for (int x = 0; x < arInfo.Length; x++)
                    {
                        if (arInfo[x].Contains("vname"))
                        {
                            vulnerabilityFound.Title = arInfo[x].Replace("vname=", "").Replace("\"", "");
                        }
                        else
                        {
                            if (arInfo[x].Contains("vpars"))
                            {
                                vulnerabilityFound.VulnerableParameter = arInfo[x].Replace("vpars=", "").Replace("\"", "");
                            }
                            else
                            {
                                if (arInfo[x].Contains("vrisk"))
                                {
                                    vulnerabilityFound.Severity = arInfo[x].Replace("vrisk=", "").Replace("\"", "");
                                }
                                else
                                {
                                    if (arInfo[x].Contains("vpath"))
                                    {
                                        vulnerabilityFound.Url = arInfo[x].Replace("vpath=", "").Replace("\"", "");
                                    }
                                }
                            }
                        }
                    }
                    VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, jobID, "sandcat", model);

                    ligne = myfilereader.ReadLine();
                }
                myfilereader.Close();
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "JobID:" + jobID + "Exception SandcatReader = " + ex.Message + " " + ex.InnerException + " " + resultfile);
            }


            string status = XCommon.STATUS.FINISHED.ToString();

            // =================================================
            // Change the status of the job to FINISHED or ERROR
            // =================================================

            /*
             * if (sandcatParser.Parse() == false)
             * {
             *  status = XCommon.STATUS.ERROR.ToString();
             *  Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("Updating job {0} status to ERROR", jobID));
             *  XCommon.Utils.Helper_SendEmail("*****@*****.**", "Sandcat ERROR", "Sandcat ERROR for job:" + jobID);
             * }
             * else
             * {
             *  Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", string.Format("Updating job {0} status to FINISHED", jobID));
             * }
             */
            try
            {
                var Q = from j in model.JOB
                        where j.JobID == jobID
                        select j;

                JOB myJob = Q.FirstOrDefault();
                myJob.Status  = status;
                myJob.DateEnd = DateTimeOffset.Now;
                //image
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                myJob.XmlResult = encoding.GetBytes(m_data);
                model.SaveChanges();
                //FREE MEMORY
                model.Dispose();
                //    sandcatParser = null;
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "JobID:" + jobID + "Exception UpdateJob = " + ex.Message + " " + ex.InnerException);
            }

            Utils.Helper_Trace("XORCISM PROVIDER SANDCAT", "JobID:" + jobID + "Leaving Run()");
        }
Esempio n. 13
0
        /// <summary>
        /// Copyright (C) 2015 Jerome Athias
        /// Imports the Common Criteria (CC) XML file in an XORCISM database
        /// All trademarks and registered trademarks are the property of their respective owners.
        /// This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
        ///
        /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
        ///
        /// You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
        /// </summary>

        static void Main(string[] args)
        {
            //  Use cc3R4.xml from https://www.commoncriteriaportal.org/cc/

            Console.WriteLine("DEBUG Importing Common Criteria");

            XORCISMEntities model = null;

            try
            {
                model = new XORCISMEntities();
                Console.WriteLine("DEBUG Model loaded");
            }
            catch (Exception exModel)
            {
                Console.WriteLine("Exception: exModel " + exModel.Message + " " + exModel.InnerException);
            }

            int iVocabularyCommonCriteriaID = 0;

            #region vocabularyCommonCriteria
            try
            {
                iVocabularyCommonCriteriaID = model.VOCABULARY.Where(o => o.VocabularyName == "Common Criteria").Select(o => o.VocabularyID).FirstOrDefault();
            }
            catch (Exception ex)
            {
            }
            if (iVocabularyCommonCriteriaID <= 0)
            {
                VOCABULARY oVocabulary = new VOCABULARY();
                oVocabulary.CreatedDate    = DateTimeOffset.Now;
                oVocabulary.VocabularyName = "Common Criteria";  //Hardcoded
                //TODO? Version
                model.VOCABULARY.Add(oVocabulary);
                model.SaveChanges();
                iVocabularyCommonCriteriaID = oVocabulary.VocabularyID;
                Console.WriteLine("DEBUG iVocabularyCommonCriteriaID=" + iVocabularyCommonCriteriaID);
            }
            else
            {
                //Update VocabularyCommonCriteria
            }
            #endregion vocabularyCommonCriteria


            //TODO: Download if needed
            //Hardcoded
            string sDownloadFileURL     = "https://www.commoncriteriaportal.org/files/ccfiles/cc3R4.xml.zip";
            string sDownloadFileName    = "cc3R4.xml.zip";
            string sDownloadLocalPath   = "C:/nvdcve/";
            string sDownloadLocalFolder = @"C:\nvdcve\";
            string sDownloadLocalFile   = "cc3R4.xml";

            XmlDocument doc;
            doc = new XmlDocument();

            //NOTE: probably not the best/fastest way to parse XML but easy/clear enough

            try
            {
                //doc.Load(@"X:\SOURCES\Import_CommonCriteria\bin\Release\cc3R4.xml");
                doc.Load(sDownloadLocalFolder + sDownloadLocalFile);
                Console.WriteLine("DEBUG " + DateTimeOffset.Now);
                Console.WriteLine("DEBUG XML file loaded");
            }
            catch (Exception exdocLoad)
            {
                Console.WriteLine("Exception: exdocLoad :\n" + exdocLoad.Message + " " + exdocLoad.InnerException);
            }


            XmlNamespaceManager mgr = null;
            try
            {
                mgr = new XmlNamespaceManager(doc.NameTable);
            }
            catch (Exception exXmlNamespaceManager)
            {
                Console.WriteLine("Exception: exXmlNamespaceManager :\n" + exXmlNamespaceManager.Message + " " + exXmlNamespaceManager.InnerException);
            }

            /*
             * mgr.AddNamespace("clauses", "");
             */

            XmlNode     XMLRoot  = doc.DocumentElement;
            XmlNodeList XMLNodes = XMLRoot.ChildNodes;
            foreach (XmlNode XNode in XMLNodes)
            {
                //Console.WriteLine("DEBUG XNode.Name: " + XNode.Name);
                //<clause title="Terms and definitions, symbols and abbreviated terms" id="a-definitions" category="normative" type="normal">
                switch (XNode.Name)
                {
                case "clause":
                    try
                    {
                        string XNodeTitle = XNode.Attributes["title"].InnerText;
                        Console.WriteLine("DEBUG XNode.title: " + XNodeTitle);
                        if (XNodeTitle.Contains("Terms and definitions"))       //HARDCODED
                        {
                            /*
                             * <glossentry id="action">
                             *  <glossterm>action</glossterm>
                             *  <glossdef>evaluator action element of the CC Part 3</glossdef>
                             *  <glossnote>
                             *      These actions are either explicitly stated as evaluator actions or implicitly derived from developer actions (implied evaluator actions) within the CC Part 3 assurance components.
                             *  </glossnote>
                             * </glossentry>
                             */
                            //  We list all the gloassry definitions
                            XmlNodeList XMLGlossEntries = XNode.ChildNodes;
                            foreach (XmlNode XGlossEntry in XMLGlossEntries)
                            {
                                try
                                {
                                    Console.WriteLine("DEBUG XGlossEntry.id: " + XGlossEntry.Attributes["id"].InnerText);
                                }
                                catch (Exception exGlossEntryID)
                                {
                                    Console.WriteLine("Exception exGlossEntryID: " + exGlossEntryID.Message + " " + exGlossEntryID.InnerException);
                                }
                            }
                        }
                    }
                    catch (Exception exXNodeTitle)
                    {
                        Console.WriteLine("Exception exXNodeTitle: " + exXNodeTitle.Message + " " + exXNodeTitle.InnerException);
                    }

                    try
                    {
                        //Console.WriteLine("DEBUG XNode.id: " + XNode.Attributes["id"].InnerText);
                    }
                    catch (Exception exXNodeID)
                    {
                        Console.WriteLine("Exception exXNodeID: " + exXNodeID.Message + " " + exXNodeID.InnerException);
                    }
                    break;

                    try
                    {
                        //Console.WriteLine("DEBUG XNode.category: " + XNode.Attributes["category"].InnerText);
                    }
                    catch (Exception exXNodeCategory)
                    {
                        Console.WriteLine("Exception exXNodeCategory: " + exXNodeCategory.Message + " " + exXNodeCategory.InnerException);
                    }
                    break;

                //******************************************************************************************************************************************
                //<subclause title="Organisation of CC Part 3" id="assurance-scope-organisation">
                //TODO


                case "f-class":
                    //TODO
                    break;

                case "a-class":     //Assurance Class
                    //TODO
                    break;

                case "eal":         //Evaluation Assurance Level
                    //TODO
                    break;

                case "cap":         //?
                    //TODO
                    break;

                case "patchinfo":
                    //TODO
                    break;

                default:
                    Console.WriteLine("ERROR Missing code for " + XNode.Name);
                    break;
                }
            }
        }
Esempio n. 14
0
        public void Start()
        {
            // ==================================================================
            // Recovery mode : start again any previously running session threads
            // ==================================================================
            XORCISMEntities context;

            context = new XORCISMEntities();

            // Explicitly open the connection.
            //context.Connection.Open();

            #region RecoveryMode
            try
            {
                string status;
                status = XCommon.STATUS.RUNNING.ToString();
                //Search in the database the Sessions with a Status of "Running"
                var runningSessions = from s in context.SESSION
                                      where s.Status == status
                                      select s;
                //If any
                if (runningSessions.Count() > 0)
                {
                    //For each of the "Running" Sessions
                    foreach (SESSION oneSession in runningSessions.ToList())
                    {
                        //Depending on the ServiceCategory of the Session
                        switch (oneSession.ServiceCategoryID)
                        {
                        case 8:     //HARDCODED
                        {
                            //Monitoring
                            //Dealing with the previous jobs
                            //Searching the Jobs attached to the current Session
                            var query = from j in context.JOB
                                        where j.SessionID == oneSession.SessionID
                                        select j;
                            //Marks all the Session's Jobs as FINISHED
                            foreach (JOB oneJob in query.ToList())
                            {
                                oneJob.Status = XCommon.STATUS.FINISHED.ToString();

                                context.SaveChanges();
                            }
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} will be recovered", oneSession.SessionID));
                            //Marks the Session's status as IDLE (so it will be (re)started)
                            oneSession.Status = XCommon.STATUS.IDLE.ToString();
                            Utils.Helper_Trace("MANAGER ENGINE", "TRACE4");
                            context.SaveChanges();

                            break;
                        }

                        default:
                        {
                            //Canceling the session (changing status)
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} TOCANCEL", oneSession.SessionID));
                            oneSession.Status = XCommon.STATUS.TOCANCEL.ToString();

                            context.SaveChanges();

                            break;
                        }
                        }
                    }
                }
            }
            catch (ThreadAbortException exThreadAbort)
            {
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadError in recovery : Exception = {0}", exThreadAbort.Message));
                return;
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error in recovery : Exception = {0} - {1}", ex.Message, ex.InnerException));

                //    return;
            }
            #endregion RecoveryMode

            // ==============================
            // Create the main polling thread
            // ==============================

            Utils.Helper_Trace("MANAGER ENGINE", "Launching main polling thread");

            m_ListRunningSessionThread = new Dictionary <int, LaunchSessionThreadInfo>();

            m_Thread = new Thread(new ThreadStart(FuncThread));
            m_Thread.Start();
        }
Esempio n. 15
0
        private void FuncThread()
        {
            XORCISMEntities context;

            context = new XORCISMEntities();

            // Explicitly open the connection.
            //context.Connection.Open();



            // =================
            // Main polling loop
            // =================

            try
            {
                while (true)    //Infinite loop
                {
                    // =============================================================================
                    // PHASE 0 : Look in table SESSION and let's see if there is something to cancel
                    // =============================================================================

                    #region Phase0
                    //Utils.Helper_Trace("MANAGER ENGINE", "Looking for new session to cancel (those with status = 'ToCancel')");

                    string status;
                    status = XCommon.STATUS.TOCANCEL.ToString();

                    XORCISMModel.SESSION cancelSession;
                    cancelSession = context.SESSION.FirstOrDefault(s => s.Status == status);

                    if (cancelSession != null)
                    {
                        // ===============================
                        // Abort the Launch Session thread
                        // ===============================

                        if (m_ListRunningSessionThread.ContainsKey(cancelSession.SessionID) == true)
                        {
                            LaunchSessionThreadInfo info;
                            info = m_ListRunningSessionThread[cancelSession.SessionID];

                            Thread musCanceledThread;
                            musCanceledThread = info.Thread;

                            musCanceledThread.Abort(cancelSession.SessionID.ToString());

                            // ==============================
                            // Launch a Cancel Session thread
                            // ==============================

                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Launching cancel session thread (sessionID={0})", cancelSession.SessionID));

                            cancelSession.Status = XCommon.STATUS.CANCELLING.ToString();

                            context.SaveChanges();

                            ParameterizedThreadStart ts;
                            ts = new ParameterizedThreadStart(FuncThreadCancelSession);

                            Thread thread;
                            thread = new Thread(ts);

                            thread.Start(info);
                        }
                        else
                        {
                            //Canceling after Manager crash/reboot
                            //Session is not in m_ListRunningSessionThread
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} must be canceled", cancelSession.SessionID));

                            //int accountID;
                            //accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID;

                            // =============================
                            // Cancel the jobs on the agents
                            // =============================

                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Cancelling jobs on agents", cancelSession.SessionID));

                            var jobs = from jc in context.JOB
                                       where jc.SessionID == cancelSession.SessionID
                                       select jc;

                            foreach (JOB J in jobs.ToList())
                            {
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Handling job {1}", cancelSession.SessionID, J.JobID));

                                // ====================================
                                // Contact the agent and cancel the job
                                // ====================================

                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Trying to contact the agent", cancelSession.SessionID));

                                try
                                {
                                    ServiceReferenceAgent.Service1Client service;
                                    service = new ServiceReferenceAgent.Service1Client();

                                    // TODO :
                                    // service.Endpoint.Address = bestAgent.IPAddress;

                                    service.CancelJob(J.JobID);

                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : The agent has been successfully contacted", cancelSession.SessionID));
                                }
                                catch (Exception ex)
                                {
                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Error contacting the agent. Exception = {1} {2}", cancelSession.SessionID, ex.Message, ex.InnerException));
                                    XCommon.Utils.Helper_SendEmail("*****@*****.**", "MANAGER ENGINE ERROR", "CANCELSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException);
                                    //return;
                                }
                            }

                            // =============================
                            // Update table SESSION (Status)
                            // =============================

                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Updating status in table SESSION to CANCELED", cancelSession.SessionID));
                            try
                            {
                                cancelSession.Status  = XCommon.STATUS.CANCELED.ToString();
                                cancelSession.DateEnd = DateTimeOffset.Now;

                                context.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Error CANCELED. Exception = {1}", cancelSession.SessionID, ex.Message));
                                //return;
                            }
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Finished", cancelSession.SessionID));
                        }
                    }
                    #endregion Phase0

                    // =============================================================================
                    // PHASE 1 : Look in table SESSION and let's see if there is something to launch
                    // =============================================================================

                    Utils.Helper_Trace("MANAGER ENGINE", "Looking for new session to start (status IDLE)");    //DO NOT COMMENT THIS LINE

                    string Statut = XCommon.STATUS.IDLE.ToString();

                    var session = context.SESSION.FirstOrDefault(s => s.Status == Statut);

                    if (session != null)
                    {
                        int sessionID;
                        sessionID = session.SessionID;

                        //Check if the Account and User are still valid
                        USERACCOUNT user = null;
                        user = context.USERACCOUNT.SingleOrDefault(o => o.UserID == session.UserID);
                        if (user.ACCOUNT.ValidUntilDate != null && user.ACCOUNT.ValidUntilDate < DateTimeOffset.Now)
                        {
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Account not valid for session {0}", sessionID));
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Changing session (sessionID={0}) to CANCELED", sessionID));

                            session.Status = XCommon.STATUS.CANCELED.ToString();
                            context.SaveChanges();
                        }
                        else
                        {
                            if (m_ListRunningSessionThread.ContainsKey(sessionID) == true)
                            {
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} is supposed to be launched but a thread is already running for this session !", sessionID));
                            }
                            else
                            {
                                // =======================
                                // Launch a session thread
                                // =======================

                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("Launching session (sessionID={0})", sessionID));

                                session.Status = XCommon.STATUS.RUNNING.ToString();
                                context.SaveChanges();

                                ParameterizedThreadStart managerThreadStart;
                                managerThreadStart = new ParameterizedThreadStart(FuncThreadLaunchSession);

                                Thread thread;
                                thread = new Thread(managerThreadStart);

                                LaunchSessionThreadInfo info;
                                info = new LaunchSessionThreadInfo(sessionID, thread);

                                thread.Start(info);

                                // ========================
                                // Put it in the dictionary
                                // ========================

                                m_ListRunningSessionThread.Add(sessionID, info);
                            }
                        }
                    }

                    // ===================================================================================
                    // PHASE 2 : Look in table SESSIONCRON and let's see if we have to create new sessions
                    // ===================================================================================

                    Statut = XCommon.STATUS.IDLE.ToString();

                    var q = context.SESSIONCRON.Where(o => o.Status == Statut);

                    foreach (SESSIONCRON sessionCron in q.ToList())
                    {
                        if (sessionCron.DateEnd == null || sessionCron.DateEnd > DateTime.Now)
                        {
                            //Check if the Account and User are still valid
                            USERACCOUNT user = null;
                            user = context.USERACCOUNT.SingleOrDefault(o => o.UserID == sessionCron.UserID);
                            if (user.ACCOUNT.ValidUntilDate != null && user.ACCOUNT.ValidUntilDate < DateTimeOffset.Now)
                            {
                                //Utils.Helper_Trace("MANAGER ENGINE", string.Format("Account not valid for entry {0} in table SESSIONCRON", sessionCron.SessionCronID));
                            }
                            else
                            {
                                CrontabSchedule schedule;
                                schedule = CrontabSchedule.Parse(sessionCron.CronExpression);

                                DateTimeOffset start = DateTimeOffset.Now;
                                DateTimeOffset end   = start + TimeSpan.FromDays(2 * 360);

                                var occurrence = schedule.GetNextOccurrences(start, end).GetEnumerator();
                                occurrence.MoveNext();
                                //                        Utils.Helper_Trace("MANAGER ENGINE", "SessionCron "+sessionCron.SessionCronID+" Next occurrence=" + occurrence.Current.DayOfWeek.ToString() + " " + occurrence.Current.Day.ToString() + "/" + occurrence.Current.Month.ToString() + "/" + occurrence.Current.Year.ToString() + " " + occurrence.Current.Hour.ToString() + "H" + occurrence.Current.Minute.ToString() + ":" + occurrence.Current.Second.ToString());

                                TimeSpan ts;
                                ts = occurrence.Current - start;
                                if (ts.TotalSeconds <= 5.0)
                                {
                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("Cron expression for entry {0} in table SESSIONCRON has triggered an execution", sessionCron.SessionCronID));

                                    // ================================
                                    // Extract and parse the parameters
                                    // ================================

                                    Dictionary <string, object> dicoParameters;
                                    try
                                    {
                                        MemoryStream ms;
                                        ms = new MemoryStream(sessionCron.Parameters);

                                        BinaryFormatter bf;
                                        bf = new BinaryFormatter();

                                        dicoParameters = (Dictionary <string, object>)bf.Deserialize(ms);
                                    }
                                    catch (Exception e)
                                    {
                                        Utils.Helper_Trace("MANAGER SERVICE", string.Format("Exception while deserializing parameters : {0}", e.Message));
                                        return;
                                    }

                                    int[] tabAssetID = null;
                                    if (dicoParameters["ASSETS"] != null)
                                    {
                                        tabAssetID = (int[])dicoParameters["ASSETS"];
                                    }

                                    // ================================
                                    // Add a new entry in table SESSION
                                    // ================================

                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("Adding an entry in table SESSION"));

                                    SESSION tmpSession = new SESSION();
                                    //xxx
                                    try
                                    {
                                        tmpSession.UserID            = sessionCron.UserID;
                                        tmpSession.Status            = XCommon.STATUS.IDLE.ToString();
                                        tmpSession.ServiceCategoryID = sessionCron.ServiceCategoryID;
                                        tmpSession.DateStart         = DateTimeOffset.Now;
                                        tmpSession.DateEnd           = null;
                                        tmpSession.Parameters        = sessionCron.Parameters;
                                        tmpSession.SessionCronID     = sessionCron.SessionCronID;

                                        context.SESSION.Add(tmpSession);

                                        context.SaveChanges();

                                        //xxx
                                    }
                                    catch (Exception ex)
                                    {
                                        //xxx

                                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error adding entry in table SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message));
                                        throw ex;
                                    }

                                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SessionID = {0}", tmpSession.SessionID));

                                    // ============================================
                                    // Add several entries in table ASSETSESSION
                                    // ============================================

                                    if (tabAssetID != null)
                                    {
                                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("Adding {0} entries in table ASSETSESSION", tabAssetID.Count()));
                                        try
                                        {
                                            foreach (int assetID in tabAssetID)
                                            {
                                                ASSETSESSION tmpAinS = new ASSETSESSION();
                                                tmpAinS.SESSION = tmpSession;
                                                tmpAinS.AssetID = assetID;
                                                context.ASSETSESSION.Add(tmpAinS);
                                            }
                                            context.SaveChanges();
                                        }
                                        catch (Exception ex)
                                        {
                                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error adding entries in table ASSETSESSION : Exception = {0}", ex.Message));
                                            throw ex;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // =====
                    // Sleep
                    // =====

                    Thread.Sleep(5000); //Hardcoded
                }
            }
            catch (ThreadAbortException exThreadAbort)
            {
                //int SessionId;
                //SessionId=Convert.ToInt32((string)exThreadAbort.ExceptionState);
                //XORCISMModel.SESSION musBeCanceledSession;
                //musBeCanceledSession=context.SESSION.SingleOrDefault(s => s.SessionID == SessionId);
                //if (musBeCanceledSession != null)
                //{
                //    musBeCanceledSession.Status = XCommon.STATUS.TOCANCEL.ToString();
                //    context.SaveChanges();
                //}
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadError in main polling loop : Exception = {0}", exThreadAbort.Message));
                //HARDCODED
                XCommon.Utils.Helper_SendEmail("*****@*****.**", "ThreadError in XManager", "MyException = " + exThreadAbort.Message + " " + exThreadAbort.InnerException);
                return;
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error in main polling loop : Exception = {0} {1}", ex.Message, ex.InnerException));
                //HARDCODED
                XCommon.Utils.Helper_SendEmail("*****@*****.**", "Error in XManager", "MyException = " + ex.Message + " " + ex.InnerException);
                return;
            }
        }
Esempio n. 16
0
        static void Main()
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            //https://raw.github.com/vz-risk/veris/master/verisc-enum.json

            try
            {
                WebClient wc = new WebClient();
                Console.WriteLine("Downloading verisc-enum.json");
                wc.DownloadFile("https://raw.github.com/vz-risk/veris/master/verisc-enum.json", "C:/nvdcve/verisc-enum.json");  //HARDCODED
                //
                wc.Dispose();
                //Console.WriteLine("Download is completed", "info", MessageBoxButtons.OK, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while downloading\n" + ex.Message + " " + ex.InnerException);
            }

            // create reader & open file
            StreamReader tr = new StreamReader(@"C:\nvdcve\verisc-enum.json");  //HARDCODED

            // read the file
            string verisenum = tr.ReadToEnd();

            //Console.WriteLine(verisenum);

            // close the stream
            tr.Close();


            XORCISMEntities model = new XORCISMEntities();

            XTHREATEntities threat_model = new XTHREATEntities();


            JsonObject jobj   = (JsonObject)JsonConvert.Import(verisenum);
            JsonArray  jarray = new JsonArray();

            foreach (string loc in jobj.Names)
            {
                //Console.WriteLine(loc);
                switch (loc)
                {
                case "security_compromise":

                    break;

                case "confidence":

                    break;

                case "victim":
                    //Console.WriteLine(Convert.ToString(((JsonObject)jobj[loc])["employee_count"]));
                    jarray = (JsonArray)((JsonObject)jobj[loc])["employee_count"];
                    for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                    {
                        //Console.WriteLine(Convert.ToString(jarray[cpt]));
                    }
                    break;

                case "actor":

                    break;

                case "action":
                    //Console.WriteLine(Convert.ToString(((JsonObject)jobj[loc])["malware"]));
                    //************* MALWARE **************************
                    JsonObject jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["malware"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        //vector
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=1  //malware
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 1 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 1;         //malware
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "vector":
                            jarray = (JsonArray)(jobj2)["vector"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVectorName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVectorName);
                                //ThreatActionCategoryID=1  //malware
                                XTHREATModel.THREATACTIONVECTOR tactionvector = new THREATACTIONVECTOR();
                                tactionvector = threat_model.THREATACTIONVECTOR.FirstOrDefault(o => o.ThreatActionCategoryID == 1 && o.ThreatActionVectorName == sThreatActionVectorName);
                                if (tactionvector == null)
                                {
                                    tactionvector = new THREATACTIONVECTOR();
                                    tactionvector.ThreatActionCategoryID = 1;          //malware
                                    tactionvector.ThreatActionVectorName = sThreatActionVectorName;
                                    threat_model.THREATACTIONVECTOR.Add(tactionvector);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine("ERROR " + loc2 + " is unknown for action.malware");
                            break;
                        }
                    }

                    //************* HACKING **************************
                    jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["hacking"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        //vector
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=2  //hacking
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 2 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 2;         //hacking
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "vector":
                            jarray = (JsonArray)(jobj2)["vector"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVectorName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVectorName);
                                //ThreatActionCategoryID=2  //hacking
                                XTHREATModel.THREATACTIONVECTOR tactionvector = new THREATACTIONVECTOR();
                                tactionvector = threat_model.THREATACTIONVECTOR.FirstOrDefault(o => o.ThreatActionCategoryID == 2 && o.ThreatActionVectorName == sThreatActionVectorName);
                                if (tactionvector == null)
                                {
                                    tactionvector = new THREATACTIONVECTOR();
                                    tactionvector.ThreatActionCategoryID = 2;          //hacking
                                    tactionvector.ThreatActionVectorName = sThreatActionVectorName;
                                    threat_model.THREATACTIONVECTOR.Add(tactionvector);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine(loc2 + " is unknown for action.hacking");
                            break;
                        }
                    }

                    //************* SOCIAL **************************
                    jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["social"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        //vector
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=3  //social
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 3 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 3;         //social
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "vector":
                            jarray = (JsonArray)(jobj2)["vector"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVectorName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVectorName);
                                //ThreatActionCategoryID=3  //social
                                XTHREATModel.THREATACTIONVECTOR tactionvector = new THREATACTIONVECTOR();
                                tactionvector = threat_model.THREATACTIONVECTOR.FirstOrDefault(o => o.ThreatActionCategoryID == 3 && o.ThreatActionVectorName == sThreatActionVectorName);
                                if (tactionvector == null)
                                {
                                    tactionvector = new THREATACTIONVECTOR();
                                    tactionvector.ThreatActionCategoryID = 3;          //social
                                    tactionvector.ThreatActionVectorName = sThreatActionVectorName;
                                    threat_model.THREATACTIONVECTOR.Add(tactionvector);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "target":
                            jarray = (JsonArray)(jobj2)["target"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionTargetName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionTargetName);
                                //ThreatActionCategoryID=3  //social
                                XTHREATModel.THREATACTIONTARGET tactiontarget = new THREATACTIONTARGET();
                                tactiontarget = threat_model.THREATACTIONTARGET.FirstOrDefault(o => o.ThreatActionCategoryID == 3 && o.ThreatActionTargetName == sThreatActionTargetName);
                                if (tactiontarget == null)
                                {
                                    tactiontarget = new THREATACTIONTARGET();
                                    tactiontarget.ThreatActionCategoryID = 3;          //social
                                    tactiontarget.ThreatActionTargetName = sThreatActionTargetName;
                                    threat_model.THREATACTIONTARGET.Add(tactiontarget);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine(loc2 + " is unknown for action.social");
                            break;
                        }
                    }

                    //************* SOCIAL **************************
                    jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["social"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        //vector
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=3  //social
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 3 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 3;         //social
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "vector":
                            jarray = (JsonArray)(jobj2)["vector"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVectorName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVectorName);
                                //ThreatActionCategoryID=3  //social
                                XTHREATModel.THREATACTIONVECTOR tactionvector = new THREATACTIONVECTOR();
                                tactionvector = threat_model.THREATACTIONVECTOR.FirstOrDefault(o => o.ThreatActionCategoryID == 3 && o.ThreatActionVectorName == sThreatActionVectorName);
                                if (tactionvector == null)
                                {
                                    tactionvector = new THREATACTIONVECTOR();
                                    tactionvector.ThreatActionCategoryID = 3;          //social
                                    tactionvector.ThreatActionVectorName = sThreatActionVectorName;
                                    threat_model.THREATACTIONVECTOR.Add(tactionvector);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine(loc2 + " is unknown for action.social");
                            break;
                        }
                    }

                    //************* MISUSE **************************
                    jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["misuse"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        //vector
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=4  //misuse
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 4 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 4;         //misuse
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "vector":
                            jarray = (JsonArray)(jobj2)["vector"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVectorName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVectorName);
                                //ThreatActionCategoryID=4  //misuse
                                XTHREATModel.THREATACTIONVECTOR tactionvector = new THREATACTIONVECTOR();
                                tactionvector = threat_model.THREATACTIONVECTOR.FirstOrDefault(o => o.ThreatActionCategoryID == 4 && o.ThreatActionVectorName == sThreatActionVectorName);
                                if (tactionvector == null)
                                {
                                    tactionvector = new THREATACTIONVECTOR();
                                    tactionvector.ThreatActionCategoryID = 4;          //misuse
                                    tactionvector.ThreatActionVectorName = sThreatActionVectorName;
                                    threat_model.THREATACTIONVECTOR.Add(tactionvector);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine(loc2 + " is unknown for action.misuse");
                            break;
                        }
                    }

                    //************* PHYSICAL **************************
                    jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["physical"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        //vector
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=5  //physical
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 5 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 5;         //physical
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "location":
                            jarray = (JsonArray)(jobj2)["location"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionLocationName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionLocationName);
                                //ThreatActionCategoryID=5  //physical
                                XTHREATModel.THREATACTIONLOCATION tactionlocation = new THREATACTIONLOCATION();
                                tactionlocation = threat_model.THREATACTIONLOCATION.FirstOrDefault(o => o.ThreatActionLocationName == sThreatActionLocationName);
                                if (tactionlocation == null)
                                {
                                    tactionlocation = new THREATACTIONLOCATION();
                                    //tactionlocation.ThreatActionCategoryID = 5;  //physical
                                    tactionlocation.ThreatActionLocationName = sThreatActionLocationName;
                                    threat_model.THREATACTIONLOCATION.Add(tactionlocation);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "vector":
                            jarray = (JsonArray)(jobj2)["vector"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVectorName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVectorName);
                                //ThreatActionCategoryID=5  //physical
                                XTHREATModel.THREATACTIONVECTOR tactionvector = new THREATACTIONVECTOR();
                                tactionvector = threat_model.THREATACTIONVECTOR.FirstOrDefault(o => o.ThreatActionCategoryID == 5 && o.ThreatActionVectorName == sThreatActionVectorName);
                                if (tactionvector == null)
                                {
                                    tactionvector = new THREATACTIONVECTOR();
                                    tactionvector.ThreatActionCategoryID = 5;          //physical
                                    tactionvector.ThreatActionVectorName = sThreatActionVectorName;
                                    threat_model.THREATACTIONVECTOR.Add(tactionvector);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine(loc2 + " is unknown for action.physical");
                            break;
                        }
                    }

                    //************* ERROR **************************
                    jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["error"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        //vector
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=6  //error
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 6 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 6;         //error
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        case "vector":
                            jarray = (JsonArray)(jobj2)["vector"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVectorName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVectorName);
                                //ThreatActionCategoryID=6  //error
                                XTHREATModel.THREATACTIONVECTOR tactionvector = new THREATACTIONVECTOR();
                                tactionvector = threat_model.THREATACTIONVECTOR.FirstOrDefault(o => o.ThreatActionCategoryID == 6 && o.ThreatActionVectorName == sThreatActionVectorName);
                                if (tactionvector == null)
                                {
                                    tactionvector = new THREATACTIONVECTOR();
                                    tactionvector.ThreatActionCategoryID = 6;          //error
                                    tactionvector.ThreatActionVectorName = sThreatActionVectorName;
                                    threat_model.THREATACTIONVECTOR.Add(tactionvector);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine(loc2 + " is unknown for action.error");
                            break;
                        }
                    }

                    //************* ENVIRONMENTAL **************************
                    jobj2 = (JsonObject)JsonConvert.Import(Convert.ToString(((JsonObject)jobj[loc])["environmental"]));

                    foreach (string loc2 in jobj2.Names)
                    {
                        //Console.WriteLine(loc2);
                        //variety
                        switch (loc2)
                        {
                        case "variety":
                            jarray = (JsonArray)(jobj2)["variety"];
                            for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                            {
                                string sThreatActionVarietyName = Convert.ToString(jarray[cpt]);
                                //Console.WriteLine(sThreatActionVarietyName);
                                //ThreatActionCategoryID=7  //environmental
                                XTHREATModel.THREATACTIONVARIETY tactionvariety = new THREATACTIONVARIETY();
                                tactionvariety = threat_model.THREATACTIONVARIETY.FirstOrDefault(o => o.ThreatActionCategoryID == 7 && o.ThreatActionVarietyName == sThreatActionVarietyName);
                                if (tactionvariety == null)
                                {
                                    tactionvariety = new THREATACTIONVARIETY();
                                    tactionvariety.ThreatActionCategoryID  = 7;         //environmental
                                    tactionvariety.ThreatActionVarietyName = sThreatActionVarietyName;
                                    threat_model.THREATACTIONVARIETY.Add(tactionvariety);
                                    threat_model.SaveChanges();
                                }
                            }
                            break;

                        default:
                            Console.WriteLine(loc2 + " is unknown for action.environmental");
                            break;
                        }
                    }

                    break;

                case "asset":
                    jarray = (JsonArray)((JsonObject)jobj[loc])["variety"];
                    for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                    {
                        string sAssetVarietyName = Convert.ToString(jarray[cpt]);
                        //Console.WriteLine(sAssetVarietyName);
                        XORCISMModel.ASSETVARIETY assetvariety = new ASSETVARIETY();
                        assetvariety = model.ASSETVARIETY.FirstOrDefault(o => o.AssetVarietyName == sAssetVarietyName);
                        if (assetvariety == null)
                        {
                            assetvariety = new ASSETVARIETY();
                            assetvariety.AssetVarietyName = sAssetVarietyName;
                            model.ASSETVARIETY.Add(assetvariety);
                            model.SaveChanges();
                        }
                    }
                    //cloud
                    break;

                case "attribute":

                    break;

                case "timeline":

                    break;

                case "discovery_method":

                    break;

                case "cost_corrective_action":

                    break;

                case "impact":

                    break;

                case "country":
                    //ISOCOUNTRY    COUNTRYISO
                    //http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements.htm

                    // create reader & open file
                    tr = new StreamReader(@"country_names_and_code_element.txt");       //HARDCODED

                    // read the file
                    string scountryline = tr.ReadLine();
                    //Console.WriteLine(verisenum);
                    //Country Name;ISO 3166-1-alpha-2 code
                    //Ignore the first line (headers)
                    scountryline = tr.ReadLine();
                    string[] row;
                    while (scountryline != null && scountryline != "")
                    {
                        row = scountryline.Split(';');
                        string sCountryName          = row[0];
                        string sCountryCode          = row[1];
                        XORCISMModel.COUNTRY country = new COUNTRY();
                        country = model.COUNTRY.FirstOrDefault(o => o.CountryName == sCountryName && o.CountryCode == sCountryCode);
                        if (country == null)
                        {
                            country             = new COUNTRY();
                            country.CountryCode = sCountryCode;
                            country.CountryName = sCountryName;
                            model.COUNTRY.Add(country);
                            model.SaveChanges();
                        }
                        scountryline = tr.ReadLine();
                    }

                    // close the stream
                    tr.Close();



                    jarray = (JsonArray)jobj[loc];
                    for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                    {
                        string scountry = Convert.ToString(jarray[cpt]).ToUpper();
                        //Console.WriteLine(scountry);
                        XORCISMModel.COUNTRY country = new COUNTRY();
                        country = model.COUNTRY.FirstOrDefault(o => o.CountryName == scountry);
                        if (country == null)
                        {
                            country = new COUNTRY();
                            //country.CountryCode = "";
                            country.CountryName = scountry;
                            Console.WriteLine("Country: " + scountry + " not found in the database.");
                            //model.AddToCOUNTRY(country);
                            //model.SaveChanges();
                        }
                    }
                    break;

                case "iso_currency_code":
                    //jarray = (JsonArray)((JsonObject)jobj[loc])[0];
                    //jarray = new JsonArray(loc);
                    jarray = (JsonArray)jobj[loc];
                    for (int cpt = 0; cpt < jarray.Length - 1; cpt++)
                    {
                        string scurrency = Convert.ToString(jarray[cpt]);
                        //Console.WriteLine(scurrency);
                        XORCISMModel.ISOCURRENCY currency = new ISOCURRENCY();
                        currency = model.ISOCURRENCY.FirstOrDefault(o => o.iso_currency_code == scurrency);
                        if (currency == null)
                        {
                            currency = new ISOCURRENCY();
                            currency.iso_currency_code = scurrency;
                            model.ISOCURRENCY.Add(currency);
                            model.SaveChanges();
                        }
                    }
                    break;

                default:
                    break;
                }



                //wid.value = Convert.ToString(((JsonObject)jobj[loc])["name"]);
                //JsonArray coords = (JsonArray)((JsonObject)jobj[loc])["coords"];
                //wid.style.left = Convert.ToString(coords[0]);
                //wid.style.top = Convert.ToString(coords[1]);
            }
            //FREE
            model.Dispose();
            model = null;
        }
Esempio n. 17
0
        public int fAddSocketAddress(string sLayer4_Protocol, string sIPAddress, int iPortValue)
        {
            //TODO: Deprecate or use is_source, is_destination (legacy from NDDM)

            //XORCISMModel.NETWORKCONNECTION NetConnect = new NETWORKCONNECTION();

            #region Layer4
            //Make sure we have the Layer 4 "Transport Layer" in the Database
            int iProtoLayer4ID = XModel.OSILAYER.Where(o => o.OSILayerName == "Transport Layer").Select(o => o.OSILayerID).FirstOrDefault();  //Hardcoded
            if (iProtoLayer4ID <= 0)
            {
                //TODO Create the OSILAYER
            }
            #endregion Layer4
            //Retrieve the Layer4_ProtocolID
            int iLayer4ProtocolID = XModel.PROTOCOL.Where(o => o.ProtocolName == sLayer4_Protocol && o.OSILayerID == iProtoLayer4ID).Select(o => o.ProtocolID).FirstOrDefault();
            if (iLayer4ProtocolID <= 0)
            {
                //TODO ERROR
            }


            //Add the Address IP/Hostname
            #region AddAddress
            XORCISMModel.ADDRESS IPAddress = new ADDRESS();
            int iAddressID = 0;
            try
            {
                //Get the ipv4-addr (CybOX) CategoryID (compatibility with Asset Identification)
                int iAddCat = 0;
                iAddCat = XModel.ADDRESSCATEGORY.Where(o => o.AddressCategoryName == "ipv4-addr").Select(o => o.AddressCategoryID).FirstOrDefault();    //Hardcoded
                IPAddress.AddressCategoryID = iAddCat;

                //Check if already exists. TODO: same organisation? See ASSETADDRESS
                iAddressID = XModel.ADDRESS.Where(o => o.Address_Value == sIPAddress).Select(o => o.AddressID).FirstOrDefault();
                if (iAddressID <= 0)
                {
                    IPAddress.Address_Value = sIPAddress;
                    //TODO check if country... retrievable
                    //IPAddress.is_source = true;
                    //IPAddSource.is_destination=false;
                    XModel.ADDRESS.Add(IPAddress);
                    XModel.SaveChanges();
                    iAddressID = IPAddress.AddressID;
                }
            }
            catch (Exception exAddAddress)
            {
                Console.WriteLine("Exception exAddAddress: " + exAddAddress.Message + " " + exAddAddress.InnerException);
            }
            #endregion AddAddress

            //Add the Port
            #region AddPort
            int iPortID = XModel.PORT.Where(o => o.Port_Value == iPortValue && o.ProtocolID == iProtoLayer4ID).Select(o => o.PortID).FirstOrDefault();
            if (iPortID <= 0)
            {
                try
                {
                    XORCISMModel.PORT PortSource = new PORT();
                    //TODO check if already exists
                    PortSource.ProtocolID = iProtoLayer4ID;
                    PortSource.Port_Value = iPortValue;
                    //PortSource.VocabularyID=;
                    XModel.PORT.Add(PortSource);
                    XModel.SaveChanges();
                    iPortID = PortSource.PortID;
                }
                catch (Exception exAddPort)
                {
                    Console.WriteLine("Exception exAddPort: " + exAddPort.Message + " " + exAddPort.InnerException);
                }
            }
            #endregion AddPort

            //Add the SocketAddress
            int iSocketAddressID = 0;
            iSocketAddressID = XModel.SOCKETADDRESS.Where(o => o.AddressID == iAddressID && o.PortID == iPortID).Select(o => o.SocketAddressID).FirstOrDefault();
            try
            {
                XORCISMModel.SOCKETADDRESS oSockAddress = new SOCKETADDRESS();
                oSockAddress.AddressID   = iAddressID;
                oSockAddress.PortID      = iPortID;
                oSockAddress.CreatedDate = DateTimeOffset.Now;
                oSockAddress.timestamp   = DateTimeOffset.Now;
                oSockAddress.isEncrypted = false;
                XModel.SOCKETADDRESS.Add(oSockAddress);
                XModel.SaveChanges();
                iSocketAddressID = oSockAddress.SocketAddressID;
            }
            catch (Exception exAddSocketAddress)
            {
                Console.WriteLine("Exception exAddSocketAddress: " + exAddSocketAddress.Message + " " + exAddSocketAddress.InnerException);
            }

            return(iSocketAddressID);
        }
Esempio n. 18
0
        public void Run(string target, int jobID, string policy, string strategy)
        {
            m_jobId  = jobID;
            m_target = target;
            Utils.Helper_Trace("XORCISM PROVIDER XINFO", "Entering Run()");
            Utils.Helper_Trace("XORCISM PROVIDER XINFO", string.Format("Target = {0} , JobID = {1} , Policy = {2}", target, jobID, policy));

            //Check if we have an IP address
            //string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.
            //([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
            string pattern = @"^\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?$";       //TODO IPv6...
            //create our Regular Expression object
            Regex check = new Regex(pattern);

            if (check.IsMatch(target.Trim(), 0))
            {
                Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + jobID + " target is an IP address");
            }
            else
            {
                try
                {
                    //It should be a domain name
                    Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + jobID + " target: " + target + " is not an IP address");
                    // = target.Replace("http://", "");
                    //target = target.Replace("https://", "");
                    //target = target.Replace("/", "");
                    if (!target.Contains("://"))
                    {
                        target = "http://" + target;
                    }
                    //TODO? HTTPS
                    target = new Uri(target).Host;
                    Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + jobID + " targetmodified: " + target);
                    if (check.IsMatch(target.Trim(), 0))
                    {
                        Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + jobID + " targetmodified is an IP address");
                    }
                    else
                    {
                        //crackme.cenzic.com
                        string[] sectons = target.Split(new char[] { '.' });

                        if (sectons.Length == 3)
                        {
                            //target = string.Join(".", sectons, 1, 2);
                            whois_info(string.Join(".", sectons, 1, 2));
                            Thread.Sleep(30000);        //Hardcoded
                            search_email_collector(string.Join(".", sectons, 1, 2));
                        }
                        else
                        {
                            whois_info(target);
                            Thread.Sleep(30000);        //Hardcoded
                            search_email_collector(target);
                        }

                        IPHostEntry ipEntry = Dns.GetHostEntry(target);
                        IPAddress[] addr    = ipEntry.AddressList;
                        target = addr[0].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER XINFO", string.Format("JobID:" + jobID + " Dns.GetHostEntry Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message));
                }
            }



            XINFOParser infoParser = null;

            try
            {
                infoParser = new XINFOParser(target, jobID, policy, strategy);
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + jobID + "Exception Parser = " + ex.Message + " " + ex.InnerException);
            }

            string status = XCommon.STATUS.FINISHED.ToString();


            // =================================================
            // Change the status of the job to FINISHED or ERROR
            // =================================================

            if (infoParser.Parse() == false)
            {
                status = XCommon.STATUS.ERROR.ToString();
                Utils.Helper_Trace("XORCISM PROVIDER XINFO", string.Format("Updating job {0} status to ERROR", jobID));
                XCommon.Utils.Helper_SendEmail("*****@*****.**", "XINFO ERROR", "XINFO ERROR for job:" + jobID);
            }
            else
            {
                Utils.Helper_Trace("XORCISM PROVIDER XINFO", string.Format("Updating job {0} status to FINISHED", jobID));
            }
            try
            {
                XORCISMEntities model = new XORCISMEntities();
                var             Q     = from j in model.JOB
                                        where j.JobID == jobID
                                        select j;

                JOB myJob = Q.FirstOrDefault();
                myJob.Status  = status;
                myJob.DateEnd = DateTimeOffset.Now;
                //image
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                myJob.XmlResult = encoding.GetBytes(m_data);
                model.SaveChanges();
                //FREE MEMORY
                model.Dispose();
                infoParser = null;
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + jobID + "Exception UpdateJob = " + ex.Message + " " + ex.InnerException);
            }

            Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + jobID + "Leaving Run()");
        }
Esempio n. 19
0
        public void Run(string target, int jobID, string policy, string Strategy)
        {
            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Entering Run()");

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Target = {0} , JobID = {1} , Policy = {2}", target, jobID, policy));

            Assembly a;

            a = Assembly.GetExecutingAssembly();

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Assembly location = " + a.Location);

            // ==============
            // Launch the job
            // ==============

            #region With VoIPScanner

            const string username = "******";  //TODO Hardcoded
            //string username = ConfigurationManager.AppSettings["VOIPSCANNER_USERNAME"];

            const string key = "1943e197-0zae-4bxc-xd18-12345";
            //string key = ConfigurationManager.AppSettings["VOIPSCANNER_KEY"];
            //     const string baseurl = "https://voipscanner.com/voipscanner/voipscannerxmlrpc/handle";

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("UserName = {0} , Key = {1}", username, key));

            XmlRpcStruct Xtarget = new XmlRpcStruct();

            XORCISMEntities model;
            model = new XORCISMEntities();

            Dictionary <string, object> parameters;

            var q = from x in model.JOB
                    where x.JobID == jobID
                    select x.Parameters;
            try
            {
                byte[] buffer;
                buffer = q.First();

                Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Size of parameters = {0} bytes", buffer.Length));

                MemoryStream ms;
                ms = new MemoryStream(buffer);

                BinaryFormatter bf;
                bf = new BinaryFormatter();

                parameters = (Dictionary <string, object>)bf.Deserialize(ms);
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Error while deserializing parameters : Exception =  {0}", ex.Message));
                return;
            }

            string Sip;
            Sip = (string)parameters["SIP"];

            string Extrange;
            Extrange = (string)parameters["EXTRANGE"];

            try
            {
                Xtarget.Add("hostname", target);
                if (string.IsNullOrEmpty(Sip) == false)
                {
                    Xtarget.Add("sipport", Sip);
                }
                if (string.IsNullOrEmpty(Extrange) == false)
                {
                    Xtarget.Add("extrange", Extrange);
                }
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Exception = {0}", ex.Message));
                // Que faire ?
            }

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Target = {0}", target));

            IToto proxy = XmlRpcProxyGen.Create <IToto>();

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Proxy = {0}", proxy));

            Tracer tracer = new Tracer();
            tracer.Attach(proxy);

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Param Okay");

            string[] res = null;

            try
            {
                res = proxy.scan(username, key, Xtarget);
            }
            catch (XmlRpcFaultException fex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fault Response: {0} {1}", fex.FaultCode, fex.FaultString));
            }

            string scanuid = string.Empty;

            if (res[0] == "Success")
            {
                Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Success 1");
                scanuid = res[1];
            }
            else
            {
                Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fail 1: {0}", res[0]));
            }

            // ===================
            // Wait for completion
            // ===================

            XmlRpcStruct scanparams = new XmlRpcStruct();
            scanparams.Add("scanuid", scanuid);
            scanparams.Add("pretty", true);
            scanparams.Add("documented", true);
            // target.Add("upperBound", 139);

            bool   finished = false;
            string xml      = string.Empty;
            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Waiting 45 seconds...");

            Thread.Sleep(45000);    //Hardcoded

            while (finished == false)
            {
                try
                {
                    Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Trying to get results");
                    res = proxy.getresultsxml(username, key, scanparams);
                }
                catch (XmlRpcFaultException fex)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fault Response: {0} {1}", fex.FaultCode, fex.FaultString));
                }

                if (res[0] == "Success")
                {
                    Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Success 2");
                    xml = res[1];
                    Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "res=" + xml);
                    finished = true;
                }
                else
                {
                    //Wait
                    Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fail 2: {0}", res[0]));
                    //    return null;
                    Thread.Sleep(30000);
                }
            }

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Results successfully downloaded");

            XmlDocument doc;
            doc = new XmlDocument();

            try
            {
                //TODO XML Validation
                doc.LoadXml(xml);
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("LoadXmlException = {0}", ex.Message));
                // Que faire ?
            }
            #endregion


            #region Without VoIPScanner

            /*
             * XmlDocument doc = new XmlDocument();
             * doc.Load(@"c:\VoIPScanner.xml");
             */
            #endregion


            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Parsing the results");

            VoIPScannerParser parser = new VoIPScannerParser(doc, jobID);
            parser.parse();

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Using svmap.py from sipvicious");
            string address = "111.222.333.444"; //TODO Hardcoded
            //string username = "******";
            string password = "******";
            string prompt   = "root";

            SshShell sshShell;
            sshShell = new SshShell(address, "root", password);
            sshShell.RemoveTerminalEmulationCharacters = true;

            Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} Connecting to SIPVICIOUS server at {1}", jobID, address));

            try
            {
                sshShell.Connect(22);
                //sshShell.Expect(prompt+"~#");
                sshShell.Expect(prompt);// + "~$");
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} ConnectingERROR to SIPVICIOUS server at {1} : " + ex.Message + " " + ex.InnerException, jobID, address));
            }

            string cmd1 = "cd /home/root/tools/sipvicious/"; //Hardcoded
            sshShell.WriteLine(cmd1);
            Thread.Sleep(1000);                              //Hardcoded
            string stdout = sshShell.Expect(prompt);
            Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} START DUMP STDOUT01", jobID));
            Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", stdout);

            Thread.Sleep(1000);
            sshShell.WriteLine("./svmap.py " + target); //Hardcoded
            Thread.Sleep(30000);                        //Hardcoded
            stdout = sshShell.Expect(prompt);
            Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} START DUMP STDOUT02", jobID));
            Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", stdout);

            //TODO

            /*
             *  INFORMATION myInformation = new INFORMATION();
             *  //VulnerabilityFound vulnerabilityFound = new VulnerabilityFound();
             *  myInformation.EndPointID = theEndPointID;
             *  myInformation.JobID = m_jobId;
             *  //vulnerabilityFound.ListItem = Helper_GetCVE(n);
             *  //vulnerabilityFound.ListReference = Helper_GetREFERENCE(n);  //TODO: Helper_GetCVE and Helper_GetREFERENCE could be mixed for only 1 parsing
             *  //vulnerabilityFound.InnerXml = n.OuterXml;
             *
             *  myInformation.Description = HelperGetChildInnerText(n, "DIAGNOSIS");
             *  myInformation.Solution = HelperGetChildInnerText(n, "SOLUTION");
             *  myInformation.Severity = n.Attributes["severity"].Value;
             *  myInformation.Consequence = HelperGetChildInnerText(n, "CONSEQUENCE");
             *  myInformation.Result = HelperGetChildInnerText(n, "RESULT");
             *  myInformation.ModifiedDate = DateTime.Parse(HelperGetChildInnerText(n, "LAST_UPDATE"));
             *  if (HelperGetChildInnerText(n, "PCI_FLAG") == "1")
             *  {
             *      myInformation.PCI_FLAG = true;
             *  }
             *  myInformation.Title = "";
             *
             *  model.AddToINFORMATION(myInformation);
             *  model.SaveChanges();
             */

            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Update job status to FINISHED");

            var j = from xJob in model.JOB
                    where xJob.JobID == jobID
                    select xJob;

            JOB J = j.FirstOrDefault();
            J.Status = XCommon.STATUS.FINISHED.ToString();

            model.SaveChanges();

            //FREE MEMORY
            parser = null;
            J      = null;
            model.Dispose();


            Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Leaving Run()"));
        }
Esempio n. 20
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            //NOTE: OUTDATED Project. See Import_all

            string filename;

            //http://www.saintcorporation.com/xml/exploits.xml

            try
            {
                WebClient wc = new WebClient();
                wc.DownloadFile("http://www.saintcorporation.com/xml/exploits.xml", "C:/nvdcve/exploits.xml");  //HARDCODED
                //
                wc.Dispose();
                //MessageBox.Show("Download is completed", "info", MessageBoxButtons.OK, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while downloading exploits.xml\n" + ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
            }

            filename = @"C:\nvdcve\exploits.xml";   //HARDCODED

            XmlDocument doc = new XmlDocument();

            doc.Load(filename);

            string  query = "/xml/body/exploits";
            XmlNode report;

            report = doc.SelectSingleNode(query);

            XORCISMEntities        model      = new XORCISMEntities();
            XVULNERABILITYEntities vuln_model = new XVULNERABILITYEntities();

            foreach (XmlNode n in report.ChildNodes)
            {
                //if (n.Name.ToUpper() == "exploit".ToUpper() && n.ChildNodes != null && n.ChildNodes.Count > 0)
                //{
                EXPLOIT sploit  = new EXPLOIT();
                string  myRefID = n.Attributes["id"].InnerText;
                sploit.ExploitRefID       = myRefID;
                sploit.ExploitName        = n.Attributes["id"].InnerText;
                sploit.ExploitReferential = "saint";
                sploit.ExploitDescription = HelperGetChildInnerText(n, "description");
                //TODO
                //sploit.saint_id = HelperGetChildInnerText(n, "saint_id");
                sploit.ExploitType = HelperGetChildInnerText(n, "type");
                //Search the VulnerabilityID
                string myCVE  = HelperGetChildInnerText(n, "cve");
                int    vulnID = 0;
                if (myCVE != "")
                {
                    var syn = from S in vuln_model.VULNERABILITY
                              where S.VULReferential.Equals("cve") &&
                              S.VULReferentialID.Equals(myCVE)
                              select S;
                    if (syn.Count() != 0)
                    {
                        vulnID = syn.ToList().First().VulnerabilityID;
                        //                        MessageBox.Show("VulnerabilityID of " + myCVE + " is:" + vulnID);
                    }
                    else
                    {
                        //MessageBox.Show("Import_saint_exploits CVE not found! " + myCVE);
                        //CANDIDATE
                        VULNERABILITY canCVE = new VULNERABILITY();
                        canCVE.VULReferential   = "cve";
                        canCVE.VULReferentialID = myCVE;
                        canCVE.VULDescription   = "CANDIDATE";
                        vuln_model.VULNERABILITY.Add(canCVE);
                        vuln_model.SaveChanges();
                        vulnID = canCVE.VulnerabilityID;

                        //    return;
                    }
                }

                //Check if the exploit already exists in the database
                var syna = from S in model.EXPLOIT
                           where S.ExploitReferential.Equals("saint") &&
                           S.ExploitRefID.Equals(myRefID)
                           select S;
                if (syna.Count() == 0)
                {
                    model.EXPLOIT.Add(sploit);
                }
                else
                {
                    sploit.ExploitID = syna.ToList().First().ExploitID;
                }
                try
                {
                    model.SaveChanges();
                }
                catch (FormatException ex)
                {
                    MessageBox.Show("FormatException AddToEXPLOIT : " + ex);
                    return;
                }

                if (vulnID != 0)
                {
                    //Check if EXPLOITFORVULNERABILITY already exists in the database
                    var synj = from S in model.EXPLOITFORVULNERABILITY
                               where S.VulnerabilityID.Equals(vulnID) &&
                               S.ExploitID.Equals(sploit.ExploitID)
                               select S;
                    if (synj.Count() == 0)
                    {
                        EXPLOITFORVULNERABILITY sploitvuln = new EXPLOITFORVULNERABILITY();
                        sploitvuln.VulnerabilityID = vulnID;
                        sploitvuln.ExploitID       = sploit.ExploitID;
                        try
                        {
                            model.EXPLOITFORVULNERABILITY.Add(sploitvuln);
                            model.SaveChanges();
                        }
                        catch (FormatException ex)
                        {
                            MessageBox.Show("AddToEXPLOITFORVULNERABILITY : " + ex);
                        }
                    }
                }

                //****************************************************************
                //  OSVDB
                string myOSVDB = HelperGetChildInnerText(n, "osvdb");
                if (myOSVDB != "")
                {
                    //Check if the OSVDB reference already exists in the database
                    int osvdbID = 0;
                    var syn2    = from S in model.REFERENCE
                                  where S.Source.Equals("OSVDB") &&
                                  S.ReferenceTitle.Equals(myOSVDB)
                                  select S;

                    REFERENCE RefJA = new REFERENCE();
                    if (syn2.Count() != 0)
                    {
                        //UPDATE
                        osvdbID            = syn2.ToList().First().ReferenceID;
                        RefJA.ReferenceID  = osvdbID;
                        RefJA.ReferenceURL = "http://osvdb.org/" + myOSVDB;
                        model.SaveChanges();
                    }
                    else
                    {
                        //Add the OSVDB Reference
                        RefJA.Source         = "OSVDB";
                        RefJA.ReferenceTitle = myOSVDB;
                        RefJA.ReferenceURL   = "http://osvdb.org/" + myOSVDB;
                        model.REFERENCE.Add(RefJA);
                        model.SaveChanges();
                        osvdbID = RefJA.ReferenceID;
                    }

                    //Check if the EXPLOITFORREFERENCE already exists in the database
                    var syn3 = from S in model.EXPLOITFORREFERENCE
                               where S.ExploitID.Equals(sploit.ExploitID) &&
                               S.ReferenceID.Equals(osvdbID)
                               select S;
                    if (syn3.Count() == 0)
                    {
                        EXPLOITFORREFERENCE sploitref = new EXPLOITFORREFERENCE();
                        sploitref.ExploitID   = sploit.ExploitID;
                        sploitref.ReferenceID = osvdbID;
                        model.EXPLOITFORREFERENCE.Add(sploitref);
                        model.SaveChanges();
                    }
                }

                //****************************************************************
                //  BID
                string myBID = HelperGetChildInnerText(n, "bid");
                if (myBID != "")
                {
                    //Check if the BID reference already exists in the database
                    int bidID = 0;
                    var syn2  = from S in model.REFERENCE
                                where S.Source.Equals("BID") &&
                                S.ReferenceTitle.Equals(myBID)
                                select S;
                    if (syn2.Count() != 0)
                    {
                        bidID = syn2.ToList().First().ReferenceID;
                    }
                    else
                    {
                        //Add the OSVDB Reference
                        REFERENCE RefJA = new REFERENCE();
                        RefJA.Source         = "BID";
                        RefJA.ReferenceTitle = myBID;
                        RefJA.ReferenceURL   = "http://securityfocus.com/bid/" + myBID;
                        model.REFERENCE.Add(RefJA);
                        model.SaveChanges();
                        bidID = RefJA.ReferenceID;
                    }

                    //Check if the EXPLOITFORREFERENCE already exists in the database
                    var syn3 = from S in model.EXPLOITFORREFERENCE
                               where S.ExploitID.Equals(sploit.ExploitID) &&
                               S.ReferenceID.Equals(bidID)
                               select S;
                    if (syn3.Count() == 0)
                    {
                        EXPLOITFORREFERENCE sploitref = new EXPLOITFORREFERENCE();
                        sploitref.ExploitID   = sploit.ExploitID;
                        sploitref.ReferenceID = bidID;
                        model.EXPLOITFORREFERENCE.Add(sploitref);
                        model.SaveChanges();
                    }
                }

                //}
            }
            MessageBox.Show("FINISHED MISTER_X");
        }
Esempio n. 21
0
        static void Main(string[] args)
        {
            //https://www.owasp.org/index.php/OWASP_Dependency_Check

            Excel.Application xlApp;
            Excel.Workbook    xlWorkBook;

            object misValue = System.Reflection.Missing.Value;

            xlApp      = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int iColumnIndex = 1;

            XORCISMEntities model = new XORCISMEntities();

            //https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
            model.Configuration.AutoDetectChangesEnabled = false;
            model.Configuration.ValidateOnSaveEnabled    = false;

            int    iVocabularyOWASPdepcheckID = 0;       // 11;
            string sOWASPdepcheckVersion      = "1.3.1"; //HARDCODED TODO

            #region vocabularyowaspdepcheck
            try
            {
                iVocabularyOWASPdepcheckID = model.VOCABULARY.Where(o => o.VocabularyName == "OWASP dependency-check" && o.VocabularyVersion == sOWASPdepcheckVersion).Select(o => o.VocabularyID).FirstOrDefault();
            }
            catch (Exception ex)
            {
            }
            if (iVocabularyOWASPdepcheckID <= 0)
            {
                try
                {
                    VOCABULARY oVocabulary = new VOCABULARY();
                    oVocabulary.CreatedDate       = DateTimeOffset.Now;
                    oVocabulary.VocabularyName    = "OWASP dependency-check"; //HARDCODED
                    oVocabulary.VocabularyVersion = sOWASPdepcheckVersion;
                    model.VOCABULARY.Add(oVocabulary);
                    model.SaveChanges();
                    iVocabularyOWASPdepcheckID = oVocabulary.VocabularyID;
                    Console.WriteLine("DEBUG iVocabularyOWASPdepcheckID=" + iVocabularyOWASPdepcheckID);
                }
                catch (Exception ex)
                {
                }
            }
            #endregion vocabularyowaspdepcheck


            XmlDocument doc;
            doc = new XmlDocument();

            doc.Load(@"dependency-check-report.xml");  //HARDCODED
            //TODO security: Validate XSD

            //xmlvalidator xsd=new xmlvalidator()


            //Global variables
            string sTemp               = "";
            string sProjectName        = "";
            string sReportDate         = "";
            string sDependencyFileName = "";
            string sDependencyFilePath = "";
            string sDependencyMD5      = "";
            string sDependencySHA1     = "";


            XmlNodeList nodes1;
            nodes1 = doc.DocumentElement.SelectNodes("/");
            Console.WriteLine(nodes1.Count);
            #region parsexml
            foreach (XmlNode node in nodes1)
            {
                foreach (XmlNode node2 in node)
                {
                    //Console.WriteLine(node2.Name);
                    if (node2.Name == "analysis")
                    {
                        foreach (XmlNode node3 in node2)
                        {
                            try
                            {
                                sTemp = node3.Name.Trim();
                                Console.WriteLine("DEBUG " + sTemp);
                                //scanInfo
                                //projectInfo
                                //dependencies
                                switch (sTemp)
                                {
                                case "scanInfo":
                                    //TODO
                                    //engineVersion
                                    //dataSource
                                    //name
                                    //timestamp
                                    break;

                                case "projectInfo":
                                    //TODO
                                    //name
                                    //reportDate
                                    //credits
                                    try
                                    {
                                        //sProjectName = node3.SelectSingleNode("name").InnerText;
                                        foreach (XmlNode nodeprojectInfo in node3)
                                        {
                                            if (nodeprojectInfo.Name.Trim() == "name")
                                            {
                                                sProjectName = nodeprojectInfo.InnerText;
                                            }
                                            else
                                            {
                                                if (nodeprojectInfo.Name.Trim() == "reportDate")
                                                {
                                                    sReportDate = nodeprojectInfo.InnerText;
                                                }
                                            }
                                        }
                                        Console.WriteLine("DEBUG sProjectName=" + sProjectName);
                                        Console.WriteLine("DEBUG sReportDate=" + sReportDate);
                                    }
                                    catch (Exception exprojectInfo)
                                    {
                                        Console.WriteLine("Exception exprojectInfo: " + exprojectInfo.Message + " " + exprojectInfo.InnerException);
                                    }
                                    break;

                                case "dependencies":
                                    foreach (XmlNode nodeDependency in node3)       //dependency
                                    {
                                        sDependencyFileName = "";
                                        sDependencyFilePath = "";
                                        sDependencyMD5      = "";
                                        sDependencySHA1     = "";
                                        //sDependencyFileName = nodeDependency.SelectSingleNode("fileName").InnerText;
                                        foreach (XmlNode nodeDependencyInfo in nodeDependency)
                                        {
                                            sTemp = nodeDependencyInfo.Name.Trim();
                                            switch (sTemp)
                                            {
                                            case "fileName":
                                                sDependencyFileName = nodeDependencyInfo.InnerText;
                                                break;

                                            case "filePath":
                                                sDependencyFilePath = nodeDependencyInfo.InnerText;
                                                break;

                                            case "md5":
                                                sDependencyMD5 = nodeDependencyInfo.InnerText;
                                                break;

                                            case "sha1":
                                                sDependencySHA1 = nodeDependencyInfo.InnerText;
                                                break;

                                            default:
                                                //TODO
                                                Console.WriteLine("ERROR1 " + sTemp + " not managed.");
                                                //relatedDependencies
                                                break;
                                            }

                                            /*
                                             * Console.WriteLine("DEBUG sDependencyFileName=" + sDependencyFileName);
                                             * Console.WriteLine("DEBUG sDependencyFilePath=" + sDependencyFilePath);
                                             * Console.WriteLine("DEBUG sDependencyMD5=" + sDependencyMD5);
                                             * Console.WriteLine("DEBUG sDependencySHA1=" + sDependencySHA1);
                                             */
                                        }

                                        xlWorkSheet.Cells[iRowIndex, 1] = sDependencyFileName;
                                        xlWorkSheet.Cells[iRowIndex, 2] = sDependencyFilePath;
                                        xlWorkSheet.Cells[iRowIndex, 3] = sDependencyMD5;
                                        xlWorkSheet.Cells[iRowIndex, 4] = sDependencySHA1;
                                        iRowIndex++;
                                    }
                                    break;

                                default:
                                    Console.WriteLine("ERROR2 " + node3.Name + " not managed.");
                                    //TODO
                                    //evidenceCollected
                                    //identifiers
                                    //vulnerabilities
                                    break;
                                }
                            }
                            catch (Exception exnode3Name)
                            {
                                Console.WriteLine("Exception exnode3Name: " + exnode3Name.Message + " " + exnode3Name.InnerException);
                            }
                        }
                    }
                }
            }
            #endregion parsexml

            //*********************************************************
            string sCurrentPath = Directory.GetCurrentDirectory();
            //HARDCODED
            xlWorkBook.SaveAs(sCurrentPath + @"\" + sProjectName + "-dependencies.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            Console.WriteLine(sProjectName + "-dependencies.xls created.");
        }
Esempio n. 22
0
        /// <summary>
        /// Copyright (C) 2015-2016 Jerome Athias - frhack.org
        /// *** BETA VERSION ***
        /// Parser for National Checklist Program (NCP) Checklists feed XML file and import into an XORCISM database
        /// This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
        ///
        /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
        ///
        /// You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
        /// </summary>
        ///
        static void Main(string[] args)
        {
            //https://nvd.nist.gov/download.cfm#CVE_FEED
            //National Checklist Program (NCP) Checklists

            XORCISMEntities model = new XORCISMEntities();

            //VOCABULARIES

            int iVocabularyNCPID = 0;

            #region vocabularyncp
            try
            {
                //Hardcoded
                iVocabularyNCPID = model.VOCABULARY.Where(o => o.VocabularyName == "NCP").Select(o => o.VocabularyID).FirstOrDefault();
            }
            catch (Exception ex)
            {
            }
            if (iVocabularyNCPID <= 0)
            {
                XORCISMModel.VOCABULARY oVocabulary = new XORCISMModel.VOCABULARY();
                oVocabulary.CreatedDate    = DateTimeOffset.Now;
                oVocabulary.VocabularyName = "NCP"; //Hardcoded
                model.VOCABULARY.Add(oVocabulary);
                model.SaveChanges();
                iVocabularyNCPID = oVocabulary.VocabularyID;
                Console.WriteLine("DEBUG iVocabularyNCPID=" + iVocabularyNCPID);
            }
            #endregion vocabularyncp

            //TODO: download if needed (if updated)
            string filepath = "checklist-0.1-feed.xml"; //Hardcoded

            Console.WriteLine("DEBUG " + DateTimeOffset.Now);
            XmlDocument docXML = new XmlDocument();
            //TODO: Security controls/checks
            //TODO: XSD validation
            //TODO: ...
            docXML.Load(filepath);

            XmlNodeList nodes;
            nodes = docXML.SelectNodes("/ncp");

            foreach (XmlNode nodeEntry in docXML.DocumentElement.ChildNodes)
            {
                //<entry ncp-checklist-id="7">
                string    sChecklistVocabularyID = "";
                CHECKLIST oChecklist             = null;
                int       iChecklistID           = 0;

                try
                {
                    sChecklistVocabularyID = nodeEntry.Attributes["ncp-checklist-id"].InnerText;
                }
                catch (Exception exsChecklistVocabularyID)
                {
                    Console.WriteLine("Exception: exiChecklistVocabularyID");
                }
                foreach (XmlNode nodeEntryInfo in nodeEntry.ChildNodes)
                {
                    switch (nodeEntryInfo.Name)
                    {
                    case "ncp:checklist-details":
                        //int iChecklistID = 0;
                        foreach (XmlNode nodeChecklistDetail in nodeEntryInfo.ChildNodes)
                        {
                            switch (nodeChecklistDetail.Name)
                            {
                            case "ncp:title":
                                string sChecklistName    = "";
                                string sChecklistVersion = "";
                                foreach (XmlNode nodeTitle in nodeChecklistDetail.ChildNodes)
                                {
                                    switch (nodeTitle.Name)
                                    {
                                    case "ncp:checklist-name":
                                        sChecklistName = nodeTitle.InnerText;
                                        break;

                                    case "ncp:version":
                                        sChecklistVersion = nodeTitle.InnerText;
                                        break;

                                    default:
                                        Console.WriteLine("ERROR Missing code for nodeTitle.Name=" + nodeTitle.Name);
                                        break;
                                    }
                                }
                                #region checklist

                                try
                                {
                                    //TODO? add ChecklistVersion
                                    oChecklist = model.CHECKLIST.Where(o => o.Title == sChecklistName).FirstOrDefault();
                                }
                                catch (Exception exiChecklistID)
                                {
                                }
                                if (oChecklist != null)
                                {
                                    iChecklistID = oChecklist.ChecklistID;
                                    //Update CHECKLIST
                                    try
                                    {
                                        oChecklist.ChecklistVersion      = sChecklistVersion;
                                        oChecklist.ChecklistVocabularyID = sChecklistVocabularyID;
                                        oChecklist.timestamp             = DateTimeOffset.Now;
                                        model.SaveChanges();
                                    }
                                    catch (Exception exUpdateCHECKLIST)
                                    {
                                        Console.WriteLine("Exception: exUpdateCHECKLIST " + exUpdateCHECKLIST.Message + " " + exUpdateCHECKLIST.InnerException);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("DEBUG Adding CHECKLIST");
                                    //NOTE: Model comes from OCIL   https://scap.nist.gov/specifications/ocil/
                                    try
                                    {
                                        oChecklist                  = new CHECKLIST();
                                        oChecklist.CreatedDate      = DateTimeOffset.Now;
                                        oChecklist.Title            = sChecklistName;
                                        oChecklist.ChecklistVersion = sChecklistVersion;
                                        //oChecklist.ChecklistCategoryID= //TODO
                                        //oChecklistOrganisationID  //Updated later
                                        oChecklist.ChecklistVocabularyID = sChecklistVocabularyID;
                                        oChecklist.VocabularyID          = iVocabularyNCPID;
                                        oChecklist.timestamp             = DateTimeOffset.Now;
                                        model.CHECKLIST.Add(oChecklist);
                                        model.SaveChanges();
                                        iChecklistID = oChecklist.ChecklistID;
                                    }
                                    catch (Exception exAddCHECKLIST)
                                    {
                                        Console.WriteLine("Exception: exAddCHECKLIST " + exAddCHECKLIST.Message + " " + exAddCHECKLIST.InnerException);
                                    }
                                }
                                #endregion checklist

                                //TODO  CHECKLISTTAG    sChecklistName

                                break;

                            case "ncp:authority":
                                #region authority
                                string sOrganisationName        = "";
                                string sOrganisationReference   = "";       //TODO
                                string sOrganisationDescription = "";
                                int    iRoleID = 0;
                                foreach (XmlNode nodeAuthorityDetail in nodeChecklistDetail.ChildNodes)
                                {
                                    switch (nodeAuthorityDetail.Name)
                                    {
                                    case "ncp:organization":
                                        //<ncp:organization system-id="http://www.disa.mil/" name="Defense Information Systems Agency">
                                        sOrganisationName      = nodeAuthorityDetail.Attributes["name"].InnerText;
                                        sOrganisationReference = nodeAuthorityDetail.Attributes["system-id"].InnerText;
                                        Console.WriteLine("DEBUG sOrganisationReference=" + sOrganisationReference);
                                        foreach (XmlNode nodeOrganizationDetail in nodeAuthorityDetail.ChildNodes)
                                        {
                                            switch (nodeOrganizationDetail.Name)
                                            {
                                            case "ncp:description":
                                                //Not provided.
                                                sOrganisationDescription = nodeOrganizationDetail.InnerText;
                                                break;

                                            default:
                                                Console.WriteLine("ERROR Missing code for nodeOrganizationDetail.Name=" + nodeOrganizationDetail.Name);
                                                break;
                                            }
                                        }
                                        break;

                                    case "ncp:type":
                                        //GOVERNMENTAL_AUTHORITY
                                        //Using the table ROLE
                                        #region authorityrole
                                        string sAuthority = nodeAuthorityDetail.InnerText;

                                        try
                                        {
                                            iRoleID = model.ROLE.Where(o => o.RoleName == sAuthority).FirstOrDefault().RoleID;
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                        if (iRoleID <= 0)
                                        {
                                            Console.WriteLine("Adding ROLE/AUTHORITY");
                                            try
                                            {
                                                ROLE oRole = new ROLE();
                                                oRole.CreatedDate = DateTimeOffset.Now;
                                                oRole.RoleName    = sAuthority;
                                                //oRole.RoleDescription //TODO  See https://web.nvd.nist.gov/view/ncp/repository/glossary
                                                oRole.VocabularyID = iVocabularyNCPID;
                                                oRole.timestamp    = DateTimeOffset.Now;
                                                model.ROLE.Add(oRole);
                                                model.SaveChanges();
                                                iRoleID = oRole.RoleID;
                                            }
                                            catch (Exception exAddRole)
                                            {
                                                Console.WriteLine("Exception: exAddRole " + exAddRole.Message + " " + exAddRole.InnerException);
                                            }
                                        }
                                        else
                                        {
                                            //Update ROLE
                                        }
                                        #endregion authorityrole
                                        break;

                                    default:
                                        Console.WriteLine("ERROR Missing code for nodeAuthorityDetail.Name=" + nodeAuthorityDetail.Name);
                                        break;
                                    }
                                }

                                int iOrganisationID = 0;
                                #region organisation
                                try
                                {
                                    iOrganisationID = model.ORGANISATION.Where(o => o.OrganisationName == sOrganisationName || o.OrganisationKnownAs == sOrganisationName).FirstOrDefault().OrganisationID;
                                }
                                catch (Exception exiOrganisationID)
                                {
                                }
                                if (iOrganisationID <= 0)
                                {
                                    Console.WriteLine("DEBUG Adding ORGANISATION");
                                    try
                                    {
                                        ORGANISATION oOrganisation = new ORGANISATION();
                                        oOrganisation.CreatedDate             = DateTimeOffset.Now;
                                        oOrganisation.OrganisationName        = sOrganisationName;
                                        oOrganisation.OrganisationDescription = sOrganisationDescription;
                                        oOrganisation.VocabularyID            = iVocabularyNCPID;
                                        oOrganisation.timestamp = DateTimeOffset.Now;
                                        model.ORGANISATION.Add(oOrganisation);
                                        model.SaveChanges();
                                        iOrganisationID = oOrganisation.OrganisationID;
                                    }
                                    catch (Exception exAddORGANISATION)
                                    {
                                        Console.WriteLine("Exception: exAddORGANISATION " + exAddORGANISATION.Message + " " + exAddORGANISATION.InnerException);
                                    }
                                }
                                else
                                {
                                    //Update ORGANISATION
                                    //TODO i.e. Description
                                }
                                #endregion organisation

                                try
                                {
                                    oChecklist.OrganisationID = iOrganisationID;
                                    oChecklist.timestamp      = DateTimeOffset.Now;
                                    model.SaveChanges();
                                }
                                catch (Exception exChecklistOrganisationID)
                                {
                                    Console.WriteLine("Exception: exChecklistOrganisationID " + exChecklistOrganisationID.Message + " " + exChecklistOrganisationID.InnerException);
                                }

                                //TODO
                                //<ncp:organization system-id="http://www.disa.mil/" name="Defense Information Systems Agency">
                                //ORGANISATIONREFERENCE or ORGANISATIONDOMAINNAME

                                #region  CHECKLISTAUTHORITY
                                int iChecklistAuthorityID = 0;
                                //TODO? VocabularyID
                                try
                                {
                                    iChecklistAuthorityID = model.CHECKLISTAUTHORITY.Where(o => o.ChecklistID == iChecklistID && o.RoleID == iRoleID).FirstOrDefault().ChecklistAuthorityID;
                                }
                                catch (Exception ex)
                                {
                                }
                                if (iChecklistAuthorityID <= 0)
                                {
                                    Console.WriteLine("DEBUG Adding CHECKLISTAUTHORITY");
                                    try
                                    {
                                        CHECKLISTAUTHORITY oChecklistAuthority = new CHECKLISTAUTHORITY();
                                        oChecklistAuthority.CreatedDate    = DateTimeOffset.Now;
                                        oChecklistAuthority.ChecklistID    = iChecklistID;
                                        oChecklistAuthority.OrganisationID = iOrganisationID;
                                        oChecklistAuthority.RoleID         = iRoleID;
                                        oChecklistAuthority.VocabularyID   = iVocabularyNCPID;
                                        oChecklistAuthority.timestamp      = DateTimeOffset.Now;
                                        model.CHECKLISTAUTHORITY.Add(oChecklistAuthority);
                                        model.SaveChanges();
                                        iChecklistAuthorityID = oChecklistAuthority.ChecklistAuthorityID;
                                    }
                                    catch (Exception exAddChecklistAuthority)
                                    {
                                        Console.WriteLine("Exception: exAddChecklistAuthority " + exAddChecklistAuthority.Message + " " + exAddChecklistAuthority.InnerException);
                                    }
                                }
                                else
                                {
                                    //Update CHECKLISTAUTHORITY
                                }
                                #endregion  CHECKLISTAUTHORITY
                                #endregion authority
                                break;

                            case "ncp:resource":
                                #region resource
                                string sReferenceURL      = "";
                                int    iReferenceAuthorID = 0;
                                string sReferenceTitle    = "";
                                foreach (XmlNode nodeResource in nodeChecklistDetail.ChildNodes)
                                {
                                    switch (nodeResource.Name)
                                    {
                                    case "ncp:reference":
                                        try
                                        {
                                            sReferenceURL = nodeResource.Attributes["href"].InnerText;
                                        }
                                        catch (Exception)
                                        {
                                        }
                                        break;

                                    case "ncp:author":
                                        //<ncp:author system-id="http://www.disa.mil/" name="Defense Information Systems Agency">
                                        //TODO
                                        //iReferenceAuthorID
                                        break;

                                    case "ncp:title":
                                        //.NET Framework Security Checklist
                                        sReferenceTitle = nodeResource.InnerText;
                                        break;

                                    default:
                                        //ncp:sha-1
                                        //ncp:sha-256
                                        //<ncp:type>Prose</ncp:type>
                                        Console.WriteLine("ERROR Missing code for nodeResource.Name=" + nodeResource.Name);
                                        break;
                                    }
                                }

                                //TODO Add REFERENCE    REFERENCEHASHVALUE  CHECKLISTREFERENCE

                                #endregion resource
                                break;

                            case "ncp:target-product":
                                #region targetproduct
                                //<ncp:target-product fips-140-2-compliance-flag="true">
                                string sProductName     = string.Empty;
                                string sCPEName         = string.Empty;
                                string sProductCategory = string.Empty;
                                foreach (XmlNode nodeProduct in nodeChecklistDetail.ChildNodes)
                                {
                                    switch (nodeProduct.Name)
                                    {
                                    case "ncp:name":
                                        sProductName = nodeProduct.InnerText;
                                        break;

                                    case "ncp:cpe-name":
                                        sCPEName = nodeProduct.InnerText;
                                        break;

                                    case "ncp:product-category":
                                        sProductCategory = nodeProduct.InnerText;
                                        break;

                                    default:
                                        Console.WriteLine("ERROR Missing code for nodeProduct " + nodeProduct.Name);
                                        break;
                                    }
                                }
                                Console.WriteLine("DEBUG sProductName=" + sProductName);         //Microsoft .NET Framework 1.0
                                Console.WriteLine("DEBUG sCPEName=" + sCPEName);                 //Microsoft .NET Framework 1.0
                                Console.WriteLine("DEBUG sProductCategory=" + sProductCategory); //
                                //Operating System  //TODO? OS


                                int iCategoryID = 0;
                                #region category
                                //TODO? + VocabularyID
                                try
                                {
                                    iCategoryID = model.CATEGORY.Where(o => o.CategoryName == sProductCategory).FirstOrDefault().CategoryID;
                                }
                                catch (Exception exiCategoryID)
                                {
                                }
                                if (iCategoryID <= 0)
                                {
                                    Console.WriteLine("DEBUG Adding CATEGORY");
                                    try
                                    {
                                        CATEGORY oCategory = new CATEGORY();
                                        oCategory.CreatedDate  = DateTimeOffset.Now;
                                        oCategory.CategoryName = sProductCategory;
                                        oCategory.VocabularyID = iVocabularyNCPID;
                                        oCategory.timestamp    = DateTimeOffset.Now;
                                        model.CATEGORY.Add(oCategory);
                                        model.SaveChanges();
                                        iCategoryID = oCategory.CategoryID;
                                    }
                                    catch (Exception exAddCategory)
                                    {
                                        Console.WriteLine("Exception: exAddCategory " + exAddCategory.Message + " " + exAddCategory.InnerException);
                                    }
                                }
                                #endregion category

                                int iProductCategoryID = 0;
                                #region productcategory
                                //TODO? + VocabularyID
                                try
                                {
                                    iProductCategoryID = model.PRODUCTCATEGORY.Where(o => o.ProductCategoryName == sProductCategory).FirstOrDefault().ProductCategoryID;
                                }
                                catch (Exception exiProductCategoryID)
                                {
                                }
                                if (iProductCategoryID <= 0)
                                {
                                    Console.WriteLine("DEBUG Adding PRODUCTCATEGORY");
                                    try
                                    {
                                        PRODUCTCATEGORY oProductCategory = new PRODUCTCATEGORY();
                                        oProductCategory.CreatedDate         = DateTimeOffset.Now;
                                        oProductCategory.ProductCategoryName = sProductCategory;
                                        oProductCategory.CategoryID          = iCategoryID;
                                        //TODO
                                        //oProductCategory.OrganisationID   //Defense Information Systems Agency
                                        oProductCategory.VocabularyID = iVocabularyNCPID;
                                        oProductCategory.timestamp    = DateTimeOffset.Now;
                                        model.PRODUCTCATEGORY.Add(oProductCategory);
                                        model.SaveChanges();
                                        iProductCategoryID = oProductCategory.ProductCategoryID;
                                    }
                                    catch (Exception exAddProductCategory)
                                    {
                                        Console.WriteLine("Exception: exAddProductCategory " + exAddProductCategory.Message + " " + exAddProductCategory.InnerException);
                                    }
                                }
                                #endregion productcategory

                                int iProductID = 0;
                                #region product

                                //Note: It seems that ProductNames are the 'same' in NCP and OVAL :-)
                                try
                                {
                                    iProductID = model.PRODUCT.Where(o => o.ProductName == sProductName).FirstOrDefault().ProductID;
                                }
                                catch (Exception exiProductID)
                                {
                                }
                                if (iProductID <= 0)
                                {
                                    Console.WriteLine("DEBUG Adding PRODUCT");
                                    try
                                    {
                                        PRODUCT oProduct = new PRODUCT();
                                        oProduct.ProductName = sProductName;
                                        //TODO? Vendor...
                                        string sProductVendor = "";
                                        #region productvendor
                                        //Hardcoded
                                        if (sProductName.Contains("Microsoft"))
                                        {
                                            sProductVendor = "Microsoft";
                                        }
                                        if (sProductName.Contains("Windows"))
                                        {
                                            sProductVendor = "Microsoft";
                                        }
                                        if (sProductName.Contains("VBScript"))
                                        {
                                            sProductVendor = "Microsoft";
                                        }
                                        if (sProductName.Contains("Skype"))
                                        {
                                            sProductVendor = "Microsoft";
                                        }
                                        if (sProductName.Contains("Outlook"))
                                        {
                                            sProductVendor = "Microsoft";
                                        }

                                        if (sProductName.Contains("MSN Messenger"))
                                        {
                                            sProductVendor = "Microsoft";
                                        }
                                        if (sProductName.Contains("Internet Explorer"))
                                        {
                                            sProductVendor = "Microsoft";
                                        }
                                        //Print Spooler Service
                                        //Licence Logging Service
                                        //File and Print Sharing
                                        //Remote Desktop Client
                                        //Local Security Authority Subsystem Service (LSASS)
                                        //Task Scheduler
                                        //Kerberos
                                        //NetBIOS

                                        if (sProductName.Contains("Google"))
                                        {
                                            sProductVendor = "Google";
                                        }
                                        if (sProductName.Contains("Adobe"))
                                        {
                                            sProductVendor = "Adobe";
                                        }
                                        if (sProductName.Contains("Flash Player"))
                                        {
                                            sProductVendor = "Adobe";
                                        }

                                        if (sProductName.Contains("Apple"))
                                        {
                                            sProductVendor = "Apple";
                                        }
                                        if (sProductName.Contains("Mozilla"))
                                        {
                                            sProductVendor = "Mozilla";
                                        }
                                        if (sProductName.Contains("Oracle"))
                                        {
                                            sProductVendor = "Oracle";
                                        }
                                        if (sProductName.Contains("Solaris"))
                                        {
                                            sProductVendor = "Oracle";
                                        }
                                        //Oracle VirtualBox
                                        if (sProductName.Contains("Apache"))
                                        {
                                            sProductVendor = "Apache";
                                        }
                                        if (sProductName.Contains("OpenOffice"))
                                        {
                                            sProductVendor = "Apache";
                                        }

                                        if (sProductName.Contains("avast"))
                                        {
                                            sProductVendor = "Avast";
                                        }
                                        if (sProductName.Contains("TechSmith"))
                                        {
                                            sProductVendor = "TechSmith";
                                        }
                                        if (sProductName.Contains("Kaspersky"))
                                        {
                                            sProductVendor = "Kaspersky";
                                        }
                                        if (sProductName.Contains("Symantec"))
                                        {
                                            sProductVendor = "Symantec";
                                        }
                                        if (sProductName.Contains("Norton"))
                                        {
                                            sProductVendor = "Symantec";                                            //Norton
                                        }
                                        if (sProductName.Contains("McAfee"))
                                        {
                                            sProductVendor = "McAfee";
                                        }
                                        if (sProductName.Contains("MySQL"))
                                        {
                                            sProductVendor = "MySQL";
                                        }
                                        if (sProductName.Contains("Kodak"))
                                        {
                                            sProductVendor = "Kodak";
                                        }
                                        if (sProductName.Contains("Lotus"))
                                        {
                                            sProductVendor = "Lotus";
                                        }
                                        if (sProductName.Contains("VMware"))
                                        {
                                            sProductVendor = "VMware";
                                        }
                                        if (sProductName.Contains("Trend Micro"))
                                        {
                                            sProductVendor = "Trend Micro";
                                        }

                                        //Crystal Enterprise
                                        if (sProductName.Contains("Crystal Reports"))
                                        {
                                            sProductVendor = "SAP";                                                     //SAP AG?   SAP AE?
                                        }
                                        if (sProductName.Contains("PostgreSQL"))
                                        {
                                            sProductVendor = "DB Consulting Inc.";
                                        }

                                        if (sProductVendor == "")
                                        {
                                            if (sProductName.Contains("IBM"))
                                            {
                                                sProductVendor = "IBM";
                                            }
                                            if (sProductName.Contains("Sun"))
                                            {
                                                sProductVendor = "Oracle";
                                            }
                                        }

                                        //Macrovision   Rovi Corporation
                                        //Opera
                                        //VLC
                                        //Winamp
                                        //VirtualBox
                                        //Perl
                                        //Python
                                        //RealPlayer
                                        //DirectX
                                        //DirectShow
                                        //...



                                        #endregion productvendor

                                        Console.WriteLine("DEBUG sProductVendor=" + sProductVendor);
                                        oProduct.ProductVendor = sProductVendor;
                                        //TODO  OrganisationID

                                        oProduct.CPEName      = sCPEName;
                                        oProduct.CreatedDate  = DateTimeOffset.Now;
                                        oProduct.VocabularyID = iVocabularyNCPID;
                                        oProduct.timestamp    = DateTimeOffset.Now;
                                        model.PRODUCT.Add(oProduct);
                                        model.SaveChanges();
                                        iProductID = oProduct.ProductID;
                                    }
                                    catch (Exception exAddProduct)
                                    {
                                        Console.WriteLine("Exception: exAddProduct " + exAddProduct.Message + " " + exAddProduct.InnerException);
                                    }
                                }
                                #endregion product

                                int iCategoryForProductID = 0;
                                #region PRODUCTCATEGORYFORPRODUCT
                                try
                                {
                                    iCategoryForProductID = model.PRODUCTCATEGORYFORPRODUCT.Where(o => o.ProductCategoryID == iProductCategoryID && o.ProductID == iProductID).FirstOrDefault().ProductCategoryForProductID;
                                }
                                catch (Exception ex)
                                {
                                }
                                if (iCategoryForProductID <= 0)
                                {
                                    Console.WriteLine("Adding PRODUCTCATEGORYFORPRODUCT");
                                    try
                                    {
                                        PRODUCTCATEGORYFORPRODUCT oCategoryForProduct = new PRODUCTCATEGORYFORPRODUCT();
                                        oCategoryForProduct.CreatedDate       = DateTimeOffset.Now;
                                        oCategoryForProduct.ProductCategoryID = iProductCategoryID;
                                        oCategoryForProduct.ProductID         = iProductID;
                                        oCategoryForProduct.VocabularyID      = iVocabularyNCPID;
                                        oCategoryForProduct.timestamp         = DateTimeOffset.Now;
                                        model.PRODUCTCATEGORYFORPRODUCT.Add(oCategoryForProduct);
                                        model.SaveChanges();
                                    }
                                    catch (Exception exPRODUCTCATEGORYFORPRODUCT)
                                    {
                                        Console.WriteLine("Exception exPRODUCTCATEGORYFORPRODUCT " + exPRODUCTCATEGORYFORPRODUCT.Message + " " + exPRODUCTCATEGORYFORPRODUCT.InnerException);
                                    }
                                }
                                else
                                {
                                    //Update PRODUCTCATEGORYFORPRODUCT
                                }
                                #endregion PRODUCTCATEGORYFORPRODUCT

                                int iCPEID = 0;
                                #region cpe
                                try
                                {
                                    iCPEID = model.CPE.Where(o => o.CPEName == sCPEName).FirstOrDefault().CPEID;
                                }
                                catch (Exception exCPEID)
                                {
                                }
                                if (iCPEID <= 0)
                                {
                                    Console.WriteLine("ERROR CPE Unknown " + sCPEName);
                                    //Console.WriteLine("DEBUG Adding CPE");
                                }
                                #endregion cpe

                                #endregion targetproduct
                                break;

                            case "ncp:other-link":
                                #region link
                                //<ncp:other-link dependency_flag="true">
                                string sReference          = "";
                                string sReferenceLinkTitle = "";
                                foreach (XmlNode nodeLink in nodeChecklistDetail.ChildNodes)
                                {
                                    switch (nodeLink.Name)
                                    {
                                    case "ncp:reference":
                                        //ncp:reference href="http://www.nsa.gov/ia/_files/app/I731-008R-2006.pdf"/>
                                        //TODO? other attributes?
                                        try
                                        {
                                            sReference = nodeLink.Attributes["href"].InnerText;
                                        }
                                        catch (Exception exhref)
                                        {
                                        }
                                        break;

                                    case "ncp:title":
                                        sReferenceLinkTitle = nodeLink.InnerText;
                                        break;

                                    default:
                                        Console.WriteLine("ERROR MISSING CODE FOR nodeLink.Name=" + nodeLink.Name);
                                        break;
                                    }
                                }
                                if (sReference != "")
                                {
                                    #region reference
                                    int iReferenceID = 0;
                                    try
                                    {
                                        iReferenceID = model.REFERENCE.Where(o => o.ReferenceURL == sReference).FirstOrDefault().ReferenceID;
                                    }
                                    catch (Exception exiReferenceID)
                                    {
                                    }
                                    if (iReferenceID <= 0)
                                    {
                                        Console.WriteLine("DEBUG Adding REFERENCE");
                                        try
                                        {
                                            REFERENCE oReference = new REFERENCE();
                                            oReference.CreatedDate    = DateTimeOffset.Now;
                                            oReference.ReferenceURL   = sReference;
                                            oReference.ReferenceTitle = sReferenceLinkTitle;
                                            oReference.VocabularyID   = iVocabularyNCPID;
                                            oReference.timestamp      = DateTimeOffset.Now;
                                            model.REFERENCE.Add(oReference);
                                            model.SaveChanges();
                                            iReferenceID = oReference.ReferenceID;
                                        }
                                        catch (Exception exAddReference)
                                        {
                                            Console.WriteLine("Exception: exAddReference " + exAddReference.Message + " " + exAddReference.InnerException);
                                        }
                                    }
                                    else
                                    {
                                        //Update REFERENCE
                                        //TODO Test if same Title
                                    }
                                    #endregion reference
                                }

                                #endregion link
                                break;

                            default:
                                Console.WriteLine("ERROR Missing code for nodeChecklistDetail " + nodeChecklistDetail.Name);
                                break;
                            }
                        }
                        break;

                    default:
                        Console.WriteLine("ERROR Missing code for nodeEntryInfo " + nodeEntryInfo.Name);
                        //<ncp:documentation>
                        //<ncp:checklist-role>Desktop Client</ncp:checklist-role>
                        //CHECKLISTCATEGORY
                        //<ncp:regulatory-compliance>DOD Directive 8500.</ncp:regulatory-compliance>
                        //<ncp:regulatory-compliance>TBD</ncp:regulatory-compliance>
                        //COMPLIANCE
                        break;
                    }
                }
            }
        }
Esempio n. 23
0
        public void parse()
        {
            Assembly a;

            a = Assembly.GetExecutingAssembly();

            Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", "Assembly location = " + a.Location);

            // ============================================
            // Parse the XML Document and populate the database
            // ============================================

            //   Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", "data = " + m_data);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(m_data);

            XORCISMEntities model;

            model = new XORCISMEntities();

            string query = "/ScanGroup/Scan";   //Hardcoded

            XmlNode report;

            report = doc.SelectSingleNode(query);

            string ipAddress = string.Empty;

            ipAddress = HelperGetChildInnerText(report, "StartURL");    //Hardcoded
            if (ipAddress.Substring(ipAddress.Length - 1, 1) == "/")
            {
                ipAddress = ipAddress.Substring(0, ipAddress.Length - 1);
            }
            Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("Handling host with IP {0}", ipAddress));

            // ===============================================
            // If necessary, creates an asset in the database
            // ===============================================
            //TODO
            var myass = from ass in model.ASSET
                        where ass.ipaddressIPv4 == ipAddress //&& ass.AccountID == m_AccountID
                        select ass;
            ASSET asset = myass.FirstOrDefault();

            if (asset == null)
            {
                Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", "Creates a new entry in table ASSET for this IP");

                asset = new ASSET();
                //asset.AccountID = m_AccountID;
                asset.AssetName        = ipAddress;
                asset.AssetDescription = ipAddress;
                asset.ipaddressIPv4    = ipAddress;
                asset.Enabled          = true;
                //asset.JobID = m_JobId;

                model.ASSET.Add(asset);
                model.SaveChanges();
            }
            else
            {
                Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", "This IP already corresponds to an existing asset");
            }

            Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", "Creating ASSETINSESSION reference");
            ASSETSESSION assinsess = new ASSETSESSION();

            assinsess.AssetID   = asset.AssetID;
            assinsess.SessionID = model.JOB.Single(x => x.JobID == m_JobId).SessionID;
            model.ASSETSESSION.Add(assinsess);
            model.SaveChanges();

            Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", "Update JOB with ASSETINSESSIONID");
            JOB daJob = model.JOB.Single(x => x.JobID == m_JobId);

            daJob.AssetSessionID = assinsess.AssetSessionID;
            model.SaveChanges();

            Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", "VULNERABILITIES FOUND");
            query = "/ScanGroup/Scan/ReportItems";

            report = doc.SelectSingleNode(query);

            foreach (XmlNode n in report.ChildNodes)
            {
                if (n.Name.ToUpper() == "ReportItem".ToUpper() && n.ChildNodes != null && n.ChildNodes.Count > 0)
                {
                    //TODOs HARDCODED
                    VulnerabilityEndPoint vulnerabilityEndPoint = new VulnerabilityEndPoint();
                    vulnerabilityEndPoint.IpAdress = ipAddress;
                    vulnerabilityEndPoint.Protocol = "TCP"; // "http";    //https ... A VOIR
                    vulnerabilityEndPoint.Port     = 80;    //443 ... A VOIR

                    VulnerabilityFound vulnerabilityFound = new VulnerabilityFound();
                    //vulnerabilityFound.ListItem = Helper_GetCVE(n);

                    vulnerabilityFound.InnerXml = n.OuterXml;
                    //To eliminate VULNERABILITY (Value) duplicates:

                    /*
                     * string pattern = @"ReportItem id=""\d\d?\d?""";
                     * string s = Regex.Replace(n.OuterXml, pattern, "ReportItem id=\"0\"");
                     * vulnerabilityFound.InnerXml = s;
                     */
                    string url = HelperGetChildInnerText(n, "Affects");     //Server
                    vulnerabilityFound.Url = url;
                    if (url.ToLower().Contains("https://"))
                    {
                        vulnerabilityEndPoint.Port = 443;
                    }
                    Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("Url: {0}", url));
                    vulnerabilityFound.Type = HelperGetChildInnerText(n, "Type");
                    if (HelperGetChildInnerText(n, "IsFalsePositive") == "False")
                    {
                        vulnerabilityFound.IsFalsePositive = false;
                    }
                    else
                    {
                        vulnerabilityFound.IsFalsePositive = true;
                    }
                    vulnerabilityFound.Title = HelperGetChildInnerText(n, "Name");
                    //ModuleName
                    //Affects
                    vulnerabilityFound.Description = HelperGetChildInnerText(n, "Description");
                    //Extract the CVEs
                    List <VulnerabilityFound.Item> ListCVEs = new List <VulnerabilityFound.Item>();
                    //MatchCollection matches = Regex.Matches(HelperGetChildInnerText(n, "Description"), "CVE-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]");
                    MatchCollection matches = Regex.Matches(HelperGetChildInnerText(n, "Description"), @"CVE-(19|20)\d\d-(0\d{3}|[1-9]\d{3,})");            //myRegexCVE
                    //https://cve.mitre.org/cve/identifiers/tech-guidance.html

                    foreach (Match match in matches)
                    {
                        Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("CVE: {0}", match.Groups[1].Value));
                        VulnerabilityFound.Item item;
                        item       = new VulnerabilityFound.Item();
                        item.ID    = "cve";
                        item.Value = match.Groups[1].Value;
                        ListCVEs.Add(item);
                    }

                    string mySeverity = HelperGetChildInnerText(n, "Severity");
                    switch (mySeverity)
                    {
                    //HARDCODED
                    case "high":
                        mySeverity = "High";
                        break;

                    case "medium":
                        mySeverity = "Medium";
                        break;

                    case "low":
                        mySeverity = "Low";
                        break;
                        //case "info"
                    }

                    vulnerabilityFound.Severity = mySeverity;
                    Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("Severity: {0}", mySeverity));
                    string DetailsAnalysis = HelperGetChildInnerText(n, "Details");
                    if (DetailsAnalysis.Contains("URL encoded GET"))
                    {
                        vulnerabilityFound.VulnerableParameterType = "GET";         //should be Querystring for Netsparker
                        var regex = new Regex(@"URL encoded GET input <b><font color=""dark"">(.*?)</font></b>");
                        var match = regex.Match(DetailsAnalysis);
                        if (match.Success)
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("VulnerableParameter: {0}", match.Groups[1].Value));
                            vulnerabilityFound.VulnerableParameter = match.Groups[1].Value;
                            regex = new Regex(@"was set to <b><font color=""dark"">(.*?)</font></b>");
                            match = regex.Match(DetailsAnalysis);
                            if (match.Success)
                            {
                                Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("VulnerableParameterValue: {0}", match.Groups[1].Value));
                                vulnerabilityFound.VulnerableParameterValue = match.Groups[1].Value;
                            }
                        }
                    }
                    if (DetailsAnalysis.Contains("URL encoded POST"))
                    {
                        vulnerabilityFound.VulnerableParameterType = "POST";         //should be Post for Netsparker
                        var regex = new Regex(@"URL encoded POST input <b><font color=""dark"">(.*?)</font></b>");
                        var match = regex.Match(DetailsAnalysis);
                        if (match.Success)
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("VulnerableParameter: {0}", match.Groups[1].Value));
                            vulnerabilityFound.VulnerableParameter = match.Groups[1].Value;
                            regex = new Regex(@"was set to <b><font color=""dark"">(.*?)</font></b>");
                            match = regex.Match(DetailsAnalysis);
                            if (match.Success)
                            {
                                Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("VulnerableParameterValue: {0}", match.Groups[1].Value));
                                vulnerabilityFound.VulnerableParameterValue = match.Groups[1].Value;
                            }
                        }
                    }
                    //vulnerabilityFound.VulnerableParameterType = HelperGetChildInnerText(n, "vulnerableparametertype");
                    //vulnerabilityFound.VulnerableParameter = HelperGetChildInnerText(n, "vulnerableparameter");
                    //in <Details>:
                    //URL encoded GET input <b><font color="dark">id</font></b> was set to <b><font color="dark">4-2+2*3-6</font></b>
                    //URL encoded GET input <b><font color="dark">id</font></b> was set to <b><font color="dark">1'</font></b><br/>Error message found: <pre wrap="virtual"><font color="blue">supplied argument is not a valid MySQL result</font></pre>
                    //URL encoded POST input <b><font color="dark">name</font></b> was set to <b><font color="dark">'&quot;()&amp;%1&lt;ScRiPt &gt;prompt(983150)&lt;/ScRiPt&gt;</font></b>
                    //vulnerabilityFound.VulnerableParameterValue = HelperGetChildInnerText(n, "vulnerableparametervalue");

                    List <VulnerabilityFound.Reference> ListReferences = new List <VulnerabilityFound.Reference>();
                    foreach (XmlNode nchild in n.ChildNodes)
                    {
                        if (nchild.Name.ToUpper() == "TechnicalDetails".ToUpper() && nchild.ChildNodes != null && nchild.ChildNodes.Count > 0)
                        {
                            //rawrequest
                            vulnerabilityFound.rawrequest = HelperGetChildInnerText(nchild, "Request");
                            //rawresponse
                            vulnerabilityFound.rawresponse = HelperGetChildInnerText(nchild, "Response");
                        }
                        if (nchild.Name.ToUpper() == "References".ToUpper() && nchild.ChildNodes != null && nchild.ChildNodes.Count > 0)
                        {
                            foreach (XmlNode reference in nchild)
                            {
                                /*
                                 * REFERENCE myReference = new REFERENCE();
                                 * myReference.Source = HelperGetChildInnerText(reference, "Database");
                                 * myReference.Url = HelperGetChildInnerText(reference, "URL");
                                 *
                                 * model.AddToREFERENCE(myReference);
                                 */

                                VulnerabilityFound.Reference refvuln = new VulnerabilityFound.Reference();
                                refvuln.Title = HelperGetChildInnerText(reference, "Database");
                                string refurl = HelperGetChildInnerText(reference, "URL").ToLower();
                                refvuln.Url    = refurl;
                                refvuln.Source = HelperGetChildInnerText(reference, "Database");
                                //Try to harmonise the Source with the other imports (ie: exploits)
                                //HARDCODED
                                //TODO: Use a Common Function
                                if (refurl.Contains("/bugtraq/"))
                                {
                                    refvuln.Source = "BUGTRAQ";
                                }
                                if (refurl.Contains("marc.theaimsgroup.com/?l=bugtraq"))
                                {
                                    refvuln.Source = "BUGTRAQ";
                                }
                                if (refurl.Contains("securityfocus.com/bid"))
                                {
                                    refvuln.Source = "BID";
                                }
                                if (refurl.Contains("osvdb.org/"))
                                {
                                    refvuln.Source = "OSVDB";
                                }
                                if (refurl.Contains("xforce.iss.net/"))
                                {
                                    refvuln.Source = "XF";
                                }
                                if (refurl.Contains("www.iss.net/"))
                                {
                                    refvuln.Source = "XF";
                                }
                                if (refurl.Contains("www.ciac.org/"))
                                {
                                    refvuln.Source = "CIAC";
                                }
                                if (refurl.Contains("ciac.llnl.gov/"))
                                {
                                    refvuln.Source = "CIAC";
                                }
                                if (refurl.Contains("www.cert.org/"))
                                {
                                    refvuln.Source = "CERT";
                                }
                                if (refurl.Contains("sunsolve.sun.org/"))
                                {
                                    refvuln.Source = "SUN";
                                }
                                if (refurl.Contains("sunsolve.sun.com/"))
                                {
                                    refvuln.Source = "SUN";
                                }
                                if (refurl.Contains("patches.sgi.com/"))
                                {
                                    refvuln.Source = "SGI";
                                }
                                if (refurl.Contains("microsoft.com/default.aspx?scid=kb"))
                                {
                                    refvuln.Source = "MSKB";
                                }
                                if (refurl.Contains("ftp.sco.com/"))
                                {
                                    refvuln.Source = "SCO";
                                }
                                if (refurl.Contains("www.trustix.org/"))
                                {
                                    refvuln.Source = "TRUSTIX";
                                }
                                if (refurl.Contains("ftp.freebsd.org/"))
                                {
                                    refvuln.Source = "FREEBSD";
                                }
                                if (refurl.Contains("www.secunia.com/"))
                                {
                                    refvuln.Source = "SECUNIA";
                                }
                                if (refurl.Contains("www.vupen.com/"))
                                {
                                    refvuln.Source = "VUPEN";
                                }
                                if (refurl.Contains("www.securitytracker.com/"))
                                {
                                    refvuln.Source = "SECTRACK";
                                }
                                if (refurl.Contains("www.redhat.com/"))
                                {
                                    refvuln.Source = "REDHAT";
                                }
                                if (refurl.Contains("www.exploit-db.com/"))
                                {
                                    refvuln.Source = "EXPLOIT-DB";
                                }
                                if (refurl.Contains("www.milw0rm.com/"))
                                {
                                    refvuln.Source = "MILW0RM";
                                }
                                if (refurl.Contains("www.microsoft.com/"))
                                {
                                    refvuln.Source = "MS";
                                }
                                if (refurl.Contains("seclists.org/fulldisclosure"))
                                {
                                    refvuln.Source = "FULLDISC";
                                }
                                ListReferences.Add(refvuln);
                            }
                        }
                    }
                    vulnerabilityFound.ListReference = ListReferences;
                    vulnerabilityFound.ListItem      = ListCVEs;
                    vulnerabilityFound.Result        = HelperGetChildInnerText(n, "Details");
                    vulnerabilityFound.Consequence   = HelperGetChildInnerText(n, "Impact");
                    vulnerabilityFound.Solution      = HelperGetChildInnerText(n, "Recommendation");
                    //DetailedInformation
                    vulnerabilityFound.DetailedInformation = HelperGetChildInnerText(n, "DetailedInformation");

                    //TODO
                    bool   PatchUpgrade = false;
                    string MSPatch      = "";


                    int etat = VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, m_JobId, "acunetix", model);
                    if (etat == -1)
                    {
                        Utils.Helper_Trace("XORCISM PROVIDER ACUNETIX", string.Format("CANNOT IMPORT THIS ASSET !!!! "));
                    }
                }
            }
        }
Esempio n. 24
0
        //public CompositeType GetDataUsingDataContract(CompositeType composite)
        //{
        //    if (composite == null)
        //    {
        //        throw new ArgumentNullException("composite");
        //    }
        //    if (composite.BoolValue)
        //    {
        //        composite.StringValue += "Suffix";
        //    }
        //    return composite;
        //}

        public int CreateSession(int serviceCategoryID, Guid userID, byte[] parameters, Decimal PeasCount, Decimal PeasValue)
        {
            //Where Magic happens
            Utils.Helper_Trace("MANAGER SERVICE", "Entering CreateSession()");
            
            Utils.Helper_Trace("MANAGER SERVICE", string.Format("ServiceCategoryID = {0}", serviceCategoryID));
            Utils.Helper_Trace("MANAGER SERVICE", string.Format("UserID            = {0}", userID.ToString()));

            Dictionary<string, object> dicoParameters;

            try
            {
                MemoryStream ms;
                ms = new MemoryStream(parameters);

                BinaryFormatter bf;
                bf = new BinaryFormatter();

                dicoParameters = (Dictionary<string, object>)bf.Deserialize(ms);
            }
            catch (Exception e)
            {
                Utils.Helper_Trace("MANAGER SERVICE", string.Format("Exception while deserializing parameters : {0}", e.Message));
                return -1;
            }

            Utils.Helper_Trace("MANAGER SERVICE", string.Format("Size of parameters = {0} bytes", parameters.Length));

            int[] tabAssetID        = null;
            int MaxPages;
            string FileName         = string.Empty;
            string nmapAddress      = string.Empty;
            string cronExpression   = string.Empty;
            string sip              = string.Empty;
            string extrange         = string.Empty;
            string policy           = string.Empty;
            string strategie        = string.Empty;
           
            switch (serviceCategoryID)  //TODO Hardcoded
            {
                case 1:             // Vulnerability Assessment
                    tabAssetID      = (int[])dicoParameters["ASSETS"];
                    cronExpression  = (string)dicoParameters["CRONEXPRESSION"];
                    policy          = (string)dicoParameters["POLICY"];
                    strategie       = (string)dicoParameters["STRATEGY"];

                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets  = {0}", tabAssetID.Length));
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression   = {0}", cronExpression));

                    break;

                case 2:             //WAS   (Web Application Scanning)
                    tabAssetID      = (int[])dicoParameters["ASSETS"];
                    cronExpression  = (string)dicoParameters["CRONEXPRESSION"];
                    policy          = (string)dicoParameters["POLICY"];
                    strategie       = (string)dicoParameters["STRATEGY"];

                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets  = {0}", tabAssetID.Length));
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression   = {0}", cronExpression));

                    break;
                case 3:
                    Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 3");

                    break;
                case 4:             //PCI DSS
                    tabAssetID      = (int[])dicoParameters["ASSETS"];
                    cronExpression  = (string)dicoParameters["CRONEXPRESSION"];
                    policy          = "PCI DSS";
                    strategie       = "Compliance PCI DSS"; //(string)dicoParameters["STRATEGY"];

                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets  = {0}", tabAssetID.Length));
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression   = {0}", cronExpression));

                    break;
                case 5:
                    Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 5");
                    
                    break;
                case 6:             // VOIP Scanner
                    tabAssetID = (int[])dicoParameters["ASSETS"];
                    sip = (string)dicoParameters["SIP"];
                    extrange = (string)dicoParameters["EXTRANGE"];
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets  = {0}", tabAssetID.Length));
                    break;

                case 7:             // Web Anti-malware Monitoring
                    tabAssetID = (int[])dicoParameters["ASSETS"];
                    cronExpression = (string)dicoParameters["CRONEXPRESSION"];
                    MaxPages = (int)dicoParameters["MaxPages"];
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Service Malware Monitoring:Number of assets  = {0}", tabAssetID.Length));
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression   = {0}", cronExpression));
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Service Malware Monitoring:MaxPages  = {0}", MaxPages));
                    break;

                case 8:             // Web Site Monitoring
                    tabAssetID = (int[])dicoParameters["ASSETS"];
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets  = {0}", tabAssetID.Length));
                    break;

                case 9:
                    Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 9");

                    break;
                case 10:            // Discovery

                    nmapAddress = (string)dicoParameters["TARGET"];
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Target = {0}", nmapAddress));
                    break;

                case 11:
                case 12:
                case 13:             // Import
                case 14:
                case 15:
                    FileName = (string)dicoParameters["FILENAME"];
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Import File : Filename = {0}", FileName));
                    break;

                case 16:             //Information Gathering (OSINT)
                    tabAssetID = (int[])dicoParameters["ASSETS"];
                    cronExpression = (string)dicoParameters["CRONEXPRESSION"];
                    policy = (string)dicoParameters["POLICY"];
                    strategie = (string)dicoParameters["STRATEGY"];

                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets  = {0}", tabAssetID.Length));
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression   = {0}", cronExpression));

                    break;
                
            }

            XORCISMEntities context = new XORCISMEntities();

            // ===============================================
            // Add a new entry in table SESSION or SESSIONCRON
            // ===============================================

            int id;

            if (cronExpression == "")
            {
                // ================================
                // Add a new entry in table SESSION
                // ================================

                Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding an entry in table SESSION"));

                SESSION tmpSession = new SESSION();
                //Price
                try
                {
                    tmpSession.UserID               = userID;
                    tmpSession.Status = XCommon.STATUS.IDLE.ToString();
                    tmpSession.ServiceCategoryID    = serviceCategoryID;
                    tmpSession.DateEnd              = null;
                    tmpSession.DateStart            = DateTimeOffset.Now;
                    tmpSession.Parameters           = parameters;
                    //Price

                    context.SESSION.Add(tmpSession);

                    context.SaveChanges();
                    //Price
                }
                catch (Exception ex)
                {
                    /*
                    USER user;
                    user = context.USERS.SingleOrDefault(u => u.UserId == userID);
                    ACCOUNT userAccount;
                    userAccount = context.USERACCOUNT.SingleOrDefault(o => o.UserID == user.UserId).ACCOUNT;

                    //Price
                    */
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entry in table SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message));
                    throw ex;
                }

                Utils.Helper_Trace("MANAGER SERVICE", string.Format("SessionID = {0}", tmpSession.SessionID));
                //Random random = new Random();                
                try
                {
                //    tmpSession.SessionID = tmpSession.SessionID + random.Next(20, 200);
                //    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error random SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message));
                }
                Utils.Helper_Trace("MANAGER SERVICE", string.Format("NewRandomSessionID = {0}", tmpSession.SessionID));

                id = tmpSession.SessionID;

                // ============================================
                // Add several entries in table ASSETSESSION
                // ============================================

                if (tabAssetID != null)
                {
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding {0} entries in table ASSETSESSION", tabAssetID.Count()));

                    try
                    {
                        foreach (int assetID in tabAssetID)
                        {
                            ASSETSESSION tmpAinS = new ASSETSESSION();
                            tmpAinS.SESSION = tmpSession;
                            tmpAinS.AssetID = assetID;
                            context.ASSETSESSION.Add(tmpAinS);
                        }
                        context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entries in table ASSETSESSION : Exception = {0}", ex.Message));
                        throw ex;
                    }
                }
            }
            else
            {
                Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding an entry in table SESSIONCRON"));

                SESSIONCRON tmpSessionCron = new SESSIONCRON();
                //Price
                try
                {
                    tmpSessionCron.UserID               = userID;
                    tmpSessionCron.CronExpression       = cronExpression;
                    tmpSessionCron.Parameters           = parameters;
                    tmpSessionCron.Status = XCommon.STATUS.IDLE.ToString();
                    tmpSessionCron.ServiceCategoryID    = serviceCategoryID;
                    tmpSessionCron.DateStart            = DateTimeOffset.Now;         //TODO Non il faut que ce soit les dates de start/end du cron A VOIR TODO
                    tmpSessionCron.DateEnd              = null;
                    //Price
                    
                    context.SESSIONCRON.Add(tmpSessionCron);

                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entry in table SESSIONCRON : Exception = {0} - {1}", ex.Message, ex.InnerException.Message));
                    throw ex;
                }

                Utils.Helper_Trace("MANAGER SERVICE", string.Format("SessionCronID = {0}", tmpSessionCron.SessionCronID));

                id = tmpSessionCron.SessionCronID;
            }

            Utils.Helper_Trace("MANAGER SERVICE", "Leaving CreateSession()");

            // Finished
            return id;
        }
Esempio n. 25
0
        private void FuncThreadLaunchSession(object context)
        {
            LaunchSessionThreadInfo info;

            info = (LaunchSessionThreadInfo)context;

            int sessionID;

            sessionID = info.SessionID;

            XORCISMEntities model = new XORCISMEntities();

            SESSION session;

            session = model.SESSION.SingleOrDefault(o => o.SessionID == sessionID);

            int accountID;

            accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID;

            // ===========================================
            // Determine the providers that we have to use
            // ===========================================

            var category = (from sessions in model.SESSION
                            where sessions.SessionID == sessionID
                            select sessions.ServiceCategoryID).First();

            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : ServiceCategoryID is {1}   AccountID is {2}", sessionID, category.Value, accountID));

            var ListProvider = from provider in model.PROVIDER
                               where provider.ServiceCategoryID == category && provider.PROVIDERSFORACCOUNT.Any(o => o.AccountID == accountID && o.ValidUntil >= DateTimeOffset.Now)
                               select provider.ProviderID;

            List <int> listProviderID;

            listProviderID = ListProvider.ToList <int>();

            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Session will use {1} providers", sessionID, listProviderID.Count));
            int nbjoberror = 0;

            if (listProviderID.Count > 0)
            {
                // ================================
                // Add several entries in table JOB
                // ================================

                var ListAssetInSession = from AinS in model.ASSETSESSION
                                         where AinS.SessionID == sessionID
                                         select AinS.AssetSessionID;

                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Session involves {1} assets", sessionID, ListAssetInSession.Count()));

                int count;
                count = ListAssetInSession.Count() * listProviderID.Count;

                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Adding {1} entries in table JOB", sessionID, count));

                var param = from o in model.SESSION
                            where o.SessionID == sessionID
                            select o.Parameters;

                if (ListAssetInSession.Count() != 0)
                {
                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Case 1", sessionID));

                    foreach (int AinSID in ListAssetInSession)
                    {
                        foreach (int providerID in listProviderID)
                        {
                            try
                            {
                                JOB job = new JOB();
                                job.AssetSessionID = AinSID;
                                job.ProviderID     = providerID;
                                job.DateStart      = DateTimeOffset.Now;
                                job.Status         = XCommon.STATUS.IDLE.ToString();
                                job.Parameters     = param.First();
                                job.SessionID      = sessionID;
                                model.JOB.Add(job);
                                //model.AddToJOB(job);
                                //model.SaveChanges();

                                info.ListJob.Add(job);
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Added Job {1}", sessionID, job.JobID));
                            }
                            catch (Exception e1)
                            {
                                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Exception AddingJob1 " + e1.Message + " " + e1.InnerException, sessionID));
                            }
                        }
                    }
                    model.SaveChanges();
                }
                else
                {
                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Case 2", sessionID));
                    switch ((int)category.Value)
                    {
                    case 10:
                        //nmap discovery
                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : nmap discovery", sessionID));
                        break;

                    case 11:
                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import nessus", sessionID));
                        break;

                    case 14:
                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import netsparker", sessionID));
                        break;

                    case 15:
                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import acunetix", sessionID));
                        break;

                    default:
                        return;
                    }
                    foreach (int providerID in listProviderID)
                    {
                        try
                        {
                            JOB job = new JOB();
                            job.AssetSessionID = null;
                            job.ProviderID     = providerID;
                            job.DateStart      = DateTimeOffset.Now;
                            job.Status         = XCommon.STATUS.IDLE.ToString();
                            job.Parameters     = param.First();
                            job.SessionID      = sessionID;
                            //model.JOB.AddObject(job);
                            model.JOB.Add(job);
                            model.SaveChanges();

                            info.ListJob.Add(job);
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Added Job {1}", sessionID, job.JobID));
                        }
                        catch (Exception e1)
                        {
                            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Exception AddingJob2 " + e1.Message + " " + e1.InnerException, sessionID));
                        }
                    }
                }
                //model.SaveChanges();

                // =========================================
                // Dispatch the jobs on the available agents
                // =========================================

                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Dispatching jobs on agents", sessionID));

                foreach (JOB J in info.ListJob)
                {
                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Handling job {1}", sessionID, J.JobID));

                    // ======================================================
                    //TODO Get the agent with the lowest load (loadbalancing)
                    // ======================================================

                    //TODO

                    /*
                     * var agent = from Ag in model.AGENT
                     *          where Ag.Status == "ENABLED"
                     *          select Ag;
                     * if (agent == null)
                     * {
                     *  Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : There is no agent with status ENABLED", sessionID));
                     *  return;
                     * }
                     */

                    //TODO

                    /*
                     * var bestAgent = agent.ToList().OrderBy(c => c.Load).First();
                     * bestAgent.Load++;
                     *
                     * Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : The best agent for this job is at {1} ({2})", sessionID, bestAgent.AgentID, bestAgent.IPAddress));
                     */

                    // ====================================
                    // Contact the agent and launch the job
                    // ====================================

                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Trying to contact the agent", sessionID));

                    try
                    {
                        ServiceReferenceAgent.Service1Client service;
                        service = new ServiceReferenceAgent.Service1Client();

                        // TODO :
                        // service.Endpoint.Address = bestAgent.IPAddress;      // TODO

                        service.LaunchJob((Guid)session.UserID, J.JobID);
                    }
                    catch (Exception ex)
                    {
                        Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Error contacting the agent. Exception = {1}", sessionID, ex.Message));
                        //HARDCODED
                        XCommon.Utils.Helper_SendEmail("*****@*****.**", "MANAGER ENGINE ERROR", "THREADLAUNCHSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException);
                        return;
                    }

                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : The agent has been successfully contacted", sessionID));

                    // =====================================
                    //TODO Update table JOB (column AgentID)
                    // =====================================

                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : TODO Updating table JOB (AgentID column)", sessionID));
                    //TODO
                    //J.AgentID = bestAgent.AgentID;

                    //TODO: TryCatch
                    model.SaveChanges();
                }

                // =================================
                // Wait until all jobs have finished
                // =================================

                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Waiting until all jobs have finished", sessionID));

                try
                {
                    bool bFinished = false;
                    do
                    {
                        Thread.Sleep(10000);    //HARDCODED

                        bFinished  = true;
                        nbjoberror = 0;

                        //                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : There are {1} jobs in this session", sessionID, info.ListJob.Count.ToString()));

                        var myCurrentSession = from Sess in model.SESSION
                                               where Sess.SessionID == sessionID
                                               select Sess;
                        SESSION CurrentSession = myCurrentSession.ToList().First();

                        foreach (JOB J in info.ListJob)
                        {
                            int AllJobs = 0;

                            // ==========================
                            // Get the status of this job
                            // ==========================

                            var MyJob = from MyJobs in model.JOB
                                        where MyJobs.JobID == J.JobID
                                        select MyJobs.Status;

                            string jobStatus = (string)MyJob.ToList().First();

                            if (jobStatus != XCommon.STATUS.FINISHED.ToString() && jobStatus != XCommon.STATUS.ERROR.ToString())
                            {
                                bFinished = false;
                                break;
                            }
                            else
                            {
                                if (jobStatus == XCommon.STATUS.ERROR.ToString())
                                {
                                    nbjoberror++;
                                }
                                AllJobs++;
                            }

                            int pourcent = (100 / (int)MyJob.Count()) * AllJobs;

                            // CurrentSession.Status = pourcent + "%";

                            //model.SaveChanges();
                        }
                    }while (bFinished == false);
                }
                catch (ThreadAbortException ex)
                {
                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Thread has been aborted", sessionID));
                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadAbortException : Exception = {0}", ex.Message));
                    return;
                }

                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : All jobs have finished ({1} Errors)", sessionID, nbjoberror));
            }

            // =============================
            // Update table SESSION (Status)
            // =============================

            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Updating status in table SESSION", sessionID));

            var mySession = from Sess in model.SESSION
                            where Sess.SessionID == sessionID
                            select Sess;
            SESSION MySession = mySession.ToList().First();

            string additionalmailMessage = string.Empty;

            //Dealing with jobs in error
            if (info.ListJob.Count == nbjoberror)
            {
                //TODO xxx

                MySession.Status = XCommon.STATUS.ERROR.ToString();
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : All jobs in error: xxx", sessionID));
                //TODO xxx
            }
            else
            {
                MySession.Status = XCommon.STATUS.FINISHED.ToString();
            }
            MySession.DateEnd = DateTimeOffset.Now;

            model.SaveChanges();

            // ============
            // Notification
            // ============

            //TODO
            //XCommon.Utils.Helper_Notify(session.UserID.Value, "TASK_JOB", sessionID.ToString(), XCommon.RIGHT.MODIFY);

            //TODO

            /*
             * string mailMessage = "Hello "+ session.aspnet_Membership.USERS.UserName +". Your Hackenaton session " + sessionID + " ("+ MySession.SERVICECATEGORY.ServiceCategoryName +") is completed with the status: "+ MySession.Status+". Assets scanned: "; //HARDCODED
             * var myAssets = from assets in model.ASSET
             *             join assetinsess in model.ASSETSESSION on assets.AssetID equals assetinsess.AssetID
             *             where assetinsess.SessionID == sessionID
             *             select assets;
             * foreach (ASSET ass in myAssets)
             * {
             *  //TODO  ipaddressIPv4
             *  mailMessage += ass.ipaddressIPv4 + " ";
             * }
             * mailMessage += "Completed in " + string.Format("{0:00}:{1:00}:{2:00}", (MySession.DateEnd.Value - MySession.DateStart.Value).Hours, (MySession.DateEnd.Value - MySession.DateStart.Value).Minutes, (MySession.DateEnd.Value - MySession.DateStart.Value).Seconds);
             * mailMessage +=". Visit the Hackenaton website to display the Report.";
             * mailMessage += additionalmailMessage;
             * XCommon.Utils.Helper_SendEmail(session.aspnet_Membership.Email, "Hackenaton scan finished", mailMessage);   //HARDCODED
             */

            m_ListRunningSessionThread.Remove(sessionID);

            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Finished", sessionID));
        }
Esempio n. 26
0
        public void parse()
        {
            Assembly a;

            a = Assembly.GetExecutingAssembly();

            Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "Assembly location = " + a.Location);

            // ===================================================
            // Parses the XML Document and populates the database
            // ===================================================

            //   Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "data = " + m_data);

            XmlDocument doc = new XmlDocument();

            //TODO: Input Validation (XML)
            doc.LoadXml(m_data);

            XORCISMEntities model;

            model = new XORCISMEntities();

            string query = "/netsparker/target";    //Hardcoded

            XmlNode report;

            report = doc.SelectSingleNode(query);

            string ipAddress = string.Empty;

            ipAddress = HelperGetChildInnerText(report, "url"); //Hardcoded
            if (ipAddress.Substring(ipAddress.Length - 1, 1) == "/")
            {
                ipAddress = ipAddress.Substring(0, ipAddress.Length - 1);
            }
            Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", string.Format("Handling host with IP {0}", ipAddress));

            // ===============================================
            // If necessary, creates an asset in the database
            // ===============================================

            //TODO  ipaddressIPv4
            var myass = from ass in model.ASSET
                        where ass.ipaddressIPv4 == ipAddress //&& ass.AccountID == m_AccountID
                        select ass;
            ASSET asset = myass.FirstOrDefault();

            if (asset == null)
            {
                Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "Creates a new entry in table ASSET for this IP");

                asset = new ASSET();
                //asset.AccountID = m_AccountID;
                asset.AssetName        = ipAddress;
                asset.AssetDescription = ipAddress;
                //TODO  ipaddressIPv4
                asset.ipaddressIPv4 = ipAddress;
                asset.Enabled       = true;
                //asset.JobID = m_JobId;

                model.ASSET.Add(asset);
                model.SaveChanges();
            }
            else
            {
                Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "This IP already corresponds to an existing asset");
            }

            Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "Creating ASSETINSESSION reference");
            ASSETSESSION assinsess = new ASSETSESSION();

            assinsess.AssetID   = asset.AssetID;
            assinsess.SessionID = model.JOB.Single(x => x.JobID == m_JobId).SessionID;
            model.ASSETSESSION.Add(assinsess);
            model.SaveChanges();

            Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "Update JOB with ASSETINSESSIONID");
            JOB daJob = model.JOB.Single(x => x.JobID == m_JobId);

            daJob.AssetSessionID = assinsess.AssetSessionID;
            model.SaveChanges();

            Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "VULNERABILITIES FOUND");
            query = "/netsparker";  //Hardcoded

            report = doc.SelectSingleNode(query);

            foreach (XmlNode n in report.ChildNodes)
            {
                //Hardcoded
                if (n.Name.ToUpper() == "vulnerability".ToUpper() && n.ChildNodes != null && n.ChildNodes.Count > 0)
                {
                    if (n.Attributes["confirmed"].InnerText == "True")
                    {
                        VulnerabilityEndPoint vulnerabilityEndPoint = new VulnerabilityEndPoint();
                        vulnerabilityEndPoint.IpAdress = ipAddress;
                        vulnerabilityEndPoint.Protocol = "TCP"; // "http";    //https ... A VOIR
                        vulnerabilityEndPoint.Port     = 80;    //443 ... A VOIR

                        VulnerabilityFound vulnerabilityFound = new VulnerabilityFound();
                        //vulnerabilityFound.ListItem = Helper_GetCVE(n);
                        vulnerabilityFound.InnerXml = n.OuterXml;
                        string url = HelperGetChildInnerText(n, "url");
                        vulnerabilityFound.Url = url;
                        if (url.ToLower().Contains("https://"))
                        {
                            vulnerabilityEndPoint.Port = 443;
                        }
                        Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", string.Format("Url: {0}", url));
                        //vulnerabilityFound.Type = HelperGetChildInnerText(n, "type");
                        vulnerabilityFound.Title       = HelperGetChildInnerText(n, "type");
                        vulnerabilityFound.Description = HelperGetChildInnerText(n, "type");

                        vulnerabilityFound.Severity = HelperGetChildInnerText(n, "severity");
                        Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", string.Format("Severity: {0}", HelperGetChildInnerText(n, "severity")));
                        vulnerabilityFound.VulnerableParameterType  = HelperGetChildInnerText(n, "vulnerableparametertype");
                        vulnerabilityFound.VulnerableParameter      = HelperGetChildInnerText(n, "vulnerableparameter");
                        vulnerabilityFound.VulnerableParameterValue = HelperGetChildInnerText(n, "vulnerableparametervalue");
                        //rawrequest
                        //rawresponse
                        //extrainformation
                        //  <info name="Found E-mails">[email protected]</info>
                        //  <info name="Identified Internal Path(s)">/var/www/webscantest/vulnsite/picshare/upload.pl</info>
                        vulnerabilityFound.Consequence = HelperGetChildInnerText(n, "extrainformation");

                        bool   PatchUpgrade = false;
                        string MSPatch      = "";

                        /*
                         * <classification>
                         *  <OWASP>A1</OWASP>
                         *  <WASC>19</WASC>
                         *  <CWE>89</CWE>
                         *  <CAPEC>66</CAPEC>
                         * </classification>
                         */
                        foreach (XmlNode classif in n.ChildNodes)
                        {
                            //Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "classif n.ChildNodes: " + classif.Name);
                            if (classif.Name.ToUpper() == "classification".ToUpper() && classif.ChildNodes != null && classif.ChildNodes.Count > 0)
                            {
                                Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "OWASP: " + HelperGetChildInnerText(classif, "OWASP"));
                                Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "WASC: " + HelperGetChildInnerText(classif, "WASC"));
                                Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "CWE: " + HelperGetChildInnerText(classif, "CWE"));
                                Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", "CAPEC: " + HelperGetChildInnerText(classif, "CAPEC"));
                            }
                        }


                        int etat = VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, m_JobId, "netsparker", model);
                        if (etat == -1)
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER NETSPARKER", string.Format("CANNOT IMPORT THIS ASSET !!!! "));
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        private void FuncThreadCancelSession(object context)
        {
            LaunchSessionThreadInfo info;

            info = (LaunchSessionThreadInfo)context;

            int sessionID;

            sessionID = info.SessionID;

            XORCISMEntities model = new XORCISMEntities();

            SESSION session;

            session = model.SESSION.SingleOrDefault(o => o.SessionID == sessionID);

            //int accountID;
            //accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID;

            // =============================
            // Cancel the jobs on the agents
            // =============================

            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Cancelling jobs on agents", sessionID));

            foreach (JOB J in info.ListJob)
            {
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Handling job {1}", sessionID, J.JobID));

                // ====================================
                // Contact the agent and cancel the job
                // ====================================

                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Trying to contact the agent", sessionID));

                try
                {
                    ServiceReferenceAgent.Service1Client service;
                    service = new ServiceReferenceAgent.Service1Client();

                    // TODO :
                    // service.Endpoint.Address = bestAgent.IPAddress;

                    service.CancelJob(J.JobID);
                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Error contacting the agent. Exception = {1} {2}", sessionID, ex.Message, ex.InnerException));
                    //HARDCODED
                    XCommon.Utils.Helper_SendEmail("*****@*****.**", "MANAGER ENGINE ERROR", "THREADCANCELSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException);
                    return;
                }

                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : The agent has been successfully contacted", sessionID));
            }

            // =============================
            // Update table SESSION (Status)
            // =============================

            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Updating status in table SESSION to CANCELED", sessionID));

            var mySession = from Sess in model.SESSION
                            where Sess.SessionID == sessionID
                            select Sess;
            SESSION MySession = mySession.ToList().First();

            MySession.Status  = XCommon.STATUS.CANCELED.ToString();
            MySession.DateEnd = DateTimeOffset.Now;

            model.SaveChanges();
            try
            {
                m_ListRunningSessionThread.Remove(sessionID);
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Error m_ListRunningSessionThread.Remove. Exception = {1}", sessionID, ex.Message));
                return;
            }


            Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Finished", sessionID));
        }
Esempio n. 28
0
        /// <summary>
        /// Copyright (C) 2015 Jerome Athias
        /// *** ALPHA VERSION ***
        /// Import the Cybersecurity Framework Excel file in an XORCISM database
        /// All trademarks and registered trademarks are the property of their respective owners.
        /// This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
        ///
        /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
        ///
        /// You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
        /// </summary>

        static void Main(string[] args)
        {
            //Ref.: http://www.nist.gov/cyberframework/upload/framework-for-improving-critical-infrastructure-cybersecurity-core.xlsx


            XORCISMEntities model = new XORCISMEntities();

            //https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
            model.Configuration.AutoDetectChangesEnabled = false;
            model.Configuration.ValidateOnSaveEnabled    = false;

            int iVocabularyCSFID = 0;   // 7;

            #region vocabularycsf
            try
            {
                iVocabularyCSFID = model.VOCABULARY.Where(o => o.VocabularyName == "CCE").Select(o => o.VocabularyID).FirstOrDefault();
            }
            catch (Exception ex)
            {
            }
            if (iVocabularyCSFID <= 0)
            {
                VOCABULARY oVocabulary = new VOCABULARY();
                oVocabulary.CreatedDate    = DateTimeOffset.Now;
                oVocabulary.VocabularyName = "Cybersecurity Framework";
                oVocabulary.timestamp      = DateTimeOffset.Now;
                model.VOCABULARY.Add(oVocabulary);
                model.SaveChanges();
                iVocabularyCSFID = oVocabulary.VocabularyID;
                Console.WriteLine("DEBUG iVocabularyCSFID=" + iVocabularyCSFID);
            }
            #endregion vocabularcsf

            var ExcelObj = new Microsoft.Office.Interop.Excel.Application();
            //HARDCODED
            Workbook  theWorkbook = ExcelObj.Workbooks.Open(@"C:\nvdcve\framework-for-improving-critical-infrastructure-cybersecurity-core.xlsx", 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
            Sheets    sheets      = theWorkbook.Worksheets;
            Worksheet worksheet   = (Worksheet)sheets.get_Item(1);
            for (int i = 1; i <= 10; i++)
            {
                Range        range    = worksheet.get_Range("A" + i.ToString(), "J" + i.ToString());
                System.Array myvalues = (System.Array)range.Cells.Value;
                string[]     strArray = ConvertToStringArray(myvalues);
                int          iCol     = 0;


                foreach (string sValue in strArray)
                {
                    iCol++;

                    switch (iCol.ToString())
                    {
                    case "1":       //CCE ID

                        break;

                    case "2":       //CCE Description

                        break;

                    default:
                        break;
                    }


                    Console.WriteLine(sValue);
                }
                Console.WriteLine("---------------------------------");
            }
        }
Esempio n. 29
0
        /* @default : port = "80"
         * @default : strategy | tunning ="x"
         */
        public void Run(string target, int jobID, string policy, string strategy)
        {
            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "Entering Run()");
            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("Target = {0} , JobID = {1} , Policy = {2}, Strategy = {3}", target, jobID, policy, strategy));

            // delete spaces for multisite
            target = target.Replace(" ", "");

            /* On initialise une var */
            NiktoParser niktoParser = null;

            try
            {
                niktoParser = new NiktoParser(target, jobID, policy, strategy);
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "JobID:" + jobID + "Exception NiktoParser = " + ex.Message + " " + ex.InnerException);
            }

            string status = XCommon.STATUS.FINISHED.ToString();


            // =================================================
            // Change the status of the job to FINISHED or ERROR
            // =================================================

            if (niktoParser.Parse() == false)
            {
                status = XCommon.STATUS.ERROR.ToString();
                Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("Updating job {0} status to ERROR", jobID));
                XCommon.Utils.Helper_SendEmail("*****@*****.**", "Nikto ERROR", "Nikto ERROR for job:" + jobID);
            }
            else
            {
                Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("Updating job {0} status to FINISHED", jobID));
            }

            try
            {
                XORCISMEntities model = new XORCISMEntities();
                var             Q     = from j in model.JOB
                                        where j.JobID == jobID
                                        select j;

                JOB myJob = Q.FirstOrDefault();
                myJob.Status  = status;
                myJob.DateEnd = DateTimeOffset.Now;
                //image
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                myJob.XmlResult = encoding.GetBytes(m_data);
                model.SaveChanges();
                //FREE MEMORY
                model.Dispose();
                niktoParser = null;
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "JobID:" + jobID + "Exception UpdateJob = " + ex.Message + " " + ex.InnerException);
            }

            Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "JobID:" + jobID + "Leaving Run()");
        }
Esempio n. 30
0
        public void parse()
        {
            Assembly a;

            a = Assembly.GetExecutingAssembly();

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Assembly location = " + a.Location);

            // ============================================
            // Parse the Document and populate the database
            // ============================================

            XORCISMEntities model;

            model = new XORCISMEntities();



            string ipAddress;

            ipAddress = "";
            string protocol = "WWW";  //Hardcoded
            int    port     = 80;

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("Handling host with IP {0}", ipAddress));

            // =============================================
            // If necessary, create an asset in the database
            // =============================================
            //TODO
            var myass = from ass in model.ASSET
                        where ass.ipaddressIPv4 == ipAddress //&& ass.AccountID == m_AccountID
                        select ass;
            ASSET asset = myass.FirstOrDefault();

            if (asset == null)
            {
                Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Creates a new entry in table ASSET for this IP");

                asset = new ASSET();
                //asset.AccountID = m_AccountID;
                asset.AssetName        = ipAddress;
                asset.AssetDescription = ipAddress;
                asset.ipaddressIPv4    = ipAddress;
                asset.Enabled          = true;
                //asset.JobID = m_JobId;

                model.ASSET.Add(asset);
                model.SaveChanges();
            }
            else
            {
                Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "This IP already corresponds to an existing asset");
            }

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Creating ASSETINSESSION reference");
            ASSETSESSION assinsess = new ASSETSESSION();

            assinsess.AssetID   = asset.AssetID;
            assinsess.SessionID = model.JOB.Single(x => x.JobID == m_JobId).SessionID;
            model.ASSETSESSION.Add(assinsess);
            model.SaveChanges();

            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", "Update JOB with ASSETINSESSIONID");
            JOB daJob = model.JOB.Single(x => x.JobID == m_JobId);

            daJob.AssetSessionID = assinsess.AssetSessionID;
            model.SaveChanges();


            //**************************
            StreamReader monStreamReader = new StreamReader("samples.js");  //Hardcoded
            string       curline         = monStreamReader.ReadLine();
            bool         issue_samples   = false;
            int          currentseverity = 0;
            string       curvulntype     = "";

            while (curline != null)
            {
                if (issue_samples)
                {
                    if (curline.Contains("'url':"))
                    {
                        Console.WriteLine(curvulntype);
                        Console.WriteLine(vulntypeSkipfish(curvulntype));
                        curline = curline.Trim();
                        char[]   splitter1 = { ',' };
                        string[] words1    = curline.Split(splitter1);
                        string   vulnurl   = words1[0].Replace("{ 'url': '", "");
                        vulnurl = vulnurl.Substring(0, vulnurl.Length - 1);
                        Console.WriteLine(vulnurl);
                        string vulnparam = words1[1].Replace("'extra': '", "");
                        vulnparam = vulnparam.Substring(0, vulnparam.Length - 1).Trim();
                        Console.WriteLine(vulnparam);
                        string vulninfodir = words1[2].Replace("'dir': '", "");
                        vulninfodir = vulninfodir.Replace("' } ]", "");
                        vulninfodir = vulninfodir.Replace("' }", "").Trim();
                        Console.WriteLine(vulninfodir);

                        if (currentseverity > 0)
                        {
                            VulnerabilityEndPoint vulnerabilityEndPoint = new VulnerabilityEndPoint();
                            vulnerabilityEndPoint.IpAdress = ipAddress;
                            vulnerabilityEndPoint.Protocol = protocol;
                            vulnerabilityEndPoint.Port     = port;

                            VulnerabilityFound vulnerabilityFound = new VulnerabilityFound();
                            //vulnerabilityFound.PatchUpgrade = PatchUpgrade;
                            //vulnerabilityFound.MSPatch = MSPatch;
                            vulnerabilityFound.Title    = vulntypeSkipfish(curvulntype);
                            vulnerabilityFound.Severity = currentseverity.ToString();
                            vulnerabilityFound.Url      = vulnurl;
                            //vulnerabilityFound.rawrequest=    vulninfodir+"/request.dat";
                            //vulnerabilityFound.rawresponse=   vulninfodir+"/response.dat";
                            vulnerabilityFound.Result = vulnparam;


                            // ===========
                            // Persistance
                            // ===========

                            Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("Persistance [{0}] [{1}] [{2}]", protocol, port, Helper_ListCVEToString(vulnerabilityFound.ListItem)));

                            int etat = VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, m_JobId, "skipfish", model);
                            if (etat == -1)
                            {
                                Utils.Helper_Trace("XORCISM PROVIDER SkipfishImport", string.Format("CANNOT IMPORT THIS ASSET !!!! "));
                            }
                        }
                        else
                        {
                            //TODO

                            /*
                             * //severity=0
                             * INFORMATION myinfo = new INFORMATION();
                             * myinfo.Title = vulntypeSkipfish(curvulntype);
                             * myinfo.Severity = currentseverity.ToString();
                             * myinfo.Url = vulnurl;
                             * //myinfo.rawrequest=    vulninfodir+"/request.dat";
                             * //myinfo.rawresponse=   vulninfodir+"/response.dat";
                             * myinfo.Result = vulnparam;
                             * myinfo.JobID = m_JobId;
                             *
                             * model.AddToINFORMATION(myinfo);
                             * model.SaveChanges();
                             */
                        }
                    }
                }

                if (curline.Contains("'severity': 4"))
                {
                    currentseverity = 4;
                    char[]   splitter1 = { ',' };
                    string[] words1    = curline.Split(splitter1);
                    curvulntype = words1[1].Replace(" 'type': ", "");
                }
                if (curline.Contains("'severity': 3"))
                {
                    currentseverity = 3;
                    char[]   splitter1 = { ',' };
                    string[] words1    = curline.Split(splitter1);
                    curvulntype = words1[1].Replace(" 'type': ", "");
                }
                if (curline.Contains("'severity': 2"))
                {
                    currentseverity = 2;
                    char[]   splitter1 = { ',' };
                    string[] words1    = curline.Split(splitter1);
                    curvulntype = words1[1].Replace(" 'type': ", "");
                }
                if (curline.Contains("'severity': 1"))
                {
                    currentseverity = 1;
                    char[]   splitter1 = { ',' };
                    string[] words1    = curline.Split(splitter1);
                    curvulntype = words1[1].Replace(" 'type': ", "");
                }
                if (curline.Contains("'severity': 0"))
                {
                    currentseverity = 0;
                    char[]   splitter1 = { ',' };
                    string[] words1    = curline.Split(splitter1);
                    curvulntype = words1[1].Replace(" 'type': ", "");
                }
                //Where am I?
                if (curline.Contains("var issue_samples"))
                {
                    issue_samples = true;

                    /*
                     * ligne = ligne.Trim();
                     * char[] splitter1 = { ' ' };
                     * string[] words1 = ligne.Split(splitter1);
                     *
                     * cmd1 = "./msfcli " + words1[0].Trim() + " T";
                     */
                }
                curline = monStreamReader.ReadLine();
            }

            monStreamReader.Close();



            // A VOIR
            // VulnerabilityPersistor.UpdateVulnerabilityJob(list_vulnerabilyFound,m_JobId,m_model);
        }