Exemple #1
0
        public void GetHashCodeReturnsTheSameValueIfObjectsAreEqual()
        {
            var a = new Cve("cve-1", "https://cve.com");
            var b = new Cve("cve-1", "https://cve.com");

            Assert.Equal(a.GetHashCode(), b.GetHashCode());
        }
Exemple #2
0
            public void ReturnsHttp200AndExpectedBodyForValidRequests(string queryString, string expectedCveIdStartString)
            {
                var cveRepositoryMock = GetMock <IEntityRepository <Cve> >();

                var expectedResult1 = new Cve {
                    CveId = "CVE-2000-011", Description = "Description A: listed.", Listed = true
                };
                var notExpectedResult1 = new Cve {
                    CveId = "CVE-2000-012", Description = "Description A: unlisted.", Listed = false
                };
                var expectedResult2 = new Cve {
                    CveId = "CVE-2000-013", Description = "description B", Listed = true
                };
                var expectedResult3 = new Cve {
                    CveId = "CVE-2000-014", Description = "description C", Listed = true
                };
                var expectedResult4 = new Cve {
                    CveId = "CVE-2000-015", Description = "description D", Listed = true
                };
                var expectedResult5 = new Cve {
                    CveId = "CVE-2000-016", Description = "description E", Listed = true
                };
                var notExpectedResult2 = new Cve {
                    CveId = "CVE-2000-017", Description = "description F", Listed = true
                };

                cveRepositoryMock
                .Setup(x => x.GetAll())
                .Returns(new[]
                {
                    expectedResult1,
                    notExpectedResult1,
                    expectedResult2,
                    expectedResult3,
                    expectedResult4,
                    expectedResult5,
                    notExpectedResult2
                }.AsQueryable());

                var queryResults = InvokeAndAssertStatusCode(queryString, HttpStatusCode.OK);

                Assert.True(queryResults.Success);
                Assert.Null(queryResults.ErrorMessage);

                Assert.Equal(5, queryResults.Results.Count);
                Assert.True(queryResults.Success);
                Assert.Null(queryResults.ErrorMessage);
                Assert.All(
                    queryResults.Results,
                    r =>
                {
                    Assert.StartsWith(expectedCveIdStartString, r.CveId, StringComparison.OrdinalIgnoreCase);

                    // Only the listed elements with CWE-ID starting with the query string should be returned (up to 5 elements).
                    Assert.NotEqual(notExpectedResult1.CveId, r.CveId, StringComparer.OrdinalIgnoreCase);

                    // Sorted numerically, this is the 6th element in the resultset and should be filtered out (max 5).
                    Assert.NotEqual(notExpectedResult2.CveId, r.CveId, StringComparer.OrdinalIgnoreCase);
                });
            }
        public IActionResult TestUpdate(IFormFile testFile)
        {
            // Check file type
            string fileExtension = Path.GetExtension(testFile.FileName);

            if (fileExtension != ".json" || testFile == null)
            {
                return(RedirectToAction(nameof(Index)));
            }

            // Get the CVE items
            string jsonString = "";

            using (var reader = new StreamReader(testFile.OpenReadStream()))
            {
                jsonString = reader.ReadToEnd();
            }

            JObject        jsonObject  = JObject.Parse(jsonString);
            IList <JToken> jsonCveList = jsonObject["CVE_Items"].ToList();

            // Foreach CVE
            foreach (JToken currCve in jsonCveList)
            {
                // Ignore rejected CVE's
                if (!currCve["cve"]["description"]["description_data"].First["value"].ToString().Contains("** REJECT **"))
                {
                    JToken cveMeta = currCve["cve"]["CVE_data_meta"];

                    // Get existing cve
                    string existingCveGivenId = cveMeta["ID"].ToString();
                    Cve    existingCve        = _context.Cves
                                                .Where(c => c.GivenID == existingCveGivenId)
                                                .Include(c => c.CveConfigurations)
                                                .ThenInclude(cc => cc.Product)
                                                .Include(c => c.References)
                                                .FirstOrDefault();

                    // If the CVE already exists
                    if (existingCve != null)
                    {
                        // Update existing CVE
                        //UpdateExistingCve(existingCve, currCve);
                    }
                    else // If the CVE doesn't exist
                    {
                        // Add new CVE
                        AddNewCve(currCve);
                    }
                }
            }

            // Send emails
            SendEmails();

            return(RedirectToAction(nameof(Index)));
        }
            public async Task ReturnsExistingAndCreatedCves(bool commitChanges)
            {
                // Arrange
                var matchingCve1 = new Cve
                {
                    CveId = "cve-1"
                };

                var notMatchingCve1 = new Cve
                {
                    CveId = "cve-2"
                };

                var matchingCve2 = new Cve
                {
                    CveId = "cve-3"
                };

                var notMatchingCve2 = new Cve
                {
                    CveId = "cve-4"
                };

                var cves       = new[] { matchingCve1, notMatchingCve1, matchingCve2, notMatchingCve2 };
                var repository = GetMock <IEntityRepository <Cve> >();

                repository
                .Setup(x => x.GetAll())
                .Returns(cves.AsQueryable())
                .Verifiable();

                var service = Get <PackageDeprecationService>();

                var missingCveId  = "cve-5";
                var queriedCveIds = new[] { matchingCve1.CveId, matchingCve2.CveId, missingCveId };

                // Act
                var result = await service.GetOrCreateCvesByIdAsync(queriedCveIds, commitChanges);

                // Assert
                Assert.Equal(3, result.Count);
                Assert.Contains(matchingCve1, result);
                Assert.Contains(matchingCve2, result);

                var createdCve = result.Last();

                Assert.Equal(missingCveId, createdCve.CveId);
                Assert.False(createdCve.Listed);
                Assert.Equal(CveStatus.Unknown, createdCve.Status);
                Assert.Null(createdCve.Description);
                Assert.Null(createdCve.CvssRating);
                Assert.Null(createdCve.LastModifiedDate);
                Assert.Null(createdCve.PublishedDate);
            }
Exemple #5
0
        public void ItImplementsIEquatable()
        {
            List <Cve> cves = new List <Cve>();
            var        cve1 = new Cve("cve-1", "https://cve.com");
            var        cve2 = new Cve("cve-1", "https://cve.com");

            cves.Add(new Cve("cve-2", "https://cve.com"));
            cves.Add(cve1);
            cves.Add(cve2);

            Assert.Equal(cve1, cve2);
            Assert.Equal(2, cves.Distinct().Count());
        }
        public IActionResult Details(int id)
        {
            // Get related CVE's
            Cve cve = _context.Cves
                      .Where(c => c.CveID == id)
                      .Include(c => c.References)
                      .Include(c => c.CveConfigurations)
                      .ThenInclude(cc => cc.Product)
                      .FirstOrDefault();

            if (cve == null)
            {
                TempData["Param"] = "Vulnerability";
                TempData["Error"] = "Vulnerability does not exist";
                return(RedirectToAction("Error", "Home"));
            }

            return(View(cve));
        }
Exemple #7
0
        public async Task <IReadOnlyCollection <Cve> > GetOrCreateCvesByIdAsync(IEnumerable <string> ids, bool commitChanges)
        {
            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            var details = _cveRepository.GetAll()
                          .Where(c => ids.Contains(c.CveId))
                          .ToList();

            var addedDetails = new List <Cve>();

            foreach (var missingId in ids.Where(i => !details.Any(c => c.CveId == i)))
            {
                var detail = new Cve
                {
                    CveId  = missingId,
                    Listed = false,
                    Status = CveStatus.Unknown
                };
                addedDetails.Add(detail);
                details.Add(detail);
            }

            if (addedDetails.Any())
            {
                _cveRepository.InsertOnCommit(addedDetails);
                if (commitChanges)
                {
                    await _cveRepository.CommitChangesAsync();
                }
            }

            return(details);
        }
        public void DeprecationFieldsAreSetAsExpected(
            PackageDeprecationStatus status,
            SeverityString_State severity,
            bool hasCves,
            bool hasCwes,
            bool hasAlternateRegistration,
            bool hasAlternatePackage)
        {
            // Arrange
            decimal?cvss;

            switch (severity)
            {
            case SeverityString_State.Critical:
                cvss = (decimal)9.5;
                break;

            case SeverityString_State.High:
                cvss = (decimal)7.5;
                break;

            case SeverityString_State.Medium:
                cvss = (decimal)5;
                break;

            case SeverityString_State.Low:
                cvss = (decimal)2;
                break;

            case SeverityString_State.None:
                cvss = null;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(severity));
            }

            var deprecation = new PackageDeprecation
            {
                CvssRating    = cvss,
                CustomMessage = "hello"
            };

            var cveIds = new[] { "CVE-2019-1111", "CVE-2019-2222" };

            if (hasCves)
            {
                foreach (var cveId in cveIds)
                {
                    var cve = new Cve
                    {
                        CveId = cveId
                    };

                    deprecation.Cves.Add(cve);
                }
            }

            var cweIds = new[] { "CWE-1", "CWE-2" };

            if (hasCwes)
            {
                foreach (var cweId in cweIds)
                {
                    var cwe = new Cwe
                    {
                        CweId = cweId
                    };

                    deprecation.Cwes.Add(cwe);
                }
            }

            var alternateRegistrationId = "alternateRegistrationId";

            if (hasAlternateRegistration)
            {
                var registration = new PackageRegistration
                {
                    Id = alternateRegistrationId
                };

                deprecation.AlternatePackageRegistration = registration;
            }

            var alternatePackageRegistrationId = "alternatePackageRegistration";
            var alternatePackageVersion        = "1.0.0-alt";

            if (hasAlternatePackage)
            {
                var alternatePackageRegistration = new PackageRegistration
                {
                    Id = alternatePackageRegistrationId
                };

                var alternatePackage = new Package
                {
                    Version             = alternatePackageVersion,
                    PackageRegistration = alternatePackageRegistration
                };

                deprecation.AlternatePackage = alternatePackage;
            }

            var package = CreateTestPackage("1.0.0");

            var linkedDeprecation = new PackageDeprecation
            {
                Status = status
            };

            package.Deprecations.Add(linkedDeprecation);

            // Act
            var model = new DisplayPackageViewModel(package, null, deprecation);

            // Assert
            Assert.Equal(status, model.DeprecationStatus);
            Assert.Equal(deprecation.CustomMessage, model.CustomMessage);

            string expectedString;

            switch (severity)
            {
            case SeverityString_State.Critical:
                expectedString = "Critical";
                break;

            case SeverityString_State.High:
                expectedString = "High";
                break;

            case SeverityString_State.Medium:
                expectedString = "Medium";
                break;

            case SeverityString_State.Low:
                expectedString = "Low";
                break;

            case SeverityString_State.None:
                expectedString = null;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(severity));
            }

            Assert.Equal(expectedString, model.Severity);

            if (hasCves)
            {
                Assert.Equal(cveIds, model.CveIds);
            }
            else
            {
                Assert.Empty(model.CveIds);
            }

            if (hasCwes)
            {
                Assert.Equal(cweIds, model.CweIds);
            }
            else
            {
                Assert.Empty(model.CweIds);
            }

            if (hasAlternatePackage)
            {
                Assert.Equal(alternatePackageRegistrationId, model.AlternatePackageId);
                Assert.Equal(alternatePackageVersion, model.AlternatePackageVersion);
            }
            else if (hasAlternateRegistration)
            {
                Assert.Equal(alternateRegistrationId, model.AlternatePackageId);
                Assert.Null(model.AlternatePackageVersion);
            }
            else
            {
                Assert.Null(model.AlternatePackageId);
                Assert.Null(model.AlternatePackageVersion);
            }

            var versionModel = model.PackageVersions.Single();

            Assert.Equal(status, versionModel.DeprecationStatus);
            Assert.Null(versionModel.Severity);
            Assert.Null(versionModel.CveIds);
            Assert.Null(versionModel.CweIds);
            Assert.Null(versionModel.AlternatePackageId);
            Assert.Null(versionModel.AlternatePackageVersion);
            Assert.Null(versionModel.CustomMessage);
        }
Exemple #9
0
 public VulnerabilityDetailState(Cve cve)
     : this(cve.CveId, cve.Description)
 {
     cvss = cve.CvssRating;
 }
        public IActionResult InitialDataImport()
        {
            // Get all file paths
            IList <string> pathList = new List <string>();

            // Foreach file
            foreach (string currFile in Directory.EnumerateFiles(
                         "wwwroot\\CVE Data", "*",
                         SearchOption.AllDirectories))
            {
                string  jsonString = System.IO.File.ReadAllText(currFile);
                JObject jsonObject = JObject.Parse(jsonString);


                IList <JToken> jsonCveList = jsonObject["CVE_Items"].ToList();

                //Collect values from each Cve and create Cve object
                IList <Cve> newCveList = new List <Cve>();
                foreach (JToken currCve in jsonCveList)
                {
                    // Only accept if CVE description does not contain ** REJECT ** and has a score
                    if (!currCve["cve"]["description"]["description_data"].First["value"].ToString().Contains("** REJECT **"))
                    {
                        JToken cveMeta = currCve["cve"]["CVE_data_meta"];

                        // Detect errornous score information and restart
                        JToken cvss;
                        try
                        {
                            cvss = currCve["impact"]["baseMetricV2"]["cvssV2"];
                        }
                        catch (Exception e)
                        {
                            continue;
                        }

                        // Create new CveObject
                        Cve newCve = new Cve
                        {
                            PublishedDate         = Convert.ToDateTime(currCve["publishedDate"].ToString()),
                            LastModifiedDate      = Convert.ToDateTime(currCve["lastModifiedDate"].ToString()),
                            GivenID               = cveMeta["ID"].ToString(),
                            Description           = currCve["cve"]["description"]["description_data"].First["value"].ToString(),
                            VectorString          = cvss["vectorString"].ToString(),
                            AccessVector          = cvss["accessVector"].ToString(),
                            AccessComplexity      = cvss["accessComplexity"].ToString(),
                            Authentication        = cvss["authentication"].ToString(),
                            ConfidentialityImpact = cvss["confidentialityImpact"].ToString(),
                            IntegrityImpact       = cvss["availabilityImpact"].ToString(),
                            AvailabilityImpact    = cvss["availabilityImpact"].ToString(),
                            BaseScore             = Convert.ToDouble(cvss["baseScore"].ToString()),
                            References            = new List <Reference>(),
                            CveConfigurations     = new List <CveConfiguration>()
                        };

                        // Get references
                        JToken jsonReferenceList = currCve["cve"]["references"]["reference_data"];
                        foreach (JToken currReference in jsonReferenceList)
                        {
                            Reference newReference = new Reference
                            {
                                Url = currReference["url"].ToString()
                            };
                            newCve.References.Add(newReference);
                        }

                        // Get products from CVE
                        JObject        currCveObject   = JObject.Parse(currCve.ToString());
                        IList <JToken> jsonProductList = currCveObject.Descendants()
                                                         .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "cpe23Uri")
                                                         .Select(p => ((JProperty)p).Value).ToList();

                        jsonProductList = jsonProductList.Distinct().ToList();

                        // Foreach product
                        foreach (JToken currJsonProduct in jsonProductList)
                        {
                            // Get existing product if it exists
                            string  currJsonProductString = currJsonProduct.ToString();
                            Product existingProduct       = _context.Products
                                                            .Where(p => p.Concatenated == currJsonProductString)
                                                            .FirstOrDefault();

                            // If existing product does exist in the database
                            if (existingProduct != null)
                            {
                                CveConfiguration newConfiguration = new CveConfiguration
                                {
                                    Product = existingProduct
                                };

                                newCve.CveConfigurations.Add(newConfiguration);
                            }
                            else // If the existing product doesn't exist in the database
                            {
                                // Break down the currJsonProductString into its components
                                IList <string> productPartList = new List <string>();
                                productPartList = currJsonProductString.Split(":");

                                // Create new product
                                Product newProduct = new Product
                                {
                                    Concatenated    = currJsonProductString,
                                    Part            = productPartList[2],
                                    Vendor          = productPartList[3],
                                    ProductName     = productPartList[4],
                                    Version         = productPartList[5],
                                    ProductUpdate   = productPartList[6],
                                    Edition         = productPartList[7],
                                    ProductLanguage = productPartList[8],
                                    Added           = DateTime.Now
                                };

                                // Add the new product to newCveConfiguration
                                CveConfiguration newCveConfiguration = new CveConfiguration
                                {
                                    Product = newProduct
                                };

                                // Add the newCveConfiguration to the newCve
                                newCve.CveConfigurations.Add(newCveConfiguration);
                            }
                        }

                        // Add new CVE to database
                        try
                        {
                            _context.Cves.Add(newCve);
                            _context.SaveChanges();
                        }
                        catch (Exception e)
                        {
                            TempData["Param"] = "newCve";
                            TempData["Error"] = e.Message;
                            throw e;
                        }
                    }
                }
            }

            StatusMessage = "Successfully Seeded Database.";
            return(RedirectToAction(nameof(Index)));
        }
        private void AddNewCve(JToken currCve)
        {
            // Only accept if CVE description does not contain ** REJECT ** and build data
            if (!currCve["cve"]["description"]["description_data"].First["value"].ToString().Contains("** REJECT **"))
            {
                JToken cveMeta = currCve["cve"]["CVE_data_meta"];

                JToken cvss;

                if (currCve["impact"].Children().Count() == 0)
                {
                    return;
                }

                cvss = currCve["impact"]["baseMetricV2"]["cvssV2"];

                // Create new CveObject
                Cve newCve = new Cve
                {
                    PublishedDate         = Convert.ToDateTime(currCve["publishedDate"].ToString()),
                    LastModifiedDate      = Convert.ToDateTime(currCve["lastModifiedDate"].ToString()),
                    GivenID               = cveMeta["ID"].ToString(),
                    Description           = currCve["cve"]["description"]["description_data"].First["value"].ToString(),
                    VectorString          = cvss["vectorString"].ToString(),
                    AccessVector          = cvss["accessVector"].ToString(),
                    AccessComplexity      = cvss["accessComplexity"].ToString(),
                    Authentication        = cvss["authentication"].ToString(),
                    ConfidentialityImpact = cvss["confidentialityImpact"].ToString(),
                    IntegrityImpact       = cvss["availabilityImpact"].ToString(),
                    AvailabilityImpact    = cvss["availabilityImpact"].ToString(),
                    BaseScore             = Convert.ToDouble(cvss["baseScore"].ToString()),
                    References            = new List <Reference>(),
                    CveConfigurations     = new List <CveConfiguration>(),
                    UserCveConfigurations = new List <UserCveConfiguration>()
                };

                // Get references
                JToken jsonReferenceList = currCve["cve"]["references"]["reference_data"];
                foreach (JToken currReference in jsonReferenceList)
                {
                    Reference newReference = new Reference
                    {
                        Url = currReference["url"].ToString()
                    };
                    newCve.References.Add(newReference);
                }

                // Get products from CVE
                JObject        currCveObject   = JObject.Parse(currCve.ToString());
                IList <JToken> jsonProductList = currCveObject.Descendants()
                                                 .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "cpe23Uri")
                                                 .Select(p => ((JProperty)p).Value).ToList();

                jsonProductList = jsonProductList.Distinct().ToList();

                // Foreach product
                foreach (JToken currJsonProduct in jsonProductList)
                {
                    // Get existing product if it exists
                    string  currJsonProductString = currJsonProduct.ToString();
                    Product existingProduct       = _context.Products
                                                    .Where(p => p.Concatenated == currJsonProductString)
                                                    .FirstOrDefault();

                    // If existing product does exist in the database
                    if (existingProduct != null)
                    {
                        CveConfiguration newConfiguration = new CveConfiguration
                        {
                            Product = existingProduct
                        };

                        newCve.CveConfigurations.Add(newConfiguration);

                        // Update tracked userCveConfigurations where this product is already tracked
                        Status status = _context.Status.Where(s => s.StatusName == "Unresolved").FirstOrDefault();
                        foreach (var item in _context.UserCveConfigurations
                                 .Where(ucc => ucc.ProductID == existingProduct.ProductID)
                                 .GroupBy(g => g.ConfigurationID).ToList())
                        {
                            UserCveConfiguration newUserCveConfiguration = new UserCveConfiguration()
                            {
                                ProductID       = existingProduct.ProductID,
                                ConfigurationID = item.Key,
                                StatusID        = status.StatusID,
                                Notes           = "No user defined notes.",
                                DateAdded       = DateTime.Now,
                                Cve             = newCve,
                                New             = 'Y'.ToString()
                            };

                            // Add email notification if not already added
                            var existingConfiguration = _context.Configurations
                                                        .Where(c => c.ConfigurationID == item.Key)
                                                        .FirstOrDefault();

                            var userToEmail = _context.Users
                                              .Where(u => u.Id == existingConfiguration.AspNetUserID)
                                              .FirstOrDefault();

                            // Check if an email already exists
                            bool emailAlreadyExists = emailRecipientList
                                                      .Where(erl => erl.EmailAddress == userToEmail.Email).Count() > 0;

                            // If the email does exist
                            if (emailAlreadyExists == true)
                            {
                                // Add configuration Name
                                if (!emailRecipientList.Where(erl => erl.EmailAddress == userToEmail.Email).First()
                                    .ConfigurationIdList.Contains(existingConfiguration.ConfigurationID))
                                {
                                    emailRecipientList.Where(erl => erl.EmailAddress == userToEmail.Email).First()
                                    .ConfigurationIdList.Add(existingConfiguration.ConfigurationID);
                                }
                            }
                            else   // If the email does not exist
                            {
                                // Create new email and add it to the recipient list
                                Email newEmail = new Email()
                                {
                                    EmailAddress  = userToEmail.Email,
                                    RecipientName = userToEmail.FirstName,
                                };
                                newEmail.ConfigurationIdList.Add(existingConfiguration.ConfigurationID);
                                emailRecipientList.Add(newEmail);
                            }

                            newCve.UserCveConfigurations.Add(newUserCveConfiguration);
                        }
                    }
                    else // If the existing product doesn't exist in the database
                    {
                        // Break down the currJsonProductString into its components
                        IList <string> productPartList = new List <string>();
                        productPartList = currJsonProductString.Split(":");

                        // Create new product
                        Product newProduct = new Product
                        {
                            Concatenated    = currJsonProductString,
                            Part            = productPartList[2],
                            Vendor          = productPartList[3],
                            ProductName     = productPartList[4],
                            Version         = productPartList[5],
                            ProductUpdate   = productPartList[6],
                            Edition         = productPartList[7],
                            ProductLanguage = productPartList[8],
                            Added           = DateTime.Now
                        };

                        // Add the new product to newCveConfiguration
                        CveConfiguration newCveConfiguration = new CveConfiguration
                        {
                            Product = newProduct
                        };

                        // Add the newCveConfiguration to the newCve
                        newCve.CveConfigurations.Add(newCveConfiguration);
                    }
                }

                // Add new CVE to database
                try
                {
                    _context.Cves.Add(newCve);
                    _context.SaveChanges();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Error: " + e.Message);
                }
            }
        }
        private void UpdateExistingCve(Cve existingCve, JToken currCve)
        {
            JToken cveMeta = currCve["cve"]["CVE_data_meta"];
            JToken cvss;

            // Detect errornous score information and restart
            try
            {
                cvss = currCve["impact"]["baseMetricV2"]["cvssV2"];
            }
            catch (Exception)
            {
                return;
            }

            // Update the CVE itself
            existingCve.PublishedDate         = Convert.ToDateTime(currCve["publishedDate"].ToString());
            existingCve.LastModifiedDate      = Convert.ToDateTime(currCve["lastModifiedDate"].ToString());
            existingCve.GivenID               = cveMeta["ID"].ToString();
            existingCve.Description           = currCve["cve"]["description"]["description_data"].First["value"].ToString();
            existingCve.VectorString          = cvss["vectorString"].ToString();
            existingCve.AccessVector          = cvss["accessVector"].ToString();
            existingCve.AccessComplexity      = cvss["accessComplexity"].ToString();
            existingCve.Authentication        = cvss["authentication"].ToString();
            existingCve.ConfidentialityImpact = cvss["confidentialityImpact"].ToString();
            existingCve.IntegrityImpact       = cvss["availabilityImpact"].ToString();
            existingCve.AvailabilityImpact    = cvss["availabilityImpact"].ToString();
            existingCve.BaseScore             = Convert.ToDouble(cvss["baseScore"].ToString());

            existingCve.References.Clear();
            JToken jsonReferenceList = currCve["cve"]["references"]["reference_data"];

            foreach (JToken currReference in jsonReferenceList)
            {
                Reference newReference = new Reference
                {
                    Url = currReference["url"].ToString()
                };
                existingCve.References.Add(newReference);
            }

            // Add any new products
            JObject        currCveObject   = JObject.Parse(currCve.ToString());
            IList <JToken> jsonProductList = currCveObject.Descendants()
                                             .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "cpe23Uri")
                                             .Select(p => ((JProperty)p).Value).ToList();

            jsonProductList = jsonProductList.Distinct().ToList();

            bool alreadyContained = false;

            foreach (JToken currJsonProduct in jsonProductList)
            {
                // Check for existing product
                foreach (CveConfiguration currCveConfiguration in existingCve.CveConfigurations)
                {
                    if (currCveConfiguration.Product.Concatenated == currJsonProduct.ToString())
                    {
                        alreadyContained = true;
                        break;
                    }
                }

                // If not already contained add the new product
                if (alreadyContained == false)
                {
                    // Get existing product if it exists
                    string  currJsonProductString = currJsonProduct.ToString();
                    Product existingProduct       = _context.Products
                                                    .Where(p => p.Concatenated == currJsonProductString)
                                                    .Include(p => p.CveConfigurations)
                                                    .FirstOrDefault();

                    // If existing product does exist in the database
                    if (existingProduct != null)
                    {
                        CveConfiguration newConfiguration = new CveConfiguration
                        {
                            Product = existingProduct
                        };

                        existingCve.CveConfigurations.Add(newConfiguration);

                        // Update tracked userCveConfigurations where this product is already tracked
                        Status status = _context.Status.Where(s => s.StatusName == "Unresolved").FirstOrDefault();
                        foreach (var item in _context.UserCveConfigurations
                                 .Where(ucc => ucc.ProductID == existingProduct.ProductID)
                                 .GroupBy(ucc => ucc.ProductID)
                                 .Select(g => g.First()).ToList())
                        {
                            UserCveConfiguration newUserCveConfiguration = new UserCveConfiguration()
                            {
                                ProductID       = existingProduct.ProductID,
                                CveID           = existingCve.CveID,
                                ConfigurationID = item.CveID,
                                StatusID        = status.StatusID,
                                Notes           = "No user defined notes.",
                                DateAdded       = DateTime.Now
                            };

                            try
                            {
                                if (ModelState.IsValid)
                                {
                                    _context.UserCveConfigurations.Add(newUserCveConfiguration);
                                    _context.SaveChanges();
                                }
                            }
                            catch (Exception)
                            {
                                return;
                            }
                        }
                    }
                    else // If the existing product doesn't exist in the database
                    {
                        // Break down the currJsonProductString into its components
                        IList <string> productPartList = new List <string>();
                        productPartList = currJsonProductString.Split(":");

                        // Create new product
                        Product newProduct = new Product
                        {
                            Concatenated    = currJsonProductString,
                            Part            = productPartList[2],
                            Vendor          = productPartList[3],
                            ProductName     = productPartList[4],
                            Version         = productPartList[5],
                            ProductUpdate   = productPartList[6],
                            Edition         = productPartList[7],
                            ProductLanguage = productPartList[8]
                        };

                        // Add the new product to newCveConfiguration
                        CveConfiguration newCveConfiguration = new CveConfiguration
                        {
                            Product = newProduct
                        };

                        // Add the newCveConfiguration to the newCve
                        existingCve.CveConfigurations.Add(newCveConfiguration);
                    }
                }
            }
            // save updated existingCve
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Entry(existingCve).State = EntityState.Modified;
                    _context.SaveChanges();
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        public IActionResult ImportModifiedCveData(string guid)
        {
            // Only run if URL calls with the below GUID for security
            if (guid == "3777706d-0db3-4a6c-9f34-2cbd672fbd89")
            {
                // Clear directories https://stackoverflow.com/questions/1288718/how-to-delete-all-files-and-folders-in-a-directory

                Uri    uri         = new Uri("https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-recent.json.zip");
                string zipPath     = "wwwroot\\CVE Data\\recent.zip";
                string extractPath = "wwwroot\\CVE Data\\";
                string filePath;

                // Download the file
                using (var client = new WebClient())
                {
                    try
                    {
                        client.DownloadFile(uri, zipPath);
                    }
                    catch (Exception)
                    {
                        return(StatusCode(500));
                    }
                }

                // Extract the file
                using (ZipArchive archive = ZipFile.OpenRead(zipPath))
                {
                    ZipArchiveEntry entry = archive.Entries.Where(e => e.FullName.EndsWith(".json")).FirstOrDefault();
                    filePath = Path.Combine(extractPath, entry.FullName);
                    entry.ExtractToFile(filePath, true);
                }

                // Get the CVE items
                string         jsonString  = System.IO.File.ReadAllText(filePath);
                JObject        jsonObject  = JObject.Parse(jsonString);
                IList <JToken> jsonCveList = jsonObject["CVE_Items"].ToList();

                // Foreach CVE
                foreach (JToken currCve in jsonCveList)
                {
                    // Ignore rejected CVE's
                    if (!currCve["cve"]["description"]["description_data"].First["value"].ToString().Contains("** REJECT **"))
                    {
                        JToken cveMeta = currCve["cve"]["CVE_data_meta"];

                        // Get existing cve
                        string existingCveGivenId = cveMeta["ID"].ToString();
                        Cve    existingCve        = _context.Cves
                                                    .Where(c => c.GivenID == existingCveGivenId)
                                                    .Include(c => c.CveConfigurations)
                                                    .ThenInclude(cc => cc.Product)
                                                    .Include(c => c.References)
                                                    .FirstOrDefault();

                        // If the CVE already exists
                        if (existingCve != null)
                        {
                            // Update existing CVE
                            //UpdateExistingCve(existingCve, currCve);
                        }
                        else // If the CVE doesn't exist
                        {
                            // Add new CVE
                            AddNewCve(currCve);
                        }
                    }
                }

                // Send emails
                SendEmails();

                // Return success code
                return(StatusCode(200));
            }
            else
            {
                return(StatusCode(401));
            }
        }
Exemple #14
0
            public async Task ReturnsNotFoundIfGetCwesByIdThrowsArgumentException(User currentUser, User owner)
            {
                // Arrange
                var id = "id";

                var featureFlagService = GetMock <IFeatureFlagService>();

                featureFlagService
                .Setup(x => x.IsManageDeprecationEnabled(currentUser))
                .Returns(true)
                .Verifiable();

                var registration = new PackageRegistration
                {
                    Id = id
                };

                registration.Owners.Add(owner);

                var package = new Package
                {
                    NormalizedVersion   = "2.3.4",
                    PackageRegistration = registration
                };

                var packageService = GetMock <IPackageService>();

                packageService
                .Setup(x => x.FindPackagesById(id, PackageDeprecationFieldsToInclude.DeprecationAndRelationships))
                .Returns(new[] { package })
                .Verifiable();

                var deprecationService = GetMock <IPackageDeprecationService>();

                var cves = new Cve[0];

                deprecationService
                .Setup(x => x.GetOrCreateCvesByIdAsync(Enumerable.Empty <string>(), false))
                .CompletesWith(cves)
                .Verifiable();

                deprecationService
                .Setup(x => x.GetCwesById(Enumerable.Empty <string>()))
                .Throws(new ArgumentException())
                .Verifiable();

                var controller = GetController <ManageDeprecationJsonApiController>();

                controller.SetCurrentUser(currentUser);

                // Act
                var result = await controller.Deprecate(
                    id, new[] { package.NormalizedVersion }, false, false, false, null, null, null, null, null, null);

                // Assert
                AssertErrorResponse(
                    controller,
                    result,
                    HttpStatusCode.NotFound,
                    Strings.DeprecatePackage_CweMissing);
                featureFlagService.Verify();
                packageService.Verify();
            }