Exemple #1
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonInspectorConfig config = new AmazonInspectorConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonInspectorClient client = new AmazonInspectorClient(creds, config);

            ListFindingsResponse resp = new ListFindingsResponse();

            do
            {
                ListFindingsRequest req = new ListFindingsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.ListFindings(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.FindingArns)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Exemple #2
0
        static void Main(string[] args)
        {
            String detectorId = "cdc02b15f9f520a8882c959g3e95c24b";

            FindingCriteria criteria = new FindingCriteria();

            Condition condition = new Condition();

            condition.Eq.Add("Recon:EC2/PortProbeUnprotectedPort");
            condition.Eq.Add("Recon:EC2/Portscan");

            criteria.Criterion.Add("type", condition);

            using (var gdClient = new AmazonGuardDutyClient(RegionEndpoint.USWest2))
            {
                var request = new ListFindingsRequest
                {
                    DetectorId      = detectorId,
                    FindingCriteria = criteria,
                };

                Task <ListFindingsResponse> response = gdClient.ListFindingsAsync(request);
                response.Wait();

                foreach (String findingId in response.Result.FindingIds)
                {
                    Console.WriteLine(findingId.ToString());
                }
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            ListFindingsRequest request;

            try
            {
                request = new ListFindingsRequest
                {
                    SecurityAssessmentId = SecurityAssessmentId,
                    OpcRequestId         = OpcRequestId,
                    Severity             = Severity,
                    Limit = Limit,
                    Page  = Page,
                    CompartmentIdInSubtree = CompartmentIdInSubtree,
                    AccessLevel            = AccessLevel,
                    FindingKey             = FindingKey
                };
                IEnumerable <ListFindingsResponse> responses = GetRequestDelegate().Invoke(request);
                foreach (var item in responses)
                {
                    response = item;
                    WriteOutput(response, response.Items, true);
                }
                if (!ParameterSetName.Equals(AllPageSet) && !ParameterSetName.Equals(LimitSet) && response.OpcNextPage != null)
                {
                    WriteWarning("This operation supports pagination and not all resources were returned. Re-run using the -All option to auto paginate and list all resources.");
                }
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
        /// <summary>Snippet for ListFindings</summary>
        public async Task ListFindingsRequestObjectAsync()
        {
            // Snippet: ListFindingsAsync(ListFindingsRequest, CallSettings)
            // Create client
            WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();

            // Initialize request argument(s)
            ListFindingsRequest request = new ListFindingsRequest
            {
                Parent = "",
                Filter = "",
            };
            // Make the request
            PagedAsyncEnumerable <ListFindingsResponse, Finding> response = webSecurityScannerClient.ListFindingsAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Finding item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListFindingsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Finding item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int            pageSize   = 10;
            Page <Finding> singlePage = await response.ReadPageAsync(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Finding item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        static void Main(string[] args)
        {
            String detectorId = "cdc02bexample0a8882c959g3e95c24b"; // set your detector id

            //instantiate a FindingCriteria obj
            FindingCriteria criteria = new FindingCriteria();

            //instantiate a Condtion obj
            Condition condition = new Condition();

            //set the comparison operation e.g. "EQ" value that your condition is looking for
            //as well as add the values that you are looking for to the List<String>
            condition.Eq.Add("Recon:EC2/PortProbeUnprotectedPort"); //include results for this value
            condition.Eq.Add("Recon:EC2/Portscan");                 //include results for this value

            //add your Key and condition to your criteria obj
            criteria.Criterion.Add("type", condition);

            // instantiate a GD Service client ob
            using (IAmazonGuardDuty gdClient = new AmazonGuardDutyClient())
            {
                ListFindingsRequest request = new ListFindingsRequest
                {
                    DetectorId      = detectorId,
                    FindingCriteria = criteria
                };

                // Make GD service call and get back the response.
                ListFindingsResponse response = gdClient.ListFindings(request);

                foreach (String findingId in response.FindingIds)
                {
                    Console.WriteLine(findingId.ToString());
                }

                Console.ReadLine();
            }
        }
Exemple #6
0
        static int Main(string[] args)
        {
            foreach (var line in titleBanner)
            {
                Console.WriteLine(line);
            }

            if (args == null || args.Length == 0)
            {
                // Help screen
                foreach (var line in helpScreen)
                {
                    Console.WriteLine(line);
                }
                System.Environment.Exit(-1);
            }

            Options options = null;

            Parser.Default.ParseArguments <Options>(args)
            .WithParsed(o => options = o)
            .WithNotParsed(errors =>
            {
                foreach (var error in errors)
                {
                    Console.WriteLine(error);
                }
                System.Environment.Exit(-2);
            });

            // Setup AWS credentials
            var chain = new CredentialProfileStoreChain();

            AWSCredentials awsCredentials;
            RegionEndpoint awsRegion;

            if (!string.IsNullOrWhiteSpace(options.Profile))
            {
                if (!chain.TryGetAWSCredentials(options.Profile, out awsCredentials))
                {
                    Console.WriteLine($"Unable to retrieve credentials for profile {options.Profile}");
                    System.Environment.Exit(-3);
                    return(-3);
                }

                CredentialProfile credentialProfile;
                if (!chain.TryGetProfile(options.Profile, out credentialProfile))
                {
                    Console.WriteLine($"Unable to retrieve credential profile for {options.Profile}");
                    System.Environment.Exit(-4);
                    return(-4);
                }

                awsRegion = credentialProfile.Region ?? RegionEndpoint.GetBySystemName(options.Region);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(options.AccessKeyId))
                {
                    Console.Error.WriteLine("No profile was specified, but an access key ID was not provided either.");
                    System.Environment.Exit(-5);
                    return(-5);
                }

                if (string.IsNullOrWhiteSpace(options.AccessKeySecret))
                {
                    Console.Error.WriteLine("No profile was specified, but an access key secret was not provided either.");
                    System.Environment.Exit(-6);
                    return(-6);
                }

                awsCredentials = new BasicAWSCredentials(options.AccessKeyId, options.AccessKeySecret);
                awsRegion      = RegionEndpoint.GetBySystemName(options.Region);
            }

            var cts = new CancellationTokenSource();

            var getFindingsTask = Task.Run(new Func <Task <Tuple <object, Exception> > >(async() =>
            {
                var client = new AmazonGuardDutyClient(awsCredentials, awsRegion);

                var detectorRequest  = new ListDetectorsRequest();
                var detectorResponse = await client.ListDetectorsAsync(detectorRequest, cts.Token);

                dynamic bundle      = new ExpandoObject();
                bundle.type         = "bundle";
                bundle.id           = $"guardduty-stix-{DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", System.Globalization.CultureInfo.InvariantCulture)}";
                bundle.spec_version = "2.0";

                var objects = new List <object>();

                foreach (var detectorId in detectorResponse.DetectorIds)
                {
                    var listFindingsRequest = new ListFindingsRequest()
                    {
                        DetectorId = detectorId,

                        /*FindingCriteria = new FindingCriteria
                         * {
                         *  Criterion = { { "service.archived", new Condition { Eq = { "FALSE" } } } }
                         * }*/
                    };

                    try
                    {
                        // Get list of findings
                        var listFindingsResponse = await client.ListFindingsAsync(listFindingsRequest, cts.Token);

                        // For the list, get the details
                        var getFindingsRequest = new GetFindingsRequest()
                        {
                            DetectorId = detectorId,
                            FindingIds = listFindingsResponse.FindingIds
                        };
                        var getFindingsResponse = await client.GetFindingsAsync(getFindingsRequest, cts.Token);

                        foreach (var finding in getFindingsResponse.Findings)
                        {
                            var sdo = await ConvertFindingToStixAsync(finding);
                            objects.Add(sdo);
                        }
                    }
                    catch (Exception e)
                    {
                        await Console.Error.WriteLineAsync(e.ToString());
                        return(new Tuple <object, Exception>(null, e));
                    }
                }

                bundle.objects = objects;
                return(new Tuple <object, Exception>(bundle, null));
            }));

            if (!Task.WaitAll(new[] { getFindingsTask }, 60000, cts.Token))
            {
                Console.Error.WriteLine("Failed to complete within 60 seconds, aborted.");
                System.Environment.Exit(-7);
                return(-7);
            }

            var result = getFindingsTask.Result;

            if (result.Item2 != null)
            {
                Console.Error.WriteLine($"Unable to parse output: {result.Item2.ToString()}");
                System.Environment.Exit(-8);
                return(-8);
            }

            if (string.IsNullOrWhiteSpace(options.OutputFile))
            {
                Console.Out.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(result.Item1));
            }
            else
            {
                try
                {
                    using (var fs = new FileStream(options.OutputFile, FileMode.Create, FileAccess.Write))
                        using (var sw = new StreamWriter(fs))
                        {
                            sw.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result.Item1));
                        }

                    Console.Out.WriteLine($"Output saved to file {options.OutputFile}");
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine($"Unable to write file: {e.ToString()}");
                    System.Environment.Exit(-9);
                    return(-9);
                }
            }

            return(0);
        }