상속: PropertyBagHolder, ISarifNode
예제 #1
0
        public void EqualityComparer_ComputesTheSameHashCodeForDistinctEquivalentObjects()
        {
            var result1 = new Result
            {
                Stacks = new[]
                {
                    new Stack
                    {
                        Message = "Same"
                    }
                }
            };

            var result2 = new Result
            {
                Stacks = new[]
                {
                    new Stack
                    {
                        Message = "Same"
                    }
                }
            };

            Assert.AreNotSame(result1, result2);

            Assert.AreEqual(
                Result.ValueComparer.GetHashCode(result1),
                Result.ValueComparer.GetHashCode(result2));
        }
예제 #2
0
        /// <summary>
        ///     Build and return a list of Sarif Result list from the find characterstics results
        /// </summary>
        /// <param name="purl"> </param>
        /// <param name="results"> </param>
        /// <returns> </returns>
        private static List <SarifResult> GetSarifResults(PackageURL purl, double riskLevel)
        {
            List <SarifResult> sarifResults = new List <SarifResult>();
            SarifResult        sarifResult  = new SarifResult()
            {
                Kind      = ResultKind.Informational,
                Level     = FailureLevel.None,
                Locations = SarifOutputBuilder.BuildPurlLocation(purl),
                Rank      = riskLevel
            };

            sarifResults.Add(sarifResult);
            return(sarifResults);
        }
예제 #3
0
        /// <summary>
        ///     Build and return a list of Sarif Result list from the find characterstics results
        /// </summary>
        /// <param name="purl"> </param>
        /// <param name="results"> </param>
        /// <returns> </returns>
        private static List <SarifResult> GetSarifResults(PackageURL purl, Dictionary <string, AnalyzeResult?> analysisResult, Options opts)
        {
            List <SarifResult> sarifResults = new List <SarifResult>();

            if (analysisResult.HasAtLeastOneNonNullValue())
            {
                foreach (string?key in analysisResult.Keys)
                {
                    MetaData?metadata = analysisResult?[key]?.Metadata;

                    foreach (MatchRecord?result in metadata?.Matches ?? new List <MatchRecord>())
                    {
                        SarifResult?individualResult = new SarifResult()
                        {
                            Message = new Message()
                            {
                                Text = result.RuleDescription,
                                Id   = result.RuleId
                            },
                            Kind      = ResultKind.Informational,
                            Level     = opts.SarifLevel,
                            Locations = SarifOutputBuilder.BuildPurlLocation(purl),
                            Rule      = new ReportingDescriptorReference()
                            {
                                Id = result.RuleId
                            },
                        };

                        individualResult.SetProperty("Severity", result.Severity);
                        individualResult.SetProperty("Confidence", result.Confidence);

                        individualResult.Locations.Add(new CodeAnalysis.Sarif.Location()
                        {
                            PhysicalLocation = new PhysicalLocation()
                            {
                                Address = new Address()
                                {
                                    FullyQualifiedName = result.FileName
                                },
                                Region = new Region()
                                {
                                    StartLine      = result.StartLocationLine,
                                    EndLine        = result.EndLocationLine,
                                    StartColumn    = result.StartLocationColumn,
                                    EndColumn      = result.EndLocationColumn,
                                    SourceLanguage = result.Language,
                                    Snippet        = new ArtifactContent()
                                    {
                                        Text     = result.Excerpt,
                                        Rendered = new MultiformatMessageString(result.Excerpt, $"`{result.Excerpt}`", null)
                                    }
                                }
                            }
                        });

                        sarifResults.Add(individualResult);
                    }
                }
            }
            return(sarifResults);
        }
예제 #4
0
        public async Task <(string output, int numSquats)> RunAsync(Options options)
        {
            IOutputBuilder outputBuilder = SelectFormat(options.Format);
            var            foundSquats   = 0;

            foreach (var target in options.Targets ?? Array.Empty <string>())
            {
                var purl = new PackageURL(target);
                if (purl.Name is not null && purl.Type is not null)
                {
                    var manager = ProjectManagerFactory.CreateProjectManager(purl, null);
                    if (manager is not null)
                    {
                        var mutationsDict = gen.Mutate(purl.Name);

                        foreach ((var candidate, var rules) in mutationsDict)
                        {
                            if (options.SleepDelay > 0)
                            {
                                Thread.Sleep(options.SleepDelay);
                            }
                            // Nuget will match "microsoft.cst.oat." against "Microsoft.CST.OAT" but these are the same package
                            // For nuget in particular we filter out this case
                            if (manager is NuGetProjectManager)
                            {
                                if (candidate.EndsWith('.'))
                                {
                                    if (candidate.Equals($"{purl.Name}.", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        continue;
                                    }
                                }
                            }
                            var candidatePurl = new PackageURL(purl.Type, candidate);
                            try
                            {
                                var versions = await manager.EnumerateVersions(candidatePurl);

                                if (versions.Any())
                                {
                                    foundSquats++;
                                    if (!options.Quiet)
                                    {
                                        Logger.Info($"{candidate} package exists. Potential squat. {JsonConvert.SerializeObject(rules)}");
                                    }
                                    if (outputBuilder is SarifOutputBuilder sarob)
                                    {
                                        SarifResult sarifResult = new SarifResult()
                                        {
                                            Message = new Message()
                                            {
                                                Text = $"Potential Squat candidate { candidate }.",
                                                Id   = "oss-find-squats"
                                            },
                                            Kind      = ResultKind.Review,
                                            Level     = FailureLevel.None,
                                            Locations = SarifOutputBuilder.BuildPurlLocation(candidatePurl),
                                        };
                                        foreach (var tag in rules)
                                        {
                                            sarifResult.Tags.Add(tag);
                                        }
                                        sarob.AppendOutput(new SarifResult[] { sarifResult });
                                    }
                                    else if (outputBuilder is StringOutputBuilder strob)
                                    {
                                        var rulesString = string.Join(',', rules);
                                        strob.AppendOutput(new string[] { $"Potential Squat candidate '{ candidate }' detected. Generated by { rulesString }.{Environment.NewLine}" });
                                    }
                                    else
                                    {
                                        var rulesString = string.Join(',', rules);
                                        if (!options.Quiet)
                                        {
                                            Logger.Info($"Potential Squat candidate '{ candidate }' detected. Generated by { rulesString }.");
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Trace($"Could not enumerate versions. Package {candidate} likely doesn't exist. {e.Message}:{e.StackTrace}");
                            }
                        }
                    }
                }
            }

            return(outputBuilder.GetOutput(), foundSquats);
        }
예제 #5
0
        public void EqualityComparer_DecidesThatDistinctEquivalentObjectsAreEqual()
        {
            var result1 = new Result
            {
                Stacks = new[]
                {
                    new Stack
                    {
                        Message = "Same"
                    }
                }
            };

            var result2 = new Result
            {
                Stacks = new[]
                {
                    new Stack
                    {
                        Message = "Same"
                    }
                }
            };

            Assert.AreNotSame(result1, result2);
            Assert.AreNotEqual(result1, result2);
            Assert.IsTrue(result1.ValueEquals(result2));
        }