Пример #1
0
        public void Test_ASSETWithDataIsValid()
        {
            ASSET asset = new ASSET();

            asset.ROLE            = "myRole";
            asset.ASSET_TYPE      = "myRole";
            asset.HOST_NAME       = "myRole";
            asset.HOST_IP         = "myRole";
            asset.HOST_MAC        = "myRole";
            asset.HOST_FQDN       = "myRole";
            asset.TECH_AREA       = "myRole";
            asset.TARGET_KEY      = "myRole";
            asset.WEB_OR_DATABASE = "myRole";
            asset.WEB_DB_SITE     = "myRole";
            asset.WEB_DB_INSTANCE = "myRole";

            // test things out
            Assert.True(asset != null);
            Assert.True(!string.IsNullOrEmpty(asset.ROLE));
            Assert.True(!string.IsNullOrEmpty(asset.ASSET_TYPE));
            Assert.True(!string.IsNullOrEmpty(asset.HOST_NAME));
            Assert.True(!string.IsNullOrEmpty(asset.HOST_IP));
            Assert.True(!string.IsNullOrEmpty(asset.HOST_MAC));
            Assert.True(!string.IsNullOrEmpty(asset.HOST_FQDN));
            Assert.True(!string.IsNullOrEmpty(asset.TECH_AREA));
            Assert.True(!string.IsNullOrEmpty(asset.TARGET_KEY));
            Assert.True(!string.IsNullOrEmpty(asset.WEB_OR_DATABASE));
            Assert.True(!string.IsNullOrEmpty(asset.WEB_DB_SITE));
            Assert.True(!string.IsNullOrEmpty(asset.WEB_DB_INSTANCE));
        }
Пример #2
0
        public void SimpleTest()
        {
            var newAsset = new ASSET();

            newAsset.ID                = DateTime.Now.Ticks;
            newAsset.SYNC_USER_ID      = 1;
            newAsset.SYNC_SOURCE_ID    = Guid.NewGuid().ToString();
            newAsset.SYNC_DATE         = DateTime.Now;
            newAsset.LAST_UPDATED_DATE = DateTime.Now;
            newAsset.NAME              = "Tai san test";
            newAsset.ASSET_TYPE_ID     = 2;
            newAsset.UNIT_ID           = 1;
            newAsset.CODE              = "1";
            newAsset.ASSET_CATEGORY_ID = 1;


            newAsset.NPA.LAND.AREA          = 10000;
            newAsset.OA.HOUSE.AREA_BUILDING = 20000;

            _dbContext.ASSETS.Add(newAsset);
            _dbContext.SaveChanges();

            var findAsset = _dbContext.ASSETS.FirstOrDefault(x => x.ID == newAsset.ID);

            Assert.IsNotNull(findAsset);
            Assert.AreEqual(findAsset.NPA.LAND.AREA, 10000);
            Assert.AreEqual(findAsset.OA.HOUSE.AREA_BUILDING, 20000);
        }
        private void ToolStripBtnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this record?", "DELETE ASSET?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var assno = Convert.ToString(this.dgvAllAssets.CurrentRow.Cells["ASSETNO"].Value);
                //delete image if any.

                DeleteImage(assno);

                //delete finance attatched to the asset

                DeleteAssetFinance(assno);

                using (AccetManagementEntities db = new AccetManagementEntities())
                {
                    var empname = db.VIEWALLASSETS.Where(x => x.ASSETNO == assno).Select(x => x.EMPNAME).FirstOrDefault();
                    if (empname == "" || empname == null)
                    {
                        int rows = dgvAllAssets.RowCount;
                        for (int i = rows - 1; i >= 0; i--)
                        {
                            if (dgvAllAssets.Rows[i].Selected)
                            {
                                iEWALLASSET.ASSETNO = assno;
                                iEWALLASSET         = db.ASSETs.Where(x => x.ASSETNO == iEWALLASSET.ASSETNO).FirstOrDefault();

                                var entry = db.Entry(iEWALLASSET);

                                if (entry.State == EntityState.Unchanged)
                                {
                                    db.ASSETs.Attach(iEWALLASSET);
                                    db.ASSETs.Remove(iEWALLASSET);
                                    db.SaveChanges();
                                    LoadGrid();

                                    if (dgvAllAssets.CurrentRow == null)
                                    {
                                        MessageBox.Show("All Items deleted successfully");
                                    }
                                    else
                                    {
                                        dgvAllAssets.Rows[0].Selected = false;
                                    }
                                }

                                //db.VIEWALLASSETS.Remove(dgvAllAssets.Rows[i].DataBoundItem as VIEWALLASSET);
                                //vIEWALLASSETBindingSource.RemoveAt(dgvAllAssets.Rows[i].Index);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("This particular Item cannot be deleted because it's been assigned to an Employee  " + empname
                                        + "  CheckIn the Item first for it to be deleted");
                    }
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Take the ASSET XML node in here and parse to fill in the checklist.
        /// </summary>
        /// <param name="node">The XML node for the ASSET XML structure</param>
        /// <returns>
        /// The ASSET record matching the XML to the C# class structure for including
        /// into the larger CHECKLIST structure to use.
        /// </returns>
        private static ASSET getAssetListing(XmlNode node)
        {
            ASSET asset = new ASSET();

            foreach (XmlElement child in node.ChildNodes)
            {
                switch (child.Name)
                {
                case "ROLE":
                    asset.ROLE = child.InnerText;
                    break;

                case "ASSET_TYPE":
                    asset.ASSET_TYPE = child.InnerText;
                    break;

                case "HOST_NAME":
                    asset.HOST_NAME = child.InnerText;
                    break;

                case "HOST_IP":
                    asset.HOST_IP = child.InnerText;
                    break;

                case "HOST_MAC":
                    asset.HOST_MAC = child.InnerText;
                    break;

                case "HOST_FQDN":
                    asset.HOST_FQDN = child.InnerText;
                    break;

                case "TECH_AREA":
                    asset.TECH_AREA = child.InnerText;
                    break;

                case "TARGET_KEY":
                    asset.TARGET_KEY = child.InnerText;
                    break;

                case "WEB_OR_DATABASE":
                    asset.WEB_OR_DATABASE = child.InnerText;
                    break;

                case "WEB_DB_SITE":
                    asset.WEB_DB_SITE = child.InnerText;
                    break;

                case "WEB_DB_INSTANCE":
                    asset.WEB_DB_INSTANCE = child.InnerText;
                    break;
                }
            }
            return(asset);
        }
Пример #5
0
        public ASSET MapMetadataToAsset(ASSET asset, UserMetadata userInfo)
        {
            //var asset = new ASSET()
            //{
            asset.COMPUTER_NAME     = userInfo.ComputerName;
            asset.MANUFACTURER      = userInfo.ManufacturerName;
            asset.SERIAL_NUM        = userInfo.SerialNumber;
            asset.BARCODE           = userInfo.Barcode;
            asset.MODEL             = userInfo.Model;
            asset.LAST_UPDATED      = DateTime.Now;
            asset.DATETIME_ASSIGNED = DateTime.Now;
            //};

            return(asset);
        }
Пример #6
0
 public Object GetAsset(ASSET resource)
 {
     switch (resource)
     {
         case ASSET.FIGHTER_LODGROUP:
             return fighterLODGroup;
         case ASSET.FRIGATE_LODGROUP:
             return frigateLODGroup;
         case ASSET.TEAM_BLUE_MATERIAL:
             return blueTeamMaterial;
         case ASSET.TEAM_RED_MATERIAL:
             return redTeamMaterial;
         default:
             throw new UnityException();
     }
 }
Пример #7
0
        public void MappingTest()
        {
            try
            {
                var config = new MapperConfiguration(cfg =>
                {
                    //cfg.CreateMap<Foo, Bar>();
                    cfg.AddProfile <MyProfile>();
                    cfg.AddProfile <MyProfile2>();

                    cfg.CreateMap <Level1Source, Level1Destination>();
                    cfg.CreateMap <Level2Source, Level2Destination>();
                    cfg.CreateMap <Level3Source, Level3Destination>();

                    cfg.CreateMap <Level1Source, Destination>();
                });
                var mapper = config.CreateMapper();

                var source = new ASSET();
                source.ID = 123456;
                source.NPA.LAND.ADDRESS  = "AAAAA";
                source.ASSET_CATEGORY_ID = 1;
                var destination = mapper.Map <AssetNpaLandDetailDto>(source);

                Assert.AreEqual(source.ASSET_CATEGORY_ID, destination.AssetCategoryId);

                var dest2 = mapper.Map <ASSET>(destination);

                //var levelSource = new Level1Source();
                //levelSource.Level2 = new Level2Source();
                //levelSource.Level2.Level3 = new Level3Source();
                //levelSource.Level2.Level3.Value = "ABC";

                //var levelDestination = mapper.Map<Level1Destination>(levelSource);

                //var destination = mapper.Map<Destination>(levelSource);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #8
0
    public Object GetAsset(ASSET resource)
    {
        switch (resource)
        {
        case ASSET.FIGHTER_LODGROUP:
            return(fighterLODGroup);

        case ASSET.FRIGATE_LODGROUP:
            return(frigateLODGroup);

        case ASSET.TEAM_BLUE_MATERIAL:
            return(blueTeamMaterial);

        case ASSET.TEAM_RED_MATERIAL:
            return(redTeamMaterial);

        default:
            throw new UnityException();
        }
    }
Пример #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);
        }
Пример #10
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 !!!! "));
                        }
                    }
                }
            }
        }
Пример #11
0
        static void Main(string[] args)
        {
            //Recuperar ruta de directorio donde se guardaran los logs para crearla si no existe
            string path = ConfigurationManager.AppSettings["DirectorioLogs"];

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            //Información para los Logs
            //Sea A = El conjunto de activos de Maximo
            //Sea B = El Conjunto de Activos de ChevyStar

            //Indicador de proceso
            Console.WriteLine("Procesando información de ChevyStar...");

            //Fecha actual para los logs
            var fecha = DateTime.Now.ToString("yyyy-MM-dd");

            //Línea de código para tratar la conversión de string a decimal en el formato que lo envía chevystar
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            //Invocamos el servicio de ChevyStar
            ChevyStarService.OnlineSoapClient CSClient = new ChevyStarService.OnlineSoapClient();

            //Información de logeo
            ChevyStarService.LoginInfo Credentials = new ChevyStarService.LoginInfo();
            Credentials.Company  = ConfigurationManager.AppSettings["company"];
            Credentials.Username = ConfigurationManager.AppSettings["user"];
            Credentials.Password = ConfigurationManager.AppSettings["pass"];

            string content = string.Empty;

            try
            {
                //Obtener los activos sincronizados con chevystar y con con medidor, por medio de una petición http con protocolo TLS 1.2
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                    ConfigurationManager.AppSettings["UrlRESTMaximo"] +
                    ConfigurationManager.AppSettings["RAEO_ACTIVOSCHEV"] +
                    ConfigurationManager.AppSettings["credencialesMaximo"] +
                    ConfigurationManager.AppSettings["Query1"]);
                request.Method = "GET";
                //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 58.0.3029.110 Safari / 537.36";
                request.UserAgent = "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 71.0.3578.98 Safari / 537.36";
                request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                //Esta línea es para poner de acuerdo esta aplicación con el RESTService de maximo en cuanto al protocolo de comunicación seguro dado que es https
                ServicePointManager.Expect100Continue           = true;
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                HttpResponseMessage response = new HttpResponseMessage();

                using (HttpClient client = new HttpClient())
                {
                    var url = ConfigurationManager.AppSettings["UrlRESTMaximo1"] +
                              ConfigurationManager.AppSettings["RAEO_ACTIVOSCHEV"] +
                              ConfigurationManager.AppSettings["credencialesMaximo"] +
                              ConfigurationManager.AppSettings["Query1"];

                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

                    response = client.GetAsync(url).Result;
                }


                using (Stream stream = response.Content.ReadAsStreamAsync().Result)
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        content = sr.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            //Espacio de nombres para leer los nodos XML
            XNamespace headNameSpace = ConfigurationManager.AppSettings["headNameSpace"];
            //Mapear la respuesta en los objetos modelo que guardarán la información necesaria
            XDocument doc = XDocument.Parse(content);

            var documento = doc.Descendants(headNameSpace + "ASSET");

            //Obtener listado de activos
            try
            {
                List <ASSET> ASSETS = new List <ASSET>();

                /* List<ASSET> ASSETS = (from ASSET in documento
                 *                     select new ASSET()
                 *                     {
                 *                         ASSETNUM = ASSET.Descendants(headNameSpace + "ASSETNUM").FirstOrDefault().Value,
                 *                         RAULTIMAMEDICION = Convert.ToDouble(ASSET.Descendants(headNameSpace + "ASSETMETER").FirstOrDefault().Descendants(headNameSpace + "LASTREADING").FirstOrDefault().Value)
                 *                     }).ToList();
                 */
                foreach (var item in documento)
                {
                    try
                    {
                        var nodokm = item.Descendants(headNameSpace + "ASSETMETER");
                        if (nodokm != null)
                        {
                            ASSET placa = new ASSET();
                            placa.ASSETNUM         = item.Descendants(headNameSpace + "ASSETNUM").FirstOrDefault().Value;
                            placa.RAULTIMAMEDICION = 0; //Convert.ToDouble(item.Descendants(headNameSpace + "ASSETMETER").FirstOrDefault().Descendants(headNameSpace + "LASTREADING").FirstOrDefault().Value);
                            Console.WriteLine(placa.ASSETNUM);
                            if (item.Descendants(headNameSpace + "ASSETMETER").FirstOrDefault() != null)
                            {
                                Console.WriteLine(Convert.ToDouble(item.Descendants(headNameSpace + "ASSETMETER").FirstOrDefault().Descendants(headNameSpace + "LASTREADING").FirstOrDefault().Value));
                            }
                            ASSETS.Add(placa);
                        }
                        Console.WriteLine("Proceso Ejecutado Satisfactoriamente");
                    }

                    catch (Exception e) {
                        Console.WriteLine("No se encontro odometro para esta placa");
                        continue;
                    }
                }
                #region log con archivos de los activos que se traen de Maximo (Conjunto A)
                // crear el path
                if (ConfigurationManager.AppSettings["LogActivosMaximo"] == "ACTIVO")
                {
                    var archivo = ConfigurationManager.AppSettings["DirectorioLogs"] + "LogActivosMaximo_" + fecha + ".txt";

                    // eliminar el fichero si ya existe
                    if (File.Exists(archivo))
                    {
                        File.Delete(archivo);
                    }

                    // crear el fichero y guardar los activos de la consulta de maximo
                    using (var fileStream = File.Create(archivo))
                    {
                        var Cabecera = new UTF8Encoding(true).GetBytes("ACTIVO          ÚLTIMA MEDICIÓN \n");
                        fileStream.Write(Cabecera, 0, Cabecera.Length);
                        foreach (var item in ASSETS)
                        {
                            var registro = new UTF8Encoding(true).GetBytes(item.ASSETNUM + "          " + item.RAULTIMAMEDICION + " \n");
                            fileStream.Write(registro, 0, registro.Length);
                        }
                        fileStream.Flush();
                        fileStream.Close();
                    }
                }

                #endregion

                //Obtener información de todos los vehículos de ChevyStar y guardarlo en una lista del modelo a enviar a maximo
                var todosLosVehiculos = CSClient.GetCarsInfo(Credentials).ToList();

                #region log con todos activos de ChevyStar (Conjunto B)
                // crear el path
                if (ConfigurationManager.AppSettings["LogActivosChevystar"] == "ACTIVO")
                {
                    var archivoChevystar = ConfigurationManager.AppSettings["DirectorioLogs"] + "LogActivosChevystar_" + fecha + ".txt";

                    // eliminar el fichero si ya existe
                    if (File.Exists(archivoChevystar))
                    {
                        File.Delete(archivoChevystar);
                    }

                    // crear el fichero y guardar los activos de la consulta de ChevyStar
                    using (var fileStream = File.Create(archivoChevystar))
                    {
                        var Cabecera = new UTF8Encoding(true).GetBytes("ACTIVO          ÚLTIMA MEDICIÓN \n");
                        fileStream.Write(Cabecera, 0, Cabecera.Length);
                        foreach (var item in todosLosVehiculos)
                        {
                            //Separar en un array la cadena concatenada por #
                            var ArrayVehicle_Tool_Tip = item.Vehicle_Tool_Tip.Split('#');

                            //Obtener el elemento del array que tenga Kilometros

                            double Kilometros = Convert.ToDouble(Array.Find(ArrayVehicle_Tool_Tip, (x => x.Contains(ConfigurationManager.AppSettings["CampoCriterio1"]))).Split('=')[1]);
                            var    registro   = new UTF8Encoding(true).GetBytes(item.Vehicle_Label + "          " + Kilometros + " \n");
                            fileStream.Write(registro, 0, registro.Length);
                        }
                        //Escribir los bytes
                        fileStream.Flush();
                        //Cerrar la transacción una vez completada
                        fileStream.Close();
                    }
                }

                #endregion

                //Lista de mediciones(Kilómetros) a enviar a maximo
                List <METERDATA> MedicionesAEnviar = new List <METERDATA>();

                //Listado de activos de maximo
                List <string> TodosActivosMaximo    = ASSETS.Select(x => x.ASSETNUM).ToList <string>();
                List <string> TodosActivosChevystar = todosLosVehiculos.Select(x => x.Vehicle_Label).ToList <string>();

                //Activos filtrados de ambos conjuntos A-B  y B-A
                List <string> ActivosChevystarNoEncontrados = TodosActivosChevystar.Except(TodosActivosMaximo).ToList <string>();
                List <string> ActivosMaximoNoEncontrados    = TodosActivosMaximo.Except(TodosActivosChevystar).ToList <string>();

                var archivoMaximoNo    = ConfigurationManager.AppSettings["DirectorioLogs"] + "LogActivosMaximoNoEncontrados_" + fecha + ".txt";
                var archivoChevystarNo = ConfigurationManager.AppSettings["DirectorioLogs"] + "LogActivosChevystarNoEncontrados_" + fecha + ".txt";

                List <ASSET> MedicionesErroneas         = new List <ASSET>();
                List <ASSET> ActivosMasDeDoceCaracteres = new List <ASSET>();

                //Detectar que activos de chevystar poseen mas de doce caracteres
                foreach (var item in TodosActivosChevystar)
                {
                    if (item.Length > 12)
                    {
                        ActivosMasDeDoceCaracteres.Add(new ASSET()
                        {
                            ASSETNUM = item
                        });
                    }
                }

                //Validación de longitud de caracteres del activos que viene de chevystar Se logea la placa que se amayor a 12 caracteres (Longitud de ASSETNUM en maximo)


                //Armar la lista de mediciones a enviar a maximo Por activo Sincronizado
                foreach (var item in ASSETS)
                {
                    bool activoEncontrado = todosLosVehiculos.Exists(x => x.Vehicle_Label == item.ASSETNUM);

                    //Filtrar los datos de chevystar de modo que solo se envíen las mediciones de activos que existen en maximo (Hacer Match)
                    var vehiculo = todosLosVehiculos.FirstOrDefault(x => x.Vehicle_Label == item.ASSETNUM);

                    if (vehiculo != null)
                    {
                        //Separar en un array la cadena concatenada por #
                        var ArrayVehicle_Tool_Tip = vehiculo.Vehicle_Tool_Tip.Split('#');

                        //Obtener el elemento del array que tenga Kilometros
                        double Kilometros = Convert.ToDouble(Array.Find(ArrayVehicle_Tool_Tip, (x => x.Contains(ConfigurationManager.AppSettings["CampoCriterio1"]))).Split('=')[1]);

                        //Si la medición viene de chevystar con valores negativos o fuera del rango 0 a 999999 entonces se guarda en la lista de activos con errores y no se envía medición a Maximo
                        if (Kilometros < 0 && Kilometros >= 999999)
                        {
                            MedicionesErroneas.Add(new ASSET()
                            {
                                ASSETNUM = vehiculo.Vehicle_Label, RAULTIMAMEDICION = Kilometros
                            });
                        }
                        else
                        {
                            //Verificar si la medición obtenida de chevystar es mayor a la ultima registrada para realizar la petición, de lo contrario la petición no de efectua.
                            if (item.RAULTIMAMEDICION < Kilometros)
                            {
                                MedicionesAEnviar.Add(new METERDATA()
                                {
                                    ASSETNUM   = item.ASSETNUM,
                                    METERNAME  = ConfigurationManager.AppSettings["MEDIDOR"],
                                    NEWREADING = Kilometros,
                                    SITEID     = ConfigurationManager.AppSettings["SITEID"]
                                });
                            }
                        }
                    }
                }

                #region Logear activos de chevystar con errores en la medición

                var archivoActivosErroneos = ConfigurationManager.AppSettings["DirectorioLogs"] + "ActivosErroneos" + fecha + ".txt";

                // eliminar el fichero si ya existe
                if (File.Exists(archivoActivosErroneos))
                {
                    File.Delete(archivoActivosErroneos);
                }

                // crear el fichero y guardar los activos con mediciones erroneas
                using (var fileStream = File.Create(archivoActivosErroneos))
                {
                    var Texto = new UTF8Encoding(true).GetBytes("Los siguientes activos presentaron mediciones por fuera del rango 0 a 999999 \n");
                    fileStream.Write(Texto, 0, Texto.Length);
                    var Cabecera = new UTF8Encoding(true).GetBytes("ACTIVO      MEDICIÓN \n");
                    fileStream.Write(Cabecera, 0, Cabecera.Length);
                    foreach (var medicionError in MedicionesErroneas)
                    {
                        var registro = new UTF8Encoding(true).GetBytes(medicionError.ASSETNUM + "       " + medicionError.RAULTIMAMEDICION + " \n");
                        fileStream.Write(registro, 0, registro.Length);
                    }
                    //Escribir los bytes
                    fileStream.Flush();
                    //Cerrar la transacción una vez completada
                    fileStream.Close();
                }

                #endregion

                #region Log de activos de chevystar con mas de doce caracteres

                var ActivosPlacaErronea = ConfigurationManager.AppSettings["DirectorioLogs"] + "ActivosPlacaErronea" + fecha + ".txt";

                // eliminar el fichero si ya existe
                if (File.Exists(ActivosPlacaErronea))
                {
                    File.Delete(ActivosPlacaErronea);
                }

                // crear el fichero y guardar los activos de placa erronea
                using (var fileStream = File.Create(ActivosPlacaErronea))
                {
                    var Texto = new UTF8Encoding(true).GetBytes("Los siguientes activos presentaron placas por encima de doce caracteres (No se ingresaron a Maximo estas mediciones) \n");
                    fileStream.Write(Texto, 0, Texto.Length);
                    var Cabecera = new UTF8Encoding(true).GetBytes("ACTIVO \n");
                    fileStream.Write(Cabecera, 0, Cabecera.Length);
                    foreach (var ActivoDoce in ActivosMasDeDoceCaracteres)
                    {
                        var registro = new UTF8Encoding(true).GetBytes(ActivoDoce.ASSETNUM + " \n");
                        fileStream.Write(registro, 0, registro.Length);
                    }
                    //Escribir los bytes
                    fileStream.Flush();
                    //Cerrar la transacción una vez completada
                    fileStream.Close();
                }

                #endregion

                #region Log de activos de Chevistar que no hicieron match (Conjunto B-A)
                if (ConfigurationManager.AppSettings["LogActivosChevystarNoEncontrados"] == "ACTIVO")
                {
                    // eliminar el fichero si ya existe
                    if (File.Exists(archivoChevystarNo))
                    {
                        File.Delete(archivoChevystarNo);
                    }

                    // crear el fichero y guardar los activos de la consulta de ChevyStar
                    using (var fileStream = File.Create(archivoChevystarNo))
                    {
                        var Cabecera = new UTF8Encoding(true).GetBytes("ACTIVO \n");
                        fileStream.Write(Cabecera, 0, Cabecera.Length);
                        foreach (var itemChevNo in ActivosChevystarNoEncontrados)
                        {
                            var registro = new UTF8Encoding(true).GetBytes(itemChevNo + " \n");
                            fileStream.Write(registro, 0, registro.Length);
                        }
                        //Escribir los bytes
                        fileStream.Flush();
                        //Cerrar la transacción una vez completada
                        fileStream.Close();
                    }
                }

                #endregion

                #region Log de activos de maximo que no hicieron match (Conjunto A-B)

                if (ConfigurationManager.AppSettings["LogActivosMaximoNoEncontrados"] == "ACTIVO")
                {
                    // eliminar el fichero si ya existe
                    if (File.Exists(archivoMaximoNo))
                    {
                        File.Delete(archivoMaximoNo);
                    }

                    // crear el fichero y guardar los activos de la consulta de ChevyStar
                    using (var fileStream = File.Create(archivoMaximoNo))
                    {
                        var Cabecera = new UTF8Encoding(true).GetBytes("ACTIVO \n");
                        fileStream.Write(Cabecera, 0, Cabecera.Length);
                        foreach (var itemMaximoNo in ActivosMaximoNoEncontrados)
                        {
                            var registro = new UTF8Encoding(true).GetBytes(itemMaximoNo + " \n");
                            fileStream.Write(registro, 0, registro.Length);
                        }
                        //Escribir los bytes
                        fileStream.Flush();
                        //Cerrar la transacción una vez completada
                        fileStream.Close();
                    }
                }

                #endregion

                #region Log CSV de archivo con las mediciones que se fueron a maximo (Conjunto A ∩ B)

                if (ConfigurationManager.AppSettings["LogActivosMaximoNoEncontrados"] == "ACTIVO")
                {
                    //Ruta de acceso para el archivo de contingencia
                    var archivoMeterData = ConfigurationManager.AppSettings["DirectorioLogs"] + "LogMedicionesAMaximo_" + fecha + ".csv";

                    // eliminar el fichero si ya existe
                    if (File.Exists(archivoMeterData))
                    {
                        File.Delete(archivoMeterData);
                    }

                    //Generar un csv de contingnecia con la información a enviar a maximo
                    using (var fileStream = File.Create(archivoMeterData))
                    {
                        var Cabecera = new UTF8Encoding(true).GetBytes("ASSETNUM;METERNAME;NEWREADING;SITEID \n");
                        fileStream.Write(Cabecera, 0, Cabecera.Length);
                        foreach (var item in MedicionesAEnviar)
                        {
                            var registro = new UTF8Encoding(true).GetBytes(item.ASSETNUM + ";" + item.METERNAME + ";" + item.NEWREADING + ";" + item.SITEID + " \n");
                            fileStream.Write(registro, 0, registro.Length);
                        }
                        fileStream.Flush();
                        fileStream.Close();
                    }
                }

                #endregion

                foreach (var item in MedicionesAEnviar)
                {
                    try
                    {
                        //realizar petición POST a MAXIMO para guardar los kilometrajes en el activo respectivo
                        HttpWebRequest requestMaximo = (HttpWebRequest)WebRequest.Create(
                            ConfigurationManager.AppSettings["UrlRESTMaximo"] +
                            ConfigurationManager.AppSettings["MXMETERDATA"] +
                            ConfigurationManager.AppSettings["credencialesMaximo"] +
                            "&ASSETNUM=" + item.ASSETNUM + "&METERNAME=" +
                            ConfigurationManager.AppSettings["MEDIDOR"] +
                            "&NEWREADING=" + item.NEWREADING.ToString().Replace('.', ',') + "&SITEID=" + "RTAM");

                        //Console.WriteLine(item.NEWREADING.ToString().Replace('.', ','));
                        //ConfigurationManager.AppSettings["SITEID"]);

                        requestMaximo.Method    = "POST";
                        requestMaximo.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 58.0.3029.110 Safari / 537.36";
                        requestMaximo.AutomaticDecompression            = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                        HttpWebResponse responseMaximo = (HttpWebResponse)requestMaximo.GetResponse();
                    }
                    catch (Exception e)
                    {
                        using (var fileStream = File.Create(archivoActivosErroneos))
                        {
                            var Texto = new UTF8Encoding(true).GetBytes(e.Message);
                            fileStream.Write(Texto, 0, Texto.Length);
                            //Escribir los bytes
                            fileStream.Flush();
                            //Cerrar la transacción una vez completada
                            fileStream.Close();
                        }
                    }
                }

                Environment.Exit(1);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #12
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 !!!! "));
                    }
                }
            }
        }
Пример #13
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var uc = new UserController();

            var currentTime = DateTime.Now;

            using (var context = new CarContext())
            {
                var userInfo   = ApplicationState.GetValue <UserMetadata>("Metadata");
                var asset      = uc.GetAssetInfo(context, userInfo.Barcode);
                var user       = uc.GetUserInfo(context, userInfo.BadgeNumber);
                var isNewAsset = false;

                if (asset == null)
                {
                    asset = new ASSET()
                    {
                        CREATED = DateTime.Now
                    };
                    isNewAsset = true;
                }

                uc.MapMetadataToAsset(asset, userInfo);
                //asset.APO_PCO_PIV_BADGE_NUM = 1;
                asset.DATETIME_RECEIVED = currentTime;

                if (isNewAsset)
                {
                    context.Assets.Add(asset);
                }

                if (user == null)
                {
                    user = uc.MapMetadataToUser(userInfo);
                    user.APO_PCO_PIV_BADGE_NUM = asset?.APO_PCO_PIV_BADGE_NUM;
                    user.BARCODE = asset?.BARCODE ?? userInfo.Barcode;// : asset.BARCODE;

                    user.DATETIME_ACCEPTED = currentTime;

                    if (asset?.STATE == "ASSIGNED")
                    {
                        user.OUTSTANDING_ASSET = false;
                    }
                    else if (asset?.STATE == "ASSIGNED_PENDING_RETURN")
                    {
                        user.OUTSTANDING_ASSET = true;
                        user.LAST_REMINDER     = currentTime.AddDays(5);
                    }

                    context.Users.Add(user);
                }
                else
                {
                    user.PREVIOUS_BARCODE      = user.BARCODE;
                    user.DATETIME_ACCEPTED     = currentTime;
                    user.BARCODE               = asset?.BARCODE;
                    user.APO_PCO_PIV_BADGE_NUM = asset?.APO_PCO_PIV_BADGE_NUM;
                    user.LAST_UPDATED          = currentTime;

                    if (asset.STATE == "ASSIGNED")
                    {
                        user.OUTSTANDING_ASSET = false;
                    }
                    else if (asset.STATE == "ASSIGNED_PENDING_RETURN")
                    {
                        user.OUTSTANDING_ASSET = true;
                        user.LAST_REMINDER     = currentTime.AddDays(5);
                    }

                    if (user.PREVIOUS_BARCODE.HasValue)
                    {
                        var oldAsset = uc.GetAssetInfo(context, user.PREVIOUS_BARCODE.Value);
                        oldAsset.STATE        = "AWAITING_RETURNED";
                        oldAsset.LAST_UPDATED = currentTime;
                    }
                }

                asset.STATE = "ACCEPTED";

                try
                {
                    context.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var eve in ex.EntityValidationErrors)
                    {
                        Console.WriteLine("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)
                        {
                            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                              ve.PropertyName, ve.ErrorMessage);
                        }
                    }
                    throw;
                }

                this.Close();
            }
        }
Пример #14
0
        public void InsertDataAsset()
        {
            var newAsset = new ASSET();

            newAsset.NPA.LAND.ADDRESS             = "haf nooi ";
            newAsset.NPA.LAND.AREA                = 1000000;
            newAsset.NPA.LAND.AREA_BUSINESS_USAGE = 10000;
            newAsset.NAME = "tài sản NPA Land";
            newAsset.ASSET_CATEGORY_ID = 1;
            newAsset.ASSET_TYPE_ID     = 21;
            newAsset.CODE           = "01";
            newAsset.SYNC_SOURCE_ID = "1";
            newAsset.SYNC_USER_ID   = 1;
            newAsset.UNIT_ID        = 1;
            newAsset.ID             = 10;
            _dbContext.ASSETS.Add(newAsset);



            var newAsset2 = new ASSET();

            newAsset2.NPA.HOUSE.NUMBER_OF_FLOOR            = 3200;
            newAsset2.NPA.HOUSE.AREA_BUILDING              = 5400;
            newAsset2.NPA.HOUSE.AREA_BUSINESS_USAGE        = 10000;
            newAsset2.NPA.HOUSE.AREA_FLOOR                 = 4000;
            newAsset2.NPA.HOUSE.AREA_HEADQUARTER_USAGE     = 300;
            newAsset2.NPA.HOUSE.AREA_HOUSE_USAGE           = 5000;
            newAsset2.NPA.HOUSE.AREA_WAREHOUSE_USAGE       = 1000;
            newAsset2.NPA.HOUSE.AREA_OTHER_USAGE           = 3000;
            newAsset2.NPA.HOUSE.AREA_TEMPORARY_HOUSE_USAGE = 100;
            newAsset2.NAME = "tài sản NPA House";
            newAsset2.ASSET_CATEGORY_ID = 1;
            newAsset2.ASSET_TYPE_ID     = 22;
            newAsset2.CODE           = "02";
            newAsset2.SYNC_SOURCE_ID = "1";
            newAsset2.SYNC_USER_ID   = 1;
            newAsset2.UNIT_ID        = 1;
            newAsset2.ID             = 11;
            _dbContext.ASSETS.Add(newAsset2);



            var newAsset3 = new ASSET();

            newAsset3.NPA.VEHICLE.BRAND_NAME                = "oto";
            newAsset3.NPA.VEHICLE.CAPACITY                  = "20000kg";
            newAsset3.NPA.VEHICLE.COUNTRY_OF_ORIGIN         = "hà nội";
            newAsset3.NPA.VEHICLE.REGISTRATION_PLATE_NUMBER = "s/n12234823646";
            newAsset3.NPA.VEHICLE.SIZE = 12;
            newAsset3.NPA.VEHICLE.VEHICLE_IDENTIFICATION_NUMBER = "a2sx3fje";
            newAsset3.NAME = "tài sản NPA Vehicle";
            newAsset3.ASSET_CATEGORY_ID = 2;
            newAsset3.ASSET_TYPE_ID     = 23;
            newAsset3.CODE           = "03";
            newAsset3.SYNC_SOURCE_ID = "1";
            newAsset3.SYNC_USER_ID   = 1;
            newAsset3.UNIT_ID        = 1107;
            newAsset3.ID             = 12;
            _dbContext.ASSETS.Add(newAsset3);

            var newAsset4 = new ASSET();

            newAsset4.NPA.OTHER_ASSET.BRAND_NAME        = "tài khản khác";
            newAsset4.NPA.OTHER_ASSET.SPECIFICATIONS    = "20000kg";
            newAsset4.NPA.OTHER_ASSET.COUNTRY_OF_ORIGIN = "hà nội";
            newAsset4.NPA.OTHER_ASSET.SERIAL_NUMBER     = "s/n12234823646";
            newAsset4.NPA.OTHER_ASSET.SUPPLIER          = "E.U";
            newAsset4.NAME = "tài sản NPA Other Asset";
            newAsset4.ASSET_CATEGORY_ID = 2;
            newAsset4.ASSET_TYPE_ID     = 24;
            newAsset4.CODE           = "04";
            newAsset4.SYNC_SOURCE_ID = "1";
            newAsset4.SYNC_USER_ID   = 1;
            newAsset4.UNIT_ID        = 1107;
            newAsset4.ID             = 13;
            _dbContext.ASSETS.Add(newAsset4);

            var newAsset5 = new ASSET();

            newAsset5.OA.LAND.ADDRESS             = "TP.HCM";
            newAsset5.OA.LAND.AREA                = 3000000;
            newAsset5.OA.LAND.AREA_BUSINESS_USAGE = 50000;
            newAsset5.OA.LAND.AREA_LEASE_USAGE    = 3000;
            newAsset5.NAME = "tài sản OA Land";
            newAsset5.ASSET_CATEGORY_ID = 1;
            newAsset5.ASSET_TYPE_ID     = 25;
            newAsset5.CODE           = "05";
            newAsset5.SYNC_SOURCE_ID = "1";
            newAsset5.SYNC_USER_ID   = 1;
            newAsset5.UNIT_ID        = 1;
            newAsset5.ID             = 14;
            _dbContext.ASSETS.Add(newAsset5);



            var newAsset6 = new ASSET();

            newAsset6.OA.HOUSE.AREA_BUILDING       = 10000;
            newAsset6.OA.HOUSE.AREA_BUSINESS_USAGE = 3000000;
            newAsset6.OA.HOUSE.AREA_FLOOR          = 50000;
            newAsset6.OA.HOUSE.AREA_OCCUPIED_USAGE = 3000;
            newAsset6.OA.HOUSE.NUMBER_OF_FLOOR     = 35000;
            newAsset6.NAME = "tài sản OA House";
            newAsset6.ASSET_CATEGORY_ID = 1;
            newAsset6.ASSET_TYPE_ID     = 26;
            newAsset6.CODE           = "06";
            newAsset6.SYNC_SOURCE_ID = "1";
            newAsset6.SYNC_USER_ID   = 1;
            newAsset6.UNIT_ID        = 1;
            newAsset6.ID             = 15;
            _dbContext.ASSETS.Add(newAsset6);


            var newAsset7 = new ASSET();

            newAsset7.OA.VEHICLE.BRAND_NAME                = "xe mới";
            newAsset7.OA.VEHICLE.CAPACITY                  = "N/A";
            newAsset7.OA.VEHICLE.COUNTRY_OF_ORIGIN         = "a";
            newAsset7.OA.VEHICLE.REGISTRATION_PLATE_NUMBER = "ssnab243df";
            newAsset7.OA.VEHICLE.SIZE = 30;
            newAsset7.OA.VEHICLE.VEHICLE_IDENTIFICATION_NUMBER = "a3cx5g56h";
            newAsset7.NAME = "tài sản OA VEHICLE";
            newAsset7.ASSET_CATEGORY_ID = 1;
            newAsset7.ASSET_TYPE_ID     = 27;
            newAsset7.CODE           = "07";
            newAsset7.SYNC_SOURCE_ID = "1";
            newAsset7.SYNC_USER_ID   = 1;
            newAsset7.UNIT_ID        = 1;
            newAsset7.ID             = 16;
            _dbContext.ASSETS.Add(newAsset7);


            var newAsset8 = new ASSET();

            newAsset8.OA.ABOVE_500M_ASSET.BRAND_NAME        = "tài sản trên 500m";
            newAsset8.OA.ABOVE_500M_ASSET.SERIAL_NUMBER     = "N/A";
            newAsset8.OA.ABOVE_500M_ASSET.COUNTRY_OF_ORIGIN = "a";
            newAsset8.OA.ABOVE_500M_ASSET.SPECIFICATIONS    = "ssnab243df";
            newAsset8.OA.ABOVE_500M_ASSET.SUPPLIER          = "China";
            newAsset8.NAME = "tài sản OA trên 500m";
            newAsset8.ASSET_CATEGORY_ID = 1;
            newAsset8.ASSET_TYPE_ID     = 28;
            newAsset8.CODE           = "08";
            newAsset8.SYNC_SOURCE_ID = "1";
            newAsset8.SYNC_USER_ID   = 1;
            newAsset8.UNIT_ID        = 1;
            newAsset8.ID             = 17;
            _dbContext.ASSETS.Add(newAsset8);



            var newAsset9 = new ASSET();

            newAsset9.OA.BELOW_500M_ASSET.BRAND_NAME        = "tài sản dưới 500m";
            newAsset9.OA.BELOW_500M_ASSET.SERIAL_NUMBER     = "N/A";
            newAsset9.OA.BELOW_500M_ASSET.COUNTRY_OF_ORIGIN = "a";
            newAsset9.OA.BELOW_500M_ASSET.SPECIFICATIONS    = "ssnab243df";
            newAsset9.OA.BELOW_500M_ASSET.SUPPLIER          = "China";
            newAsset9.NAME = "tài sản OA dưới 500m";
            newAsset9.ASSET_CATEGORY_ID = 1;
            newAsset9.ASSET_TYPE_ID     = 29;
            newAsset9.CODE           = "09";
            newAsset9.SYNC_SOURCE_ID = "1";
            newAsset9.SYNC_USER_ID   = 1;
            newAsset9.UNIT_ID        = 1;
            newAsset9.ID             = 18;
            _dbContext.ASSETS.Add(newAsset9);
            _dbContext.SaveChanges();
        }
Пример #15
0
        public void Test_NewASSETIsValid()
        {
            ASSET asset = new ASSET();

            Assert.True(asset != null);
        }
Пример #16
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);
        }
Пример #17
0
 public CHECKLIST()
 {
     ASSET = new ASSET();
     STIGS = new STIGS();
 }
Пример #18
0
            public void parse()
            {
                Assembly a;
                a = Assembly.GetExecutingAssembly();

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

                XmlDocument doc = new XmlDocument();

                #region HackCenzic
                /*
                string filename;
                filename = @"C:\Cenzic_webscan.xml";             //Hardcoded

                doc.Load(filename);

                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("HackFile should be located at : " + filename));
                */
                #endregion

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

                string protocol = string.Empty;
                //int port = -1;
                string service = string.Empty;
                //bool PatchUpgrade = false;
                //string title;
                //string MSPatch = "";
                //string Solution;

                m_data = m_data.Replace("Configurable format #", "Configurable");   //Hardcoded
                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("m_data = {0}", m_data));
                try
                {
                    Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "Loading the XML document");

                    doc.LoadXml(m_data);

                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message));
                }

                XORCISMEntities model;
                model = new XORCISMEntities();

                string query = "/AssessmentRunData/SmartAttacks/SmartAttacksData";  //Hardcoded

                XmlNodeList report;
                report = null;
                try
                {
                    report = doc.SelectNodes(query);
                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Error SelectNodes({0}) : Exception = {1}", query, ex.Message));
                    return;
                }

                //We should retrieve the target for an import
                string m_target = string.Empty;
                string patterntoken = "<Url>(.*?)</Url>";
                MatchCollection matchesurl = Regex.Matches(m_data, patterntoken);
                foreach (Match match in matchesurl)
                {
                    m_target = match.Value.Replace("<Url>", "").Replace("</Url>", "");
                    //Console.WriteLine(mytoken);
                    Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "target: " + m_target);
                }

                int myPort = 80;
                if (m_target.Contains("https://"))
                {
                    myPort = 443;
                }
                //Check if we have a custom port, ex: http://10.20.30.40:8080/test
                string strTargetTest = m_target;
                strTargetTest = strTargetTest.Replace("http://", "");
                strTargetTest = strTargetTest.Replace("https://", "");
                try
                {
                    if (strTargetTest.Contains(":"))
                    {
                        char[] splitter = { ':' };
                        string[] strSplit = strTargetTest.Split(splitter);
                        strTargetTest = strSplit[1];
                        if (strTargetTest.Contains("/"))
                        {
                            strSplit = strTargetTest.Split(new Char[] { '/' });
                            strTargetTest = strSplit[0];
                        }
                        try
                        {
                            myPort = Convert.ToInt32(strTargetTest);
                        }
                        catch (FormatException e)
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", strTargetTest + " is not a sequence of digits.");
                        }
                        Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Custom Port:{0}", strTargetTest));
                    }
                    else
                    {
                        if (strTargetTest.Contains("/"))
                        {
                            string[] strSplit = strTargetTest.Split(new Char[] { '/' });
                            strTargetTest = strSplit[0];
                            if (m_target.Contains("https://"))
                            {
                                m_target = "https://" + strTargetTest;
                            }
                            if (m_target.Contains("http://"))
                            {
                                m_target = "http://" + strTargetTest;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Error in strTargetTest : Exception = {0}", ex.Message));
                }

                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "the m_target=" + m_target);

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

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

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

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

                int m_assetId = asset.AssetID;
                int m_sessionId = (int)model.JOB.Single(x => x.JobID == m_jobId).SessionID;

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

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

                VulnerabilityEndPoint vulnerabilityEndPoint = new VulnerabilityEndPoint();
                vulnerabilityEndPoint.IpAdress = m_target;
                vulnerabilityEndPoint.Protocol = "TCP"; // "http";
                vulnerabilityEndPoint.Port = myPort;
                vulnerabilityEndPoint.Service = "WWW";

                int myEndpointID = 0;
                var testEndpoint = from e in model.ENDPOINT
                                   where e.AssetID == m_assetId && e.SessionID == m_sessionId
                                   select e;
                if (testEndpoint.Count() == 0)
                {
                    ENDPOINT newEndpoint = new ENDPOINT();
                    newEndpoint.AssetID = m_assetId;
                    newEndpoint.SessionID = m_sessionId;
                    newEndpoint.ProtocolName = "TCP"; // "http";
                    newEndpoint.PortNumber = myPort;
                    newEndpoint.Service = "WWW";
                    model.ENDPOINT.Add(newEndpoint);
                    model.SaveChanges();
                    myEndpointID = newEndpoint.EndPointID;
                }
                else
                {
                    myEndpointID = testEndpoint.FirstOrDefault().EndPointID;
                }
                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("myEndpointID:{0}", myEndpointID));

                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + m_jobId + " Found {0} SmartAttacks to parse", report.Count));

                foreach (XmlNode reportHost in report)
                {
                    // ==================================
                    // Handle every SmartAttacksData tag
                    // ==================================

                    string myInnerXml = string.Empty;
                    string myTitle = string.Empty;
                    string myDescription = string.Empty;
                    string myConsequence = string.Empty;
                    string myResult = string.Empty;
                    string mySolution = string.Empty;

                    string myCVE = string.Empty;
                    MatchCollection myCVEs;
                    string myPCI = string.Empty;
                    string myMessage = string.Empty;

                    foreach (XmlNode n in reportHost.ChildNodes)
                    {
                        //SmartAttackInfo
                        //ReportItems
                        XmlNodeList Childs = n.ChildNodes;

                        Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Coucou 1"));
                        try
                        {
                            if (n.Name == "SmartAttackInfo")
                            {
                                myInnerXml = n.OuterXml;
                                myTitle = HelperGetChildInnerText(n, "SmartAttackName");
                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + m_jobId + " Found SmartAttackName:{0}", myTitle));
                                Regex myRegex = new Regex("PCI [0-9].[0-9].[0-9]");

                                myPCI = myRegex.Match(myTitle).ToString();
                                if (myPCI != "")
                                {
                                    Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "PCI=" + myPCI);
                                }

                                //Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("myInnerXml:{0}", myInnerXml));
                                //Hardcoded
                                myDescription = HelperGetChildInnerText(n, "Description");
                                myConsequence = HelperGetChildInnerText(n, "HowItWorks");
                                myResult = HelperGetChildInnerText(n, "Impact");
                                mySolution = HelperGetChildInnerText(n, "Remediation");
                            }
                        }
                        catch (Exception ex)
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + m_jobId + " Error in SmartAttackInfo : Exception = {0}", ex.Message));
                        }
                        if (n.Name == "ReportItems")
                        {
                            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Coucou 2"));
                            foreach (XmlNode x in n.ChildNodes)
                            {
                                //HARDCODED
                                //ReportItem
                                foreach (XmlNode ReportItem in x.ChildNodes)
                                {
                                    myMessage = "";
                                    if (ReportItem.Name == "ReportItemType")
                                    {
                                        //Pass
                                        if (ReportItem.InnerText == "Information")
                                        {
                                            try
                                            {
                                                //TODO
                                                /*
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Information"));
                                                INFORMATION newInformation = new INFORMATION();
                                                //newInformation.InnerXml
                                                newInformation.Title = myTitle;
                                                newInformation.Description = myDescription;
                                                newInformation.Consequence = myConsequence;
                                                newInformation.Result = myResult;
                                                newInformation.Solution = mySolution;
                                                newInformation.Severity = HelperGetChildInnerText(x, "Severity");
                                                newInformation.HarmScore = int.Parse(HelperGetChildInnerText(x, "HarmScore"));
                                                myMessage = HelperGetChildInnerText(x, "Message");
                                                newInformation.Message = myMessage;
                                                //TODO A FAIRE
                                                //Matching avec les références
                                                //http://www.securityfocus.com/bid/43140/info
                                                //http://www.securityfocus.com/bid/43140/solution
                                                newInformation.Url = HelperGetChildInnerText(x, "Url");
                                                newInformation.rawrequest = HelperGetChildInnerText(x, "HttpRequest");
                                                newInformation.rawresponse = HelperGetChildInnerText(x, "HttpResponse");
                                                if (myPCI != "")
                                                {
                                                    newInformation.PCI_FLAG = true;
                                                }
                                                newInformation.JobID = m_jobId;
                                                newInformation.EndPointID = myEndpointID;
                                                model.AddToINFORMATION(newInformation);
                                                model.SaveChanges();
                                                */
                                            }
                                            catch (Exception ex)
                                            {
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + m_jobId + " Error in Information : Exception = {0}. {1}", ex.Message, ex.InnerException));
                                            }
                                        }
                                        if (ReportItem.InnerText == "Warning")
                                        {
                                            try
                                            {
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Warning"));
                                                VulnerabilityFound vulnerabilityFound = new VulnerabilityFound();
                                                vulnerabilityFound.InnerXml = myInnerXml;
                                                vulnerabilityFound.Title = myTitle;
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Adding SmartAttackName:{0}", myTitle));
                                                vulnerabilityFound.Description = myDescription;
                                                vulnerabilityFound.Consequence = myConsequence;
                                                vulnerabilityFound.Result = myResult;
                                                vulnerabilityFound.Solution = mySolution;

                                                if (myPCI != "")
                                                {
                                                    vulnerabilityFound.PCI_FLAG = true;
                                                }

                                                //ReportItemCreateDate
                                                vulnerabilityFound.Severity = HelperGetChildInnerText(x, "Severity");
                                                //Low, Medium, High
                                                //Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("WARNING Severity:{0}", HelperGetChildInnerText(x, "Severity")));
                                                vulnerabilityFound.HarmScore = int.Parse(HelperGetChildInnerText(x, "HarmScore"));
                                                //Count
                                                myMessage=HelperGetChildInnerText(x, "Message");
                                                //vulnerabilityFound.Message = myMessage; //not exact because same VULNERABILITY will have various Messages
                                                vulnerabilityFound.rawresponse = myMessage;

                                                    //Regex objNaturalPattern = 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,})");  //TODO: Update this?
                                                    //https://cve.mitre.org/cve/identifiers/tech-guidance.html
                                                    /*
                                                    myCVE = objNaturalPattern.Match(myMessage).ToString();
                                                    if (myCVE != "")
                                                    {
                                                        Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "CVE=" + myCVE);
                                                    }
                                                    */
                                                    List<VulnerabilityFound.Item> l;
                                                    l = new List<VulnerabilityFound.Item>();
                                                    myCVEs = myRegexCVE.Matches(myMessage);
                                                    foreach (Match match in myCVEs)
                                                    {
                                                        foreach (Capture capture in match.Captures)
                                                        {
                                                            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Index={0}, CVE={1}", capture.Index, capture.Value));
                                                            VulnerabilityFound.Item item;
                                                            item = new VulnerabilityFound.Item();
                                                            item.Value = capture.Value;
                                                            item.ID = "cve";
                                                            l.Add(item);
                                                        }
                                                    }
                                                    vulnerabilityFound.ListItem = l;

                                                vulnerabilityFound.Url = HelperGetChildInnerText(x, "Url");
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Url={0}", HelperGetChildInnerText(x, "Url")));
                                                vulnerabilityFound.rawrequest = HelperGetChildInnerText(x, "HttpRequest");
                                                //vulnerabilityFound.rawresponse = HelperGetChildInnerText(x, "HttpResponse");
                                                //StructuredData

                                                //*** Compliances? voir en bas
                                                //http://www.cenzic.com/downloads/Cenzic_CWE.pdf
                                                int VulnID = VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, m_jobId, "cenzic", model);
                                            }
                                            catch (Exception ex)
                                            {
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("JobID:" + m_jobId + " Error in Warning : Exception = {0}. {1}", ex.Message, ex.InnerException));
                                            }
                                        }
                                        if (ReportItem.InnerText == "Vulnerable")
                                        {
                                            try
                                            {
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Vulnerable"));
                                                VulnerabilityFound vulnerabilityFound = new VulnerabilityFound();
                                                vulnerabilityFound.InnerXml = myInnerXml;
                                                vulnerabilityFound.Title = myTitle;
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Adding SmartAttackName:{0}", myTitle));
                                                vulnerabilityFound.Description = myDescription;
                                                vulnerabilityFound.Consequence = myConsequence;
                                                vulnerabilityFound.Result = myResult;
                                                vulnerabilityFound.Solution = mySolution;

                                                //ReportItemCreateDate
                                                vulnerabilityFound.Severity = HelperGetChildInnerText(x, "Severity");
                                                //Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("VULNERABLE Severity:{0}", HelperGetChildInnerText(x, "Severity")));
                                                vulnerabilityFound.HarmScore = int.Parse(HelperGetChildInnerText(x, "HarmScore"));
                                                //Count
                                                myMessage = HelperGetChildInnerText(x, "Message");
                                                //vulnerabilityFound.Message = myMessage;
                                                vulnerabilityFound.rawresponse = myMessage;

                                                    //Regex objNaturalPattern = 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
                                                    /*
                                                    myCVE = objNaturalPattern.Match(myMessage).ToString();
                                                    if (myCVE != "")
                                                    {
                                                        Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "CVE=" + myCVE);
                                                    }
                                                    */

                                                    List<VulnerabilityFound.Item> l;
                                                    l = new List<VulnerabilityFound.Item>();
                                                    myCVEs = myRegexCVE.Matches(myMessage);
                                                    foreach (Match match in myCVEs)
                                                    {
                                                        foreach (Capture capture in match.Captures)
                                                        {
                                                            Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Index={0}, CVE={1}", capture.Index, capture.Value));
                                                            VulnerabilityFound.Item item;
                                                            item = new VulnerabilityFound.Item();
                                                            item.Value = capture.Value;
                                                            item.ID = "cve";
                                                            l.Add(item);
                                                        }
                                                    }
                                                    vulnerabilityFound.ListItem = l;

                                                vulnerabilityFound.Url = HelperGetChildInnerText(x, "Url");
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Url={0}", HelperGetChildInnerText(x, "Url")));
                                                vulnerabilityFound.rawrequest = HelperGetChildInnerText(x, "HttpRequest");
                                                //vulnerabilityFound.rawresponse = HelperGetChildInnerText(x, "HttpResponse");
                                                //StructuredData

                                                if (myPCI != "")
                                                {
                                                    //TODO
                                                    /*
                                                    vulnerabilityFound.PCI_FLAG = true;
                                                    int VulnID = VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, m_jobId, "cenzic", model);

                                                    List<int> myIds = new List<int>();
                                                    var id = from o in model.COMPLIANCECATEG
                                                             where o.Title == myTitle &&
                                                             o.COMPLIANCE.Title == "PCIDSS"
                                                             select o.ComplianceCategID;
                                                    int Id = id.FirstOrDefault();

                                                    myIds.Add(Id);

                                                    List<int> Compliances = new List<int>();
                                                    Compliances = myIds;
                                                    Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Vulnerability persisted , VulnID = {0} & Compliance count = {1}", VulnID, Compliances.Count));
                                                    var V = from tmpVuln in model.VULNERABILITYFOUND
                                                            where tmpVuln.VulnerabilityFoundID == VulnID
                                                            select tmpVuln;

                                                    VULNERABILITYFOUND VF = V.FirstOrDefault();

                                                    foreach (int i in Compliances)
                                                    {
                                                        Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Categorie Compliance => ", i));
                                                        var C = from Comp in model.COMPLIANCECATEG
                                                                where Comp.ComplianceCategID == i
                                                                select Comp;

                                                        COMPLIANCECATEG myCompliance = new COMPLIANCECATEG();
                                                        myCompliance = C.FirstOrDefault();

                                                        VF.COMPLIANCECATEG.Add(myCompliance);

                                                        model.SaveChanges();
                                                        Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", "Mapping Compliance-Vulnerability Added");
                                                    }
                                                    */
                                                }
                                                else
                                                {
                                                    int VulnID = VulnerabilityPersistor.Persist(vulnerabilityFound, vulnerabilityEndPoint, m_jobId, "cenzic", model);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Utils.Helper_Trace("XORCISM PROVIDER Cenzic Import", string.Format("Error in Vulnerable : Exception = {0}. {1}", ex.Message, ex.InnerException));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }