コード例 #1
0
ファイル: Program.cs プロジェクト: KingKnecht/AplayTest
        public static void Main()
        {
            var undoServiceFactory = new UndoServiceFactory();
            var undoService        = undoServiceFactory.Create();
            var clientStateService = new ClientIdLookup();
            var undoManagerCache   = new UndoManagerCache(undoService);

            var projectManagerService = new ProjectManagerService();


            var connectionFactory = new ConnectionFactory(undoService);
            var connectorFactory  = new ConnectorFactory(undoService, connectionFactory);

            connectionFactory.ConnectorFactory = connectorFactory; //Make sure to inject the connectorFactory.

            var blockSymbolFactory = new BlockSymbolFactory(undoService, connectorFactory);
            var sheetFactory       = new SheetFactory(undoService, connectionFactory, blockSymbolFactory, connectorFactory);

            connectionFactory.SheetFactory  = sheetFactory;
            blockSymbolFactory.SheetFactory = sheetFactory;
            connectorFactory.SheetFactory   = sheetFactory;

            var projectManager = new ProjectManagerFactory(projectManagerService, undoService, undoManagerCache,
                                                           connectorFactory, connectionFactory, blockSymbolFactory, sheetFactory);

            var server = new APlayServer(Int32.Parse(Properties.Settings.Default.ServerPort), projectManager,
                                         clientStateService);
        }
コード例 #2
0
        public void ConvertToAndFromJson(string packageUrl, string expectedToFind)
        {
            PackageURL purl = new(packageUrl);

            if (purl.Name is not null && purl.Type is not null)
            {
                BaseProjectManager?manager = ProjectManagerFactory.ConstructPackageManager(purl, null);
                if (manager is not null)
                {
                    foreach ((string mutationPurlString, IList <Mutation> mutations) in manager.EnumerateSquatCandidates(purl) !)
                    {
                        PackageURL             mutationPurl = new(mutationPurlString);
                        FindPackageSquatResult result       = new(mutationPurl.GetFullName(), mutationPurl,
                                                                  purl, mutations);
                        string jsonResult = result.ToJson();
                        if (jsonResult.Contains(expectedToFind, StringComparison.OrdinalIgnoreCase))
                        {
                            FindPackageSquatResult fromJson = FindPackageSquatResult.FromJsonString(jsonResult);
                            if (fromJson.OriginalPackageUrl.ToString().Equals(purl.ToString(), StringComparison.OrdinalIgnoreCase) &&
                                fromJson.MutatedPackageUrl.ToString().Equals(expectedToFind, StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }
                        }
                    }
                }
            }
            Assert.Fail($"Did not find expected mutation {expectedToFind}");
        }
コード例 #3
0
        /// <summary>
        ///     Constuctor - creates a class object for downloading packages
        /// </summary>
        /// <param name="purl"> package to download </param>
        /// <param name="destinationDir"> the directory where the package needs to be placed </param>
        /// <param name="doCaching"> check and use the cache if it exists - create if not </param>
        public PackageDownloader(PackageURL?purl, string?destinationDir = null, bool doCaching = false)
        {
            if (purl == null)
            {
                throw new ArgumentNullException("PackageURL cannot be null");
            }

            this.doCache = doCaching;
            // if we are told to use caching, and it exists, believe that caching is still doable
            this.actualCaching = (doCaching && !string.IsNullOrEmpty(destinationDir) && Directory.Exists(destinationDir));

            // if no destination specified, dump the package in the temp directory
            this.destinationDirectory = string.IsNullOrEmpty(destinationDir) ?
                                        Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()) : destinationDir;

            this.packageManager = ProjectManagerFactory.CreateProjectManager(purl, this.destinationDirectory);
            if (this.packageManager == null)
            {
                // Cannot continue without package manager
                throw new ArgumentException("Invalid Package URL type: {0}", purl.Type);
            }
            this.PackageVersions = new List <PackageURL>();
            if (purl.Version == null || purl.Version.Equals("*"))
            {
                // figure out which version(s) we need to process
                this.PackageVersions = this.GetPackageVersionsToProcess(purl).Result;
            }
            else
            {
                this.PackageVersions.Add(purl);
            }
        }
コード例 #4
0
ファイル: SharedTests.cs プロジェクト: microsoft/OSSGadget
        public async Task MetadataToFromJsonSucceeds(string packageUrlString)
        {
            PackageURL         packageUrl     = new(packageUrlString);
            BaseProjectManager?projectManager = ProjectManagerFactory.ConstructPackageManager(packageUrl);

            if (projectManager == null)
            {
                throw new NullReferenceException("The project manager is null.");
            }

            PackageMetadata metadata = await projectManager.GetPackageMetadataAsync(packageUrl, useCache : false);

            Assert.AreEqual("lodash", metadata.Name);
            Assert.AreEqual("Lodash modular utilities.", metadata.Description);
            Assert.AreEqual("4.17.15", metadata.PackageVersion);

            string?metadataJson = metadata.ToString();

            Assert.IsTrue(metadataJson.Contains("Lodash modular utilities."));

            PackageMetadata metadataFromJson = PackageMetadata.FromJson(metadataJson) ?? throw new InvalidOperationException("Can't deserialize the metadata json.");

            Assert.AreEqual("lodash", metadataFromJson.Name);
            Assert.AreEqual("Lodash modular utilities.", metadataFromJson.Description);
            Assert.AreEqual("4.17.15", metadataFromJson.PackageVersion);
        }
コード例 #5
0
        public async Task Wildcard_Download_Version_Succeeds(string packageUrl, string targetFilename)
        {
            PackageURL           purl     = new(packageUrl);
            BaseProjectManager?  manager  = new ProjectManagerFactory().CreateProjectManager(purl);
            IEnumerable <string> versions = await manager?.EnumerateVersionsAsync(purl) ?? throw new InvalidOperationException();

            await TestDownload(packageUrl, targetFilename, versions.Count());
        }
コード例 #6
0
 public FindPackageSquats(ProjectManagerFactory projectManagerFactory, PackageURL packageUrl)
     : base(projectManagerFactory)
 {
     PackageUrl     = packageUrl;
     ProjectManager = projectManagerFactory.CreateProjectManager(packageUrl);
     if (ProjectManager is null)
     {
         Logger.Trace($"Could not generate valid ProjectManager from { packageUrl }.");
         throw new InvalidProjectManagerException(packageUrl);
     }
 }
コード例 #7
0
        public async Task <string> DiffProjects(Options options)
        {
            var extractor     = new Extractor();
            var diffObjs      = new List <Diff>();
            var outputBuilder = OutputBuilderFactory.CreateOutputBuilder(options.Format);

            if (outputBuilder is null)
            {
                Logger.Error($"Format {options.Format} is not supported.");
                return(string.Empty);
            }


            // Map relative location in package to actual location on disk
            Dictionary <string, (string, string)> files = new Dictionary <string, (string, string)>();
            IEnumerable <string> locations  = Array.Empty <string>();
            IEnumerable <string> locations2 = Array.Empty <string>();

            try
            {
                PackageURL purl1   = new PackageURL(options.Targets.First());
                var        manager = ProjectManagerFactory.CreateProjectManager(purl1, options.DownloadDirectory ?? Path.GetTempPath());

                if (manager is not null)
                {
                    locations = await manager.DownloadVersion(purl1, true, options.UseCache);
                }
            }
            catch (Exception)
            {
                var tmpDir = Path.GetTempFileName();
                File.Delete(tmpDir);
                try
                {
                    extractor.ExtractToDirectory(tmpDir, options.Targets.First());
                    locations = new string[] { tmpDir };
                }
                catch (Exception e)
                {
                    Logger.Error($"{e.Message}:{e.StackTrace}");
                    Environment.Exit(-1);
                }
            }

            foreach (var directory in locations)
            {
                foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
                {
                    files.Add(string.Join(Path.DirectorySeparatorChar, file[directory.Length..].Split(Path.DirectorySeparatorChar)[2..]), (file, string.Empty));
コード例 #8
0
ファイル: DiffTool.cs プロジェクト: microsoft/OSSGadget
        public async Task <IOutputBuilder> DiffProjects(Options options)
        {
            Extractor?     extractor     = new Extractor();
            IOutputBuilder?outputBuilder = OutputBuilderFactory.CreateOutputBuilder(options.Format);

            if (outputBuilder is null)
            {
                Logger.Error($"Format {options.Format} is not supported.");
                throw new ArgumentOutOfRangeException("options.Format", $"Format {options.Format} is not supported.");
            }

            // Map relative location in package to actual location on disk
            ConcurrentDictionary <string, (string, string)> files = new ConcurrentDictionary <string, (string, string)>();
            IEnumerable <string> locations  = Array.Empty <string>();
            IEnumerable <string> locations2 = Array.Empty <string>();

            try
            {
                PackageURL         purl1   = new PackageURL(options.Targets.First());
                BaseProjectManager?manager = ProjectManagerFactory.CreateProjectManager(purl1, options.DownloadDirectory ?? Path.GetTempPath());

                if (manager is not null)
                {
                    locations = await manager.DownloadVersionAsync(purl1, true, options.UseCache);
                }
            }
            catch (Exception)
            {
                string?tmpDir = Path.GetTempFileName();
                File.Delete(tmpDir);
                try
                {
                    extractor.ExtractToDirectory(tmpDir, options.Targets.First());
                    locations = new string[] { tmpDir };
                }
                catch (Exception e)
                {
                    Logger.Error($"{e.Message}:{e.StackTrace}");
                    Environment.Exit(-1);
                }
            }

            foreach (string?directory in locations)
            {
                foreach (string?file in System.IO.Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
                {
                    files[string.Join(Path.DirectorySeparatorChar, file[directory.Length..].Split(Path.DirectorySeparatorChar)[2..])] = (file, string.Empty);
コード例 #9
0
        public void DontGenerateManagerSpecific(string packageUrl, Type notExpectedToFind)
        {
            PackageURL purl = new(packageUrl);

            if (purl.Name is not null && purl.Type is not null)
            {
                BaseProjectManager?manager = ProjectManagerFactory.ConstructPackageManager(purl, null);
                if (manager is not null)
                {
                    foreach (IMutator mutator in manager.GetDefaultMutators())
                    {
                        if (mutator.GetType().Equals(notExpectedToFind))
                        {
                            Assert.Fail($"Found unexpected mutator {notExpectedToFind.FullName}");
                        }
                    }
                }
            }
        }
コード例 #10
0
        public List <Result> toSarif()
        {
            BaseProjectManager?projectManager = ProjectManagerFactory.CreateProjectManager(purl, null);

            if (projectManager == null)
            {
                Logger.Error("Cannot determine the package type");
                return(new List <Result>());
            }

            Normalize();

            List <Result> results    = new List <Result>();
            var           properties = getHealthProperties();

            foreach (var property in properties.OrderBy(s => s.Name))
            {
                if (property.Name.EndsWith("Health"))
                {
                    var textualName = Regex.Replace(property.Name, "(\\B[A-Z])", " $1");
                    var value       = Convert.ToDouble(property.GetValue(this));

                    Result healthResult = new Result()
                    {
                        Kind    = ResultKind.Review,
                        Level   = FailureLevel.None,
                        Message = new Message()
                        {
                            Text = textualName
                        },
                        Rank = value,

                        Locations = SarifOutputBuilder.BuildPurlLocation(purl)
                    };
                    results.Add(healthResult);
                }
            }

            return(results);
        }
コード例 #11
0
        public void EnsureHttpEncoded(string packageUrl)
        {
            PackageURL purl = new(packageUrl);

            if (purl.Name is not null && purl.Type is not null)
            {
                BaseProjectManager?manager = ProjectManagerFactory.ConstructPackageManager(purl, null);
                if (manager is not null)
                {
                    foreach ((string mutationPurlString, _) in manager.EnumerateSquatCandidates(purl) !)
                    {
                        PackageURL mutatedPurl = new(mutationPurlString);

                        if (IsUrlEncoded(mutatedPurl.Name) || (mutatedPurl.HasNamespace() && IsUrlEncoded(mutatedPurl.Namespace)))
                        {
                            return;
                        }
                    }
                }
            }
            Assert.Fail();
        }
コード例 #12
0
        /// <summary>
        /// Constructor - creates a class object for downloading packages.
        /// </summary>
        /// <param name="purl">The package to download.</param>
        /// <param name="projectManagerFactory">The <see cref="ProjectManagerFactory"/> to use to get the project managers.</param>
        /// <param name="destinationDir">The directory where the package needs to be downloaded to.</param>
        /// <param name="doCaching">Check and use the cache if it exists - create if not.</param>
        public PackageDownloader(PackageURL purl, ProjectManagerFactory projectManagerFactory, string?destinationDir = null, bool doCaching = false)
        {
            if (purl == null)
            {
                throw new ArgumentNullException(nameof(purl), "PackageURL cannot be null");
            }

            doCache = doCaching;
            // if we are told to use caching, and it exists, believe that caching is still doable
            actualCaching = (doCaching && !string.IsNullOrEmpty(destinationDir) && Directory.Exists(destinationDir));

            // if no destination specified, dump the package in the temp directory
            if (string.IsNullOrEmpty(destinationDir))
            {
                usingTemp            = true;
                destinationDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            }
            else
            {
                destinationDirectory = destinationDir;
            }

            packageManager = projectManagerFactory.CreateProjectManager(purl, destinationDirectory);
            if (packageManager == null)
            {
                // Cannot continue without a package manager.
                throw new ArgumentException($"Invalid Package URL type: {purl.Type}", nameof(purl.Type));
            }
            PackageVersions = new List <PackageURL>();
            if (purl.Version == null || purl.Version.Equals("*"))
            {
                // figure out which version(s) we need to process
                PackageVersions = GetPackageVersionsToProcess(purl).Result;
            }
            else
            {
                PackageVersions.Add(purl);
            }
        }
コード例 #13
0
        [DataRow("pkg:nuget/Microsoft.CST.OAT", "pkg:nuget/microsoft.cst.oat.net")] // SuffixAdded, .net
        public void GenerateManagerSpecific(string packageUrl, string expectedToFind)
        {
            PackageURL purl = new(packageUrl);

            if (purl.Name is not null && purl.Type is not null)
            {
                BaseProjectManager?manager = ProjectManagerFactory.ConstructPackageManager(purl, null);
                if (manager is not null)
                {
                    foreach ((string _, IList <Mutation> mutations) in manager.EnumerateSquatCandidates(purl) !)
                    {
                        foreach (Mutation mutation in mutations)
                        {
                            if (mutation.Mutated.Equals(expectedToFind, StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }
                        }
                    }
                }
            }
            Assert.Fail($"Did not find expected mutation {expectedToFind}");
        }
コード例 #14
0
        public async Task DetectSquats(string packageUrl, bool generateSquats, bool expectedToHaveSquats)
        {
            PackageURL purl = new(packageUrl);

            IEnumerable <string>?validSquats = null;

            // Only populate validSquats if we want to generate squats.
            if (generateSquats)
            {
                validSquats = ProjectManagerFactory.GetDefaultManagers()[purl.Type].Invoke()?.EnumerateSquatCandidates(purl)?.Keys;
            }

            // Construct the mocked IHttpClientFactory
            IHttpClientFactory httpClientFactory = FindSquatsHelper.SetupHttpCalls(purl: purl, validSquats: validSquats);

            // Construct the manager overrides with the mocked IHttpClientFactory.
            Dictionary <string, ProjectManagerFactory.ConstructProjectManager> managerOverrides = ProjectManagerFactory.GetDefaultManagers(httpClientFactory);

            IManagerPackageActions <NuGetPackageVersionMetadata>?nugetPackageActions = PackageActionsHelper <NuGetPackageVersionMetadata> .SetupPackageActions(
                purl);

            // Override the NuGet constructor to add the mocked NuGetPackageActions.
            managerOverrides[NuGetProjectManager.Type] =
                _ => new NuGetProjectManager(".", nugetPackageActions, httpClientFactory);

            ProjectManagerFactory projectManagerFactory = new(managerOverrides);
            FindSquatsTool        fst = new(projectManagerFactory);

            FindSquatsTool.Options options = new()
            {
                Quiet   = true,
                Targets = new string[] { packageUrl }
            };
            (string output, int numSquats)result = await fst.RunAsync(options);

            Assert.IsTrue(expectedToHaveSquats ? result.numSquats > 0 : result.numSquats == 0);
        }
コード例 #15
0
ファイル: HealthTool.cs プロジェクト: microsoft/OSSGadget
        public async Task <HealthMetrics?> CheckHealth(PackageURL purl)
        {
            BaseProjectManager?packageManager = ProjectManagerFactory.CreateProjectManager(purl);

            if (packageManager != null)
            {
                string?content = await packageManager.GetMetadataAsync(purl);

                if (!string.IsNullOrWhiteSpace(content))
                {
                    RepoSearch repoSearcher = new RepoSearch(ProjectManagerFactory);
                    foreach ((PackageURL githubPurl, double _) in await repoSearcher.ResolvePackageLibraryAsync(purl))
                    {
                        try
                        {
                            GitHubHealthAlgorithm?healthAlgorithm = new GitHubHealthAlgorithm(githubPurl);
                            HealthMetrics?        health          = await healthAlgorithm.GetHealth();

                            return(health);
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn(ex, "Unable to calculate health for {0}: {1}", githubPurl, ex.Message);
                        }
                    }
                }
                else
                {
                    Logger.Warn("No metadata found for {0}", purl.ToString());
                }
            }
            else
            {
                throw new ArgumentException($"Invalid Package URL type: {purl.Type}");
            }
            return(null);
        }
コード例 #16
0
ファイル: HealthTool.cs プロジェクト: microsoft/OSSGadget
 public HealthTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }
コード例 #17
0
        public async Task NewtonsoftMutations_Succeeds_Async()
        {
            // arrange
            PackageURL newtonsoft = new("pkg:nuget/[email protected]");

            string[] squattingPackages = new[]
            {
                "pkg:nuget/newtons0ft.json", // ["AsciiHomoglyph","CloseLetters"]
                "pkg:nuget/newtousoft.json", // ["AsciiHomoglyph"]
                "pkg:nuget/newtonsoft.jsan", // ["AsciiHomoglyph","VowelSwap"]
                "pkg:nuget/mewtonsoft.json", // ["AsciiHomoglyph","BitFlip","CloseLetters"]
                "pkg:nuget/bewtonsoft.json", // ["CloseLetters"]
                "pkg:nuget/newtohsoft.json", // ["CloseLetters"]
            };

            IHttpClientFactory httpClientFactory =
                FindSquatsHelper.SetupHttpCalls(purl: newtonsoft, validSquats: squattingPackages);

            IManagerPackageActions <NuGetPackageVersionMetadata> packageActions = PackageActionsHelper <NuGetPackageVersionMetadata> .SetupPackageActions(newtonsoft, validSquats : squattingPackages) ?? throw new InvalidOperationException();

            Dictionary <string, ProjectManagerFactory.ConstructProjectManager> overrideDict = ProjectManagerFactory.GetDefaultManagers(httpClientFactory);

            overrideDict[NuGetProjectManager.Type] = directory =>
                                                     new NuGetProjectManager(directory, packageActions, httpClientFactory);

            FindPackageSquats findPackageSquats = new(new ProjectManagerFactory(overrideDict), newtonsoft);

            // act
            IDictionary <string, IList <Mutation> >?squatCandidates   = findPackageSquats.GenerateSquatCandidates();
            List <FindPackageSquatResult>           existingMutations = await findPackageSquats.FindExistingSquatsAsync(squatCandidates, new MutateOptions()
            {
                UseCache = false
            }).ToListAsync();

            Assert.IsNotNull(existingMutations);
            Assert.IsTrue(existingMutations.Any());
            string[] resultingMutationNames = existingMutations.Select(m => m.MutatedPackageUrl.ToString()).ToArray();
            CollectionAssert.AreEquivalent(squattingPackages, resultingMutationNames);
        }
コード例 #18
0
ファイル: DiffTool.cs プロジェクト: microsoft/OSSGadget
 public DiffTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }
コード例 #19
0
 public DetectBackdoorTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
     RULE_DIRECTORY = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "BackdoorRules");
 }
コード例 #20
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);
        }
コード例 #21
0
 public CharacteristicTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }
コード例 #22
0
        /// <summary>
        ///     Main entrypoint for the download program.
        /// </summary>
        /// <param name="args"> parameters passed in from the user </param>
        private static async Task Main(string[] args)
        {
            DetectCryptographyTool detectCryptographyTool = new DetectCryptographyTool();

            Logger.Info($"Microsoft OSS Gadget - {TOOL_NAME} {VERSION}");

            detectCryptographyTool.ParseOptions(args);

            // select output destination and format
            detectCryptographyTool.SelectOutput((string?)detectCryptographyTool.Options["output-file"] ?? "");
            IOutputBuilder outputBuilder = detectCryptographyTool.SelectFormat((string?)detectCryptographyTool.Options["format"] ?? "text");

            if (detectCryptographyTool.Options["target"] is IList <string> targetList && targetList.Count > 0)
            {
                var sb = new StringBuilder();
                foreach (var target in targetList)
                {
                    sb.Clear();
                    try
                    {
                        List <IssueRecord>?results = null;
                        if (target.StartsWith("pkg:", StringComparison.InvariantCulture))
                        {
                            var purl = new PackageURL(target);
                            results = await(detectCryptographyTool.AnalyzePackage(purl,
                                                                                  (string?)detectCryptographyTool.Options["download-directory"] ?? string.Empty,
                                                                                  (bool?)detectCryptographyTool.Options["use-cache"] == true) ??
                                            Task.FromResult(new List <IssueRecord>()));
                        }
                        else if (Directory.Exists(target))
                        {
                            results = await(detectCryptographyTool.AnalyzeDirectory(target) ??
                                            Task.FromResult(new List <IssueRecord>()));
                        }
                        else if (File.Exists(target))
                        {
                            string?targetDirectoryName = null;
                            while (targetDirectoryName == null || Directory.Exists(targetDirectoryName))
                            {
                                targetDirectoryName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                            }
                            var projectManager = ProjectManagerFactory.CreateBaseProjectManager(targetDirectoryName);

#pragma warning disable SCS0018 // Path traversal: injection possible in {1} argument passed to '{0}'
                            var path = await projectManager.ExtractArchive("temp", File.ReadAllBytes(target));

#pragma warning restore SCS0018 // Path traversal: injection possible in {1} argument passed to '{0}'

                            results = await(detectCryptographyTool.AnalyzeDirectory(path) ??
                                            Task.FromResult(new List <IssueRecord>()));;

                            // Clean up after ourselves
                            try
                            {
                                if (targetDirectoryName != null)
                                {
                                    Directory.Delete(targetDirectoryName, true);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Warn("Unable to delete {0}: {1}", targetDirectoryName, ex.Message);
                            }
                        }

                        if (results == null)
                        {
                            Logger.Warn("Error generating results, was null.");
                        }
                        else if (!results.Any())
                        {
                            sb.AppendLine($"[ ] {target} - This software package does NOT appear to implement cryptography.");
                        }
                        else
                        {
                            var shortTags = results.SelectMany(r => r.Issue.Rule.Tags ?? Array.Empty <string>())
                                            .Distinct()
                                            .Where(t => t.StartsWith("Cryptography.Implementation."))
                                            .Select(t => t.Replace("Cryptography.Implementation.", ""));
                            var otherTags = results.SelectMany(r => r.Issue.Rule.Tags ?? Array.Empty <string>())
                                            .Distinct()
                                            .Where(t => !t.StartsWith("Cryptography.Implementation."));

                            if (shortTags.Any())
                            {
                                sb.AppendLine($"[X] {target} - This software package appears to implement {string.Join(", ", shortTags)}.");
                            }

                            if (otherTags.Contains("Cryptography.GenericImplementation.HighDensityOperators"))
                            {
                                sb.AppendLine($"[X] {target} - This software package has a high-density of cryptographic operators.");
                            }
                            else
                            {
                                sb.AppendLine($"[ ] {target} - This software package does NOT have a high-density of cryptographic operators.");
                            }

                            if (otherTags.Contains("Cryptography.GenericImplementation.CryptographicWords"))
                            {
                                sb.AppendLine($"[X] {target} - This software package contains words that suggest cryptography.");
                            }
                            else
                            {
                                sb.AppendLine($"[ ] {target} - This software package does NOT contains words that suggest cryptography.");
                            }

                            if ((bool?)detectCryptographyTool.Options["verbose"] == true)
                            {
                                var items = results.GroupBy(k => k.Issue.Rule.Name).OrderByDescending(k => k.Count());
                                foreach (var item in items)
                                {
                                    sb.AppendLine();
                                    sb.AppendLine($"There were {item.Count()} finding(s) of type [{item.Key}].");

                                    foreach (var result in results)
                                    {
                                        if (result.Issue.Rule.Name == item.Key)
                                        {
                                            sb.AppendLine($" {result.Filename}:");
                                            if (result.Issue.Rule.Id == "_CRYPTO_DENSITY")
                                            {
                                                // No excerpt for cryptogrpahic density
                                                // TODO: We stuffed the density in the unused 'Description' field. This is code smell.
                                                sb.AppendLine($"  | The maximum cryptographic density is {result.Issue.Rule.Description}.");
                                            }
                                            else
                                            {
                                                // Show the excerpt
                                                foreach (var line in result.TextSample.Split(new char[] { '\n', '\r' }))
                                                {
                                                    if (!string.IsNullOrWhiteSpace(line))
                                                    {
                                                        sb.AppendLine($"  | {line.Trim()}");
                                                    }
                                                }
                                            }
                                            sb.AppendLine();
                                        }
                                    }
                                }
                            }

                            if (Logger.IsDebugEnabled)
                            {
                                foreach (var result in results)
                                {
                                    Logger.Debug($"Result: {result.Filename} {result.Issue.Rule.Name} {result.TextSample}");
                                }
                            }
                        }
                        Console.WriteLine(sb.ToString());
                    }
                    catch (Exception ex)
                    {
                        Logger.Warn(ex, "Error processing {0}: {1}", target, ex.Message);
                        Logger.Warn(ex.StackTrace);
                    }
                }
            }
            else
            {
                Logger.Warn("No target provided; nothing to analyze.");
                DetectCryptographyTool.ShowUsage();
                Environment.Exit(1);
            }
        }
コード例 #23
0
 public FindSquatsTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }
コード例 #24
0
 public DownloadTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }
コード例 #25
0
ファイル: OssGadgetLib.cs プロジェクト: microsoft/OSSGadget
 protected OssGadgetLib(ProjectManagerFactory projectManagerFactory, string directory = ".")
 {
     ProjectManagerFactory = Check.NotNull(nameof(projectManagerFactory), projectManagerFactory);
     Directory             = directory;
 }
コード例 #26
0
 public ReproducibleTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }
コード例 #27
0
 public DetectCryptographyTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }
コード例 #28
0
 public RiskCalculatorTool(ProjectManagerFactory projectManagerFactory) : base(projectManagerFactory)
 {
 }