├── NOTICE ├── images ├── sample-card.png ├── guarddutybadge.png ├── guarddutylarge.png ├── guarddutysmall.png └── skill-diagram.png ├── lambda ├── alexa-ask-guardduty-lambda.zip └── lambda_function.py ├── .github └── PULL_REQUEST_TEMPLATE.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── README.md ├── cloudformation └── alexa-ask-guardduty.template ├── alexa └── alexa_ask_guardduty_skill.json └── LICENSE /NOTICE: -------------------------------------------------------------------------------- 1 | Amazon Guardduty Alexa Sample 2 | Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /images/sample-card.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-guardduty-alexa-sample/HEAD/images/sample-card.png -------------------------------------------------------------------------------- /images/guarddutybadge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-guardduty-alexa-sample/HEAD/images/guarddutybadge.png -------------------------------------------------------------------------------- /images/guarddutylarge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-guardduty-alexa-sample/HEAD/images/guarddutylarge.png -------------------------------------------------------------------------------- /images/guarddutysmall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-guardduty-alexa-sample/HEAD/images/guarddutysmall.png -------------------------------------------------------------------------------- /images/skill-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-guardduty-alexa-sample/HEAD/images/skill-diagram.png -------------------------------------------------------------------------------- /lambda/alexa-ask-guardduty-lambda.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-guardduty-alexa-sample/HEAD/lambda/alexa-ask-guardduty-lambda.zip -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/aws-samples/amazon-guardduty-alexa-sample/issues), or [recently closed](https://github.com/aws-samples/amazon-guardduty-alexa-sample/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws-samples/amazon-guardduty-alexa-sample/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/aws-samples/amazon-guardduty-alexa-sample/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Ask GuardDuty Sample Alexa Skill 3 | 4 | Deploy a sample custom Alexa skill and use an Alexa-enabled device, such as Amazon Echo to obtain information about GuardDuty findings across your AWS accounts and regions. This will enable you to quickly understand current GuardDuty finding statistics and details through the Alexa voice interface. The information provided by this sample skill is intended to give you a broad overview of GuardDuty finding statistics, severities and descriptions. With this information, you may wish to log into the GuardDuty console or another analysis tool to drill further into the findings data. 5 | 6 | Note: A basic understanding of Alexa Custom Skills is helpful for deploying the sample skill described in this blog post. If you are not already familiar with Alexa custom skill concepts and terminology, you may want to review the [documentation resources](https://developer.amazon.com/docs/custom-skills/understanding-custom-skills.html). 7 | 8 | Solution overview 9 | The solution diagram below is followed by a description of the flow of events. The CloudFormation template creates the Lambda function for the sample Alexa skill. 10 | 11 | ## Solution Diagram 12 | ![architecture diagram](images/skill-diagram.png) 13 | 14 | Here is how the solution works, as shown in the preceding numbered diagram: 15 | 1. The user opens the skill; "Alexa, ask GuardDuty" or "Alexa, open GuardDuty". 16 | 2. After opening the skill, the user states a supported intent, such as "Get flash briefing." 17 | 3. The Alexa service passes the intent and the custom skill uses the Lambda function to call the GuardDuty API and request the information. 18 | 4. The GuardDuty service returns the requested information and the Lambda function returns the response to the Alexa service. 19 | 5. The Alexa service delivers the audio response via the Alexa-enabled device. 20 | 21 | Prerequisites 22 | In order to complete the steps in this blog post, make sure you have the following prerequisites: 23 | 1. An AWS account with GuardDuty enabled in one or more AWS regions. 24 | 2. An Alexa-enabled device, such as an Amazon Echo. 25 | 3. An Amazon Developer Account. 26 | 4. (Optional) An AWS account configured with [Alexa for Business](https://aws.amazon.com/alexaforbusiness/). 27 | 28 | ## Features 29 | - Multi-Region support 30 | - DetectorId auto discovery 31 | - "Ask GuardDuty to get Flash Briefing" powered by [get_findings_statistics](http://boto3.readthedocs.io/en/latest/reference/services/guardduty.html#GuardDuty.Client.get_findings_statistics). Uses an environment variable with comma separated region ids. 32 | - Response provides high / med / low severity labels 33 | - Instance Id / IP redaction 34 | - Help 35 | - Error detection for disabled / regions not configured 36 | - CloudFormation deployment for Lambda component 37 | 38 | ## Intent examples 39 | - *Open GuardDuty* 40 | - *Ask GuardDuty to get Flash Briefing* 41 | - *Get statistics for Virginia* 42 | - *Get high severity findings for Oregon* 43 | - *help* 44 | 45 | ## Variables 46 | **MAXRESP = os.environ['MAXRESP']** 47 | 48 | Max number of findings to return. Although 50 can be returned without paginating, 49 | keeping this below 15 is a good idea to avoid Alexa size limit and general sanity preservation. 50 | 51 | **FLASHREGIONS = os.environ['FLASHREGIONS']** 52 | 53 | Comma separated list of region codes with NO spaces to include in flash briefing stats. 54 | ***Make sure GuardDuty is enabled in regions declared*** 55 | 56 | ## Deployment into Personal Amazon Developer Account 57 | 58 | 1. Deploy CloudFormation Template. 59 | 2. Go to [Amazon Dev Console](https://developer.amazon.com/alexa/console/ask) 60 | 2. Click Create Skill. 61 | 3. For the name, enter Ask Amazon GuardDuty and click Next. 62 | 4. Paste Skill JSON into Skill Builder JSON Editor in **Build**. Save / Build 63 | 5. Get Outputs: AlexaAskGDSkillArn from stack and paste into Lambda **Default Region** endpoint field in the skill **Endpoint**. Save 64 | 6. Test with Alexa-enabled device. 65 | 66 | **Note:** Since you are not publishing this skill, you do not need to complete the **Launch** section of the configuration. The skill will remain in the Development status and will only be available for Alexa devices linked to the Amazon developer account used to create the skill. Anyone with physical access to the linked Alexa-enabled device can use the custom skill. As a best practice, we recommend that you delete the Lambda trigger created by the CloudFormation template and add a new one with Skill ID verification enabled. [Learn more.](https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-an-aws-lambda-function.html#configuring-the-alexa-skills-kit-trigger) You can also deploy this sample skill using Alexa for Business. For more info, check out ***[Alexa for Business Deployment](https://aws.amazon.com/alexaforbusiness/getting-started/)*** 67 | 68 | 69 | ## License 70 | 71 | This library is licensed under the Apache 2.0 License. 72 | -------------------------------------------------------------------------------- /cloudformation/alexa-ask-guardduty.template: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: This template deploys the Lambda Function for the Sample Alexa skill, Ask GuardDuty. **NOTICE** 3 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of 4 | the License is located at http://aws.amazon.com/apache2.0/ 5 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 6 | ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 7 | 8 | Parameters: 9 | MAXRESP: 10 | Default: "5" 11 | Description: Maximum number of findings to return. 5-10 recommended due to verbosity. 12 | Type: Number 13 | AllowedValues: [5,10,15] 14 | FLASHREGIONS: 15 | Description: Comma separated list of region codes with NO spaces to include in flash briefing stats. Minimum of 1 region required. 16 | E.g. "us-east-1,us-west-1,us-west-2" GuardDuty MUST be enabled in declared regions. 17 | Type: String 18 | AllowedPattern: ^[0-9a-z-,]*$ 19 | ArtifactsBucket: 20 | Description: S3 bucket with artifact files (Lambda functions, templates, html files, etc.). Leave default for N. Virginia. 21 | Type: String 22 | Default: awsiammedia 23 | AllowedPattern: ^[0-9a-zA-Z]+([0-9a-zA-Z-]*[0-9a-zA-Z])*$ 24 | ConstraintDescription: ArtifactsBucket S3 bucket name can include numbers, lowercase letters, uppercase letters, and hyphens (-). 25 | It cannot start or end with a hyphen (-). 26 | ArtifactsPrefix: 27 | Description: Path in the S3 bucket containing artifact files. Leave default for N. Virginia. 28 | Type: String 29 | Default: public/sample/GuardDutyStatisticsFindings/ 30 | AllowedPattern: ^[0-9a-zA-Z-/]*$ 31 | ConstraintDescription: ArtifactsPrefix key prefix can include numbers, lowercase letters, uppercase letters, hyphens (-), 32 | and forward slash (/). 33 | Metadata: 34 | AWS::CloudFormation::Interface: 35 | ParameterGroups: 36 | - Label: 37 | default: Alexa Ask GuardDuty Configuration 38 | Parameters: 39 | - FLASHREGIONS 40 | - MAXRESP 41 | - Label: 42 | default: Artifacts Configuration 43 | Parameters: 44 | - ArtifactsBucket 45 | - ArtifactsPrefix 46 | 47 | Resources: 48 | AlexaAskGDLambdaSkill: 49 | Type: AWS::Lambda::Function 50 | Properties: 51 | Description: "Ask Guard Duty Sample Alexa Skill" 52 | Handler : "lambda_function.lambda_handler" 53 | MemorySize: 128 54 | Timeout: 300 55 | Role: !GetAtt AlexaAskGDLambdaRole.Arn 56 | Runtime : "python3.6" 57 | Environment: 58 | Variables: 59 | MAXRESP: !Ref MAXRESP 60 | FLASHREGIONS: !Ref FLASHREGIONS 61 | Code: 62 | S3Bucket: !Ref ArtifactsBucket 63 | S3Key: !Sub ${ArtifactsPrefix}alexa-ask-guardduty-lambda.zip 64 | AlexaAskGDLambdaRole: 65 | Type: AWS::IAM::Role 66 | Properties: 67 | AssumeRolePolicyDocument: 68 | Version: "2012-10-17" 69 | Statement: 70 | - 71 | Effect: "Allow" 72 | Principal: 73 | Service: 74 | - "lambda.amazonaws.com" 75 | Action: 76 | "sts:AssumeRole" 77 | Path: "/" 78 | AlexaAskGDLambdaPolicy: 79 | Type: AWS::IAM::Policy 80 | Properties: 81 | PolicyName: "askgd_lambda_consumer_policy" 82 | PolicyDocument: 83 | Version: 2012-10-17 84 | Statement: 85 | - 86 | Effect: "Allow" 87 | Action: 88 | - "logs:CreateLogGroup" 89 | - "logs:CreateLogStream" 90 | - "logs:PutLogEvents" 91 | Resource: "arn:aws:logs:*:*:*" 92 | - 93 | Effect: "Allow" 94 | Action: 95 | - "guardduty:ListDetectors" 96 | - "guardduty:ListFindings" 97 | - "guardduty:GetFindingsStatistics" 98 | - "guardduty:GetFindings" 99 | Resource: "*" 100 | Roles: 101 | - 102 | Ref: "AlexaAskGDLambdaRole" 103 | AlexaAskGDPermission: 104 | Type: AWS::Lambda::Permission 105 | Properties: 106 | FunctionName: !GetAtt AlexaAskGDLambdaSkill.Arn 107 | Action: lambda:InvokeFunction 108 | Principal: 'alexa-appkit.amazon.com' 109 | 110 | Outputs: 111 | AlexaAskGDSkillArn: 112 | Description: Use as endpoint in Amazon developer portal. 113 | Value: 114 | !GetAtt AlexaAskGDLambdaSkill.Arn 115 | AlexaAskGDLambdaSkill: 116 | Description: Ask GuardDuty Sample Alexa Skill Lambda. 117 | Value: !Sub https://console.aws.amazon.com/lambda/home?region=${AWS::Region}#/functions/${AlexaAskGDLambdaSkill} 118 | Region: 119 | Description: Region of the stack. 120 | Value: 121 | Ref: AWS::Region 122 | -------------------------------------------------------------------------------- /alexa/alexa_ask_guardduty_skill.json: -------------------------------------------------------------------------------- 1 | { 2 | "languageModel": { 3 | "types": [ 4 | { 5 | "name": "REGION", 6 | "values": [ 7 | { 8 | "id": null, 9 | "name": { 10 | "value": "Virginia", 11 | "synonyms": [] 12 | } 13 | }, 14 | { 15 | "id": null, 16 | "name": { 17 | "value": "Mumbai", 18 | "synonyms": [] 19 | } 20 | }, 21 | { 22 | "id": null, 23 | "name": { 24 | "value": "London", 25 | "synonyms": [] 26 | } 27 | }, 28 | { 29 | "id": null, 30 | "name": { 31 | "value": "Ireland", 32 | "synonyms": [] 33 | } 34 | }, 35 | { 36 | "id": null, 37 | "name": { 38 | "value": "Seoul", 39 | "synonyms": [] 40 | } 41 | }, 42 | { 43 | "id": null, 44 | "name": { 45 | "value": "Tokyo", 46 | "synonyms": [] 47 | } 48 | }, 49 | { 50 | "id": null, 51 | "name": { 52 | "value": "Canada", 53 | "synonyms": [] 54 | } 55 | }, 56 | { 57 | "id": null, 58 | "name": { 59 | "value": "Sao Paulo", 60 | "synonyms": [] 61 | } 62 | }, 63 | { 64 | "id": null, 65 | "name": { 66 | "value": "Singapore", 67 | "synonyms": [] 68 | } 69 | }, 70 | { 71 | "id": null, 72 | "name": { 73 | "value": "Sydney", 74 | "synonyms": [] 75 | } 76 | }, 77 | { 78 | "id": null, 79 | "name": { 80 | "value": "Frankfurt", 81 | "synonyms": [] 82 | } 83 | }, 84 | { 85 | "id": null, 86 | "name": { 87 | "value": "Ohio", 88 | "synonyms": [] 89 | } 90 | }, 91 | { 92 | "id": null, 93 | "name": { 94 | "value": "California", 95 | "synonyms": [] 96 | } 97 | }, 98 | { 99 | "id": null, 100 | "name": { 101 | "value": "Oregon", 102 | "synonyms": [] 103 | } 104 | }, 105 | { 106 | "id": null, 107 | "name": { 108 | "value": "Northern Virginia", 109 | "synonyms": [] 110 | } 111 | }, 112 | { 113 | "id": null, 114 | "name": { 115 | "value": "Northern California", 116 | "synonyms": [] 117 | } 118 | }, 119 | { 120 | "id": null, 121 | "name": { 122 | "value": "Central", 123 | "synonyms": [] 124 | } 125 | } 126 | ] 127 | }, 128 | { 129 | "name": "SEVNAME", 130 | "values": [ 131 | { 132 | "id": null, 133 | "name": { 134 | "value": "low", 135 | "synonyms": [] 136 | } 137 | }, 138 | { 139 | "id": null, 140 | "name": { 141 | "value": "medium", 142 | "synonyms": [] 143 | } 144 | }, 145 | { 146 | "id": null, 147 | "name": { 148 | "value": "high", 149 | "synonyms": [] 150 | } 151 | } 152 | ] 153 | } 154 | ], 155 | "intents": [ 156 | { 157 | "name": "AMAZON.CancelIntent", 158 | "samples": [] 159 | }, 160 | { 161 | "name": "AMAZON.HelpIntent", 162 | "samples": [] 163 | }, 164 | { 165 | "name": "AMAZON.StopIntent", 166 | "samples": [] 167 | }, 168 | { 169 | "name": "FlashBriefing", 170 | "samples": [ 171 | "FlashBriefing get my flash briefing", 172 | "FlashBriefing get flash briefing", 173 | "FlashBriefing get global statistics", 174 | "FlashBriefing get global stats" 175 | ], 176 | "slots": [] 177 | }, 178 | { 179 | "name": "ListFindings", 180 | "samples": [ 181 | "get {SevName} severity findings for {selectedRegion}", 182 | "get {SevName} severity findings in {selectedRegion}", 183 | "list {SevName} severity findings in {selectedRegion}", 184 | "list {SevName} severity findings for {selectedRegion}", 185 | "get {SevName} severity findings from {selectedRegion}" 186 | ], 187 | "slots": [ 188 | { 189 | "name": "selectedRegion", 190 | "type": "REGION" 191 | }, 192 | { 193 | "name": "SevName", 194 | "type": "SEVNAME" 195 | } 196 | ] 197 | }, 198 | { 199 | "name": "ListStats", 200 | "samples": [ 201 | "ListStats get statistics for {selectedRegion}", 202 | "ListStats list statistics for {selectedRegion}", 203 | "ListStats get stats for {selectedRegion}", 204 | "ListStats list stats for {selectedRegion}", 205 | "ListStats list stats from {selectedRegion}", 206 | "ListStats get statistics from {selectedRegion}" 207 | ], 208 | "slots": [ 209 | { 210 | "name": "selectedRegion", 211 | "type": "REGION" 212 | } 213 | ] 214 | } 215 | ], 216 | "invocationName": "guard duty" 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /lambda/lambda_function.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"). You 5 | # may not use this file except in compliance with the License. A copy of 6 | # the License is located at 7 | # 8 | # http://aws.amazon.com/apache2.0/ 9 | # 10 | # or in the "license" file accompanying this file. This file is 11 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 12 | # ANY KIND, either express or implied. See the License for the specific 13 | # language governing permissions and limitations under the License. 14 | 15 | import boto3 16 | import os 17 | import re 18 | from collections import Counter 19 | 20 | # Variables 21 | 22 | # Max number of findings to return. Although 50 can be returned without paginating, 23 | # keeping this below 15 is a good idea to avoid Alexa size limit. 24 | MAXRESP = os.environ['MAXRESP'] 25 | 26 | # Comma separated list of region codes with NO spaces to include in flash briefing stats. 27 | # GuardDuty must be enabled in declared regions. 28 | FLASHREGIONS = os.environ['FLASHREGIONS'] 29 | 30 | 31 | def lambda_handler(event, context): 32 | """ Route the incoming request based on type (LaunchRequest, IntentRequest, 33 | etc.) The JSON body of the request is provided in the event parameter. 34 | """ 35 | print("event.session.application.applicationId=" + 36 | event['session']['application']['applicationId']) 37 | 38 | """ 39 | Uncomment this if statement and populate with your skill's application ID to 40 | prevent someone else from configuring a skill that sends requests to this 41 | function. 42 | """ 43 | # if (event['session']['application']['applicationId'] != 44 | # "amzn1.echo-sdk-ams.app.[unique-value-here]"): 45 | # raise ValueError("Invalid Application ID") 46 | 47 | if event['session']['new']: 48 | on_session_started({'requestId': event['request']['requestId']}, 49 | event['session']) 50 | 51 | if event['request']['type'] == "LaunchRequest": 52 | return on_launch(event['request'], event['session']) 53 | elif event['request']['type'] == "IntentRequest": 54 | return on_intent(event['request'], event['session']) 55 | elif event['request']['type'] == "SessionEndedRequest": 56 | return on_session_ended(event['request'], event['session']) 57 | 58 | def on_session_started(session_started_request, session): 59 | """ Called when the session starts """ 60 | 61 | print("on_session_started requestId=" + session_started_request['requestId'] 62 | + ", sessionId=" + session['sessionId']) 63 | 64 | def on_launch(launch_request, session): 65 | """ Called when the user launches the skill without specifying what they 66 | want 67 | """ 68 | 69 | print("on_launch requestId=" + launch_request['requestId'] + 70 | ", sessionId=" + session['sessionId']) 71 | # Dispatch to skill's launch 72 | return get_welcome_response() 73 | 74 | def on_intent(intent_request, session): 75 | """ Called when the user specifies an intent for this skill """ 76 | 77 | print("on_intent requestId=" + intent_request['requestId'] + 78 | ", sessionId=" + session['sessionId']) 79 | 80 | intent = intent_request['intent'] 81 | intent_name = intent_request['intent']['name'] 82 | 83 | # Dispatch intent handlers 84 | if intent_name == "FlashBriefing": 85 | return get_flash_briefing(intent, session) 86 | elif intent_name == "SetRegion": 87 | return set_region_in_session(intent, session) 88 | elif intent_name == "ListFindings": 89 | return list_findings(intent, session) 90 | elif intent_name == "ListStats": 91 | return list_stats(intent, session) 92 | elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent": 93 | return handle_session_end_request() 94 | elif intent_name == "AMAZON.HelpIntent": 95 | return get_help() 96 | else: 97 | raise ValueError("Invalid intent") 98 | 99 | def on_session_ended(session_ended_request, session): 100 | """ Called when the user ends the session. 101 | 102 | Is not called when the skill returns should_end_session=true 103 | """ 104 | print("on_session_ended requestId=" + session_ended_request['requestId'] + 105 | ", sessionId=" + session['sessionId']) 106 | 107 | # --------------- Functions that control the skill's behavior ------------------ 108 | 109 | # Initial welcome 110 | def get_welcome_response(): 111 | session_attributes = {} 112 | card_title = "Ask GuardDuty Welcome" 113 | should_end_session = False 114 | 115 | speech_output = "Welcome to Ask GuardDuty. To get started, you can get" \ 116 | " global GuardDuty finding statistics by saying, get flash briefing. For additional information, you can say, Help." 117 | 118 | reprompt_text = "Are you still there? For regional statistics, you can say for example, get statistics for Virginia." \ 119 | " Or, get high severity findings for Oregon. You can also get" \ 120 | " global statistics by saying, Get flash briefing. For additional information, you can say, Help." 121 | 122 | return build_response(session_attributes, build_speechlet_response( 123 | card_title, speech_output, reprompt_text, should_end_session)) 124 | 125 | def create_selected_region(selected_region): 126 | return {"selectedRegion": selected_region} 127 | 128 | # Return region ID 129 | def get_region_id(selectedRegion): 130 | if selectedRegion in {"Virginia", "virginia", "Northern Virginia", "northern virginia", "northern Virginia"}: 131 | return {"regionId": "us-east-1"} 132 | elif selectedRegion in {"Ohio", "ohio"}: 133 | return {"regionId": "us-east-2"} 134 | elif selectedRegion in {"Frankfurt", "frankfurt"}: 135 | return {"regionId": "eu-central-1"} 136 | elif selectedRegion in {"California", "california", "Northern California", "northern california", "northern California"}: 137 | return {"regionId": "us-west-1"} 138 | elif selectedRegion in {"Oregon", "oregon"}: 139 | return {"regionId": "us-west-2"} 140 | elif selectedRegion in {"London", "london"}: 141 | return {"regionId": "eu-west-2"} 142 | elif selectedRegion in {"Ireland", "ireland"}: 143 | return {"regionId": "eu-west-1"} 144 | elif selectedRegion in {"Singapore", "singapore"}: 145 | return {"regionId": "ap-southeast-1"} 146 | elif selectedRegion in {"Sydney", "sydney"}: 147 | return {"regionId": "ap-southeast-2"} 148 | elif selectedRegion in {"Canada", "canada", "Central", "central"}: 149 | return {"regionId": "ca-central-1"} 150 | elif selectedRegion in {"Sao Paulo", "sao paulo", "sao Paulo"}: 151 | return {"regionId": "sa-east-1"} 152 | elif selectedRegion in {"Seoul", "seoul"}: 153 | return {"regionId": "ap-northeast-2"} 154 | elif selectedRegion in {"Mumbai", "mumbai"}: 155 | return {"regionId": "ap-south-1"} 156 | elif selectedRegion in {"Tokyo", "tokyo"}: 157 | return {"regionId": "ap-northeast-1"} 158 | else: 159 | return {"regionId": "Unknown"} 160 | 161 | # Return region friendly name 162 | def get_region_name(region_id): 163 | if region_id == "us-east-1": 164 | return {"regionName": "Virginia"} 165 | elif region_id == "us-east-2": 166 | return {"regionName": "Ohio"} 167 | elif region_id == "us-west-1": 168 | return {"regionName": "California"} 169 | elif region_id == "eu-central-1": 170 | return {"regionName": "Frankfurt"} 171 | elif region_id == "us-west-2": 172 | return {"regionName": "Oregon"} 173 | elif region_id == "eu-west-2": 174 | return {"regionName": "London"} 175 | elif region_id == "ap-southeast-1": 176 | return {"regionName": "Singapore"} 177 | elif region_id == "ap-southeast-2": 178 | return {"regionName": "Sydney"} 179 | elif region_id == "eu-west-1": 180 | return {"regionName": "Ireland"} 181 | elif region_id == "ca-central-1": 182 | return {"regionName": "Canada"} 183 | elif region_id == "sa-east-1": 184 | return {"regionName": "Sao Paulo"} 185 | elif region_id == "ap-northeast-2": 186 | return {"regionName": "Seoul"} 187 | elif region_id == "ap-south-1": 188 | return {"regionName": "Mumbai"} 189 | elif region_id == "ap-northeast-1": 190 | return {"regionName": "Tokyo"} 191 | else: 192 | return {"regionName": ""} 193 | 194 | # Get GuardDuty Flash Briefing 195 | def get_flash_briefing(intent, session): 196 | session_attributes = {} 197 | card_title = "Ask GuardDuty Flash Briefing" 198 | should_end_session = False 199 | flashglobal = getflashbrief()[0] 200 | flashregion = getflashbrief()[1] 201 | 202 | if flashglobal: 203 | speech_output = " Here is your GuardDuty flash briefing." \ 204 | " Globally, there are, " + str(flashglobal) + " findings." \ 205 | " Here are the regional finding statistics: " + str(flashregion) + "." 206 | else: 207 | speech_output = "There are no current GuardDuty findings for the selected AWS regions." \ 208 | " You can generate samples in the console and GuardDuty will" \ 209 | " populate your current list with one sample finding for each supported type. " 210 | 211 | reprompt_text = "Are you still there? For regional statistics, you can say for example, get statistics for Virginia." \ 212 | " Or, get high severity findings for Oregon." \ 213 | " For additional information, you can say, Help." 214 | 215 | return build_response(session_attributes, build_speechlet_response( 216 | card_title, speech_output, reprompt_text, should_end_session)) 217 | 218 | # Get finding details for region X and severity Y 219 | def list_findings(intent, session): 220 | session_attributes = {} 221 | card_title = "Ask GardDuty Finding Details" 222 | should_end_session = False 223 | selected_region = intent['slots']['selectedRegion']['value'] 224 | session_attributes = create_selected_region(selected_region) 225 | region_name = get_region_id(selected_region)['regionId'] 226 | 227 | # Try to catch unknown or unsupported region 228 | if region_name == 'Unknown': 229 | speech_output = "I'm not sure which AWS region you would like me to access." \ 230 | " Please confirm the selected region is valid and GuardDuty is enabled." 231 | 232 | reprompt_text = "Please confirm the selected region is valid and GuardDuty is enabled." 233 | 234 | return build_response(session_attributes, build_speechlet_response( 235 | card_title, speech_output, reprompt_text, should_end_session)) 236 | 237 | if region_name: 238 | try: 239 | sevname = intent['slots']['SevName']['value'] 240 | min_sev = getsevvalue(sevname)['MinSev'] 241 | except KeyError: 242 | min_sev = '0' 243 | 244 | # In case GD is not enabled for selected region. 245 | try: 246 | gdfindings = getfindings(minsev=min_sev, region_name=region_name)['Findings'] 247 | except TypeError: 248 | gdfindings = [0] 249 | 250 | sgdfindings = [] 251 | 252 | if 'selectedRegion' in intent['slots'] and gdfindings != [0]: 253 | selected_region = intent['slots']['selectedRegion']['value'] 254 | for f in gdfindings: 255 | sevname = getsevname(str(f['Severity']))['SeverityName'] 256 | description = str(f['Title']) 257 | sgdfindings.append("Severity, " + sevname + ", " + "Count, " + str(f['Service']['Count']) + ", " + description) 258 | # Clean up output 259 | findings = scruboutput(inputtxt = str(sgdfindings)) 260 | 261 | if gdfindings: 262 | speech_output = "Here are up to " + MAXRESP + " GuardDuty findings for, " + selected_region + ", with minimum severity " + str(min_sev) + ". " + str(findings) + "" 263 | else: 264 | speech_output = "There are no current GuardDuty findings for, " + selected_region + ", with minimum severity " + str(min_sev) + "." 265 | 266 | else: 267 | speech_output = "The was a problem retrieving the information. Please confirm GuardDuty" \ 268 | " is enabled in the " + selected_region + " region." 269 | 270 | reprompt_text = "Are you still there? You can get GuardDuty" \ 271 | " finding details by saying for example, get high severity findings for Oregon. You can also get " \ 272 | " global statistics by saying, Get flash briefing. For additional information, you can say, Help." 273 | 274 | return build_response(session_attributes, build_speechlet_response( 275 | card_title, speech_output, reprompt_text, should_end_session)) 276 | 277 | # Get statistics by region. 278 | def list_stats(intent, session): 279 | session_attributes = {} 280 | card_title = "Ask GuardDuty Finding Statistics" 281 | should_end_session = False 282 | selected_region = intent['slots']['selectedRegion']['value'] 283 | session_attributes = create_selected_region(selected_region) 284 | region_name = get_region_id(selected_region)['regionId'] 285 | 286 | if region_name == 'Unknown': 287 | speech_output = "I'm not sure which AWS region you would like me to access." \ 288 | " Please confirm the selected region is valid and GuardDuty is enabled." 289 | 290 | reprompt_text = "Are you still there? You can get GuardDuty" \ 291 | " finding details by saying, get high severity findings for Virginia. Or you can get global statistics by saying," \ 292 | " Get flash briefing. For additional information, you can say, Help." 293 | 294 | return build_response(session_attributes, build_speechlet_response( 295 | card_title, speech_output, reprompt_text, should_end_session)) 296 | 297 | try: 298 | gdstats = getstats(region_name=region_name)['FindingStatistics']['CountBySeverity'] 299 | # In case GD is not enabled for selected region. 300 | except TypeError or KeyError: 301 | gdstats = [0] 302 | 303 | sgdstats = [] 304 | if 'selectedRegion' in intent['slots'] and gdstats != [0]: 305 | selected_region = intent['slots']['selectedRegion']['value'] 306 | for key, value in gdstats.items(): 307 | sevname = getsevname(key)['SeverityName'] 308 | sgdstats.append(" " + str(value) + " " + sevname + " severity") 309 | # Clean up output 310 | stats = scruboutput(inputtxt = str(sgdstats)) 311 | if sgdstats: 312 | speech_output = " In " + selected_region + ", there are currently, " + str(stats) + " findings. " 313 | else: 314 | speech_output = "There are no current findings in " + selected_region + "." \ 315 | " You can generate samples in the console and GuardDuty will" \ 316 | " populate your current list with one sample finding for each supported type. " 317 | 318 | else: 319 | speech_output = "The was a problem retrieving the information. Please confirm GuardDuty" \ 320 | " is enabled in the " + selected_region + " region." 321 | 322 | reprompt_text = "Are you still there? You can get GuardDuty" \ 323 | " finding details by saying, get high severity findings for Virginia. Or you can get global statistics by saying," \ 324 | " Get flash briefing. For additional information, you can say, Help." 325 | 326 | 327 | return build_response(session_attributes, build_speechlet_response( 328 | card_title, speech_output, reprompt_text, should_end_session)) 329 | 330 | # Get Help 331 | def get_help(): 332 | session_attributes = {} 333 | card_title = "Ask GuardDuty Help" 334 | should_end_session = False 335 | 336 | speech_output = "Welcome to Ask GardDuty. Amazon GuardDuty is a managed" \ 337 | " threat detection service that continuously monitors for" \ 338 | " malicious or unauthorized behavior to help you protect your AWS accounts and workloads." \ 339 | " GuardDuty generates findings when it detects unexpected and potentially malicious activity" \ 340 | " in your AWS environment. To get started, you can get" \ 341 | " global GuardDuty finding statistics by saying, get flash briefing. I am currently configured" \ 342 | " to return flash briefing information for the following AWS regions: " + getflashregions() + "." \ 343 | " You can also get finding statistics for a region by saying for example, get statistics for Oregon." \ 344 | " I can retrieve information for other AWS regions where GuardDuty is enabled." \ 345 | " You can get GuardDuty finding details by saying for example," \ 346 | " get high severity findings for California." \ 347 | " I am currently configured to return up to " + MAXRESP + " findings in a response." \ 348 | " Each GuardDuty finding has an assigned severity level and value that can help you determine your " \ 349 | " response to a potential security issue that is highlighted by a finding. The value of the severity " \ 350 | " can fall within the 0.1 to 8.9 range. High severity findings fall within the 7.0 to 8.9 range," \ 351 | " medium severity falls within the 4.0 to 6.9 range and low severity falls within the 0.1 to 3.9 range." \ 352 | " You can generate samples in the console and GuardDuty will" \ 353 | " populate your current list with one sample finding for each supported type." \ 354 | " Finally, make sure GuardDuty is enabled in AWS regions you would like me to access." 355 | 356 | reprompt_text = "Are you still there? To get started, you can say, get statistics for Virginia. You can also get" \ 357 | " global statistics by saying, get flash briefing. For additional information, you can say, Help." 358 | 359 | return build_response(session_attributes, build_speechlet_response( 360 | card_title, speech_output, reprompt_text, should_end_session)) 361 | 362 | # Return GuardDuty detector Id for region 363 | def getdetectorid(region_name): 364 | gdclient = boto3.client('guardduty', region_name=region_name) 365 | try: 366 | response = gdclient.list_detectors()['DetectorIds'][0] 367 | except IndexError: 368 | response = [] 369 | return response 370 | 371 | # Return finding severity name based on value 372 | def getsevname(sevlevel): 373 | if float(sevlevel) < 4: 374 | return {"SeverityName": "Low"} 375 | elif 4 < float(sevlevel) < 7: 376 | return {"SeverityName": "Medium"} 377 | elif float(sevlevel) > 7: 378 | return {"SeverityName": "High"} 379 | else: 380 | return {"SeverityName": sevlevel} 381 | 382 | # Return finding value value based on severity 383 | def getsevvalue(sevname): 384 | if sevname == "low": 385 | return {"MinSev": "0", "MaxSev": "3.9"} 386 | if sevname == "medium": 387 | return {"MinSev": "4", "MaxSev": "6.9"} 388 | if sevname == "high": 389 | return {"MinSev": "7", "MaxSev": "10"} 390 | else: 391 | return {"MinSev": "0", "MaxSev": "10"} 392 | 393 | # List regions declared in FLASHREGIONS by name 394 | def getflashregions(): 395 | flashregions = [] 396 | try: 397 | regionids = FLASHREGIONS.split(",") 398 | for r in regionids: 399 | flashregions.append(get_region_name(r)['regionName']) 400 | # Clean up output 401 | response = scruboutput(inputtxt = str(flashregions)) 402 | except IndexError or NameError: 403 | response = [] 404 | return response 405 | 406 | # Redact stuff from findings and clean up output for card display 407 | def scruboutput(inputtxt): 408 | response = re.sub('&', 'and', inputtxt) 409 | response = re.sub(r'[\[\]\"]', '', response) 410 | response = re.sub(r'instance i-(\w+)', 'instance', response) 411 | response = re.sub(r'i-(\w{1,17}\b)', 'EC2 instance', response) 412 | response = re.sub(r'against i-(\w+)', 'against an EC2 instance', response) 413 | response = re.sub(r'([0-9]+)(?:\.[0-9]+){3}', 'IP host', response) 414 | return response 415 | 416 | # ReturnGuardDuty Flash Briefing 417 | def getflashbrief(): 418 | # set the target regions to aggregate findng stats 419 | targ_regions = FLASHREGIONS.split(",") 420 | flashglobal = [] 421 | flashregion = [] 422 | c = Counter() 423 | for r in targ_regions: 424 | region_name = r 425 | rn = get_region_name(r)['regionName'] 426 | response = getstats(region_name=region_name)['FindingStatistics']['CountBySeverity'] 427 | if response: 428 | flashregion.append("Findings for " + str(rn) + " region") 429 | for key, value in response.items(): 430 | sevname = getsevname(key)['SeverityName'] 431 | #Sum total findings across regions declared in FLASHREGIONS 432 | c[key] += value 433 | flashregion.append("" + str(value) + " " + sevname + " severity") 434 | else: 435 | flashregion.append(" There are no current findings in the " + str(rn) + " region.") 436 | 437 | t = dict(c) 438 | totals = t.items() 439 | for key, value in totals: 440 | sevname = getsevname(key)['SeverityName'] 441 | flashglobal.append("" + str(value) + " " + sevname + " severity") 442 | 443 | # Clean up output 444 | fglobal = scruboutput(inputtxt = str(flashglobal)) 445 | fregion = scruboutput(inputtxt = str(flashregion)) 446 | return fglobal, fregion 447 | 448 | # Return statistics for region 449 | def getstats(region_name): 450 | gdclient = boto3.client('guardduty', region_name=region_name) 451 | detector_id = getdetectorid(region_name) 452 | if detector_id: 453 | response = gdclient.get_findings_statistics( 454 | DetectorId=detector_id, 455 | FindingCriteria={ 456 | 'Criterion': { 457 | 'service.archived': { 458 | 'Eq': 459 | ['false'], 460 | }, 461 | 'severity': { 462 | 'Gte': 463 | 0, 464 | } 465 | } 466 | }, 467 | FindingStatisticTypes=[ 468 | 'COUNT_BY_SEVERITY', 469 | ] 470 | ) 471 | else: 472 | response = [] 473 | return response 474 | 475 | # Return findings with minimum severity 476 | def listfindings(minsev, region_name): 477 | gdclient = boto3.client('guardduty', region_name=region_name) 478 | detector_id = getdetectorid(region_name) 479 | if detector_id: 480 | response = gdclient.list_findings( 481 | DetectorId=detector_id, 482 | FindingCriteria={ 483 | 'Criterion': { 484 | 'service.archived': { 485 | 'Eq': 486 | ['false'], 487 | }, 488 | 'severity': { 489 | 'Gte': 490 | int(minsev), 491 | } 492 | } 493 | }, 494 | MaxResults=int(MAXRESP), 495 | SortCriteria={ 496 | 'AttributeName': 'severity', 497 | 'OrderBy': 'ASC' 498 | } 499 | ) 500 | else: 501 | response = [] 502 | return response 503 | 504 | # Return finding details 505 | def getfindings(minsev, region_name): 506 | gdclient = boto3.client('guardduty', region_name=region_name) 507 | detector_id = getdetectorid(region_name) 508 | if detector_id: 509 | gresponse = listfindings(minsev, region_name) 510 | response = gdclient.get_findings( 511 | DetectorId=detector_id, 512 | FindingIds=gresponse['FindingIds'], 513 | SortCriteria={ 514 | 'AttributeName': 'severity', 515 | 'OrderBy': 'ASC' 516 | } 517 | ) 518 | else: 519 | response = [] 520 | return response 521 | 522 | def handle_session_end_request(): 523 | card_title = "Session Ended" 524 | speech_output = "" 525 | # Setting this to true ends the session and exits the skill. 526 | should_end_session = True 527 | return build_response({}, build_speechlet_response( 528 | card_title, speech_output, None, should_end_session)) 529 | 530 | # Setting reprompt_text to None signifies that we do not want to reprompt 531 | # the user. If the user does not respond or says something that is not 532 | # understood, the session will end. 533 | return build_response(session_attributes, build_speechlet_response( 534 | intent['name'], speech_output, reprompt_text, should_end_session)) 535 | 536 | # --------------- Helpers that build all of the responses ---------------------- 537 | 538 | def build_speechlet_response(title, output, reprompt_text, should_end_session): 539 | cleanout = re.sub(r'(<([^>]+)>)', '', output) 540 | return { 541 | 'outputSpeech': { 542 | 'type': 'SSML', 543 | 'ssml': output 544 | }, 545 | 'card': { 546 | 'type': 'Standard', 547 | 'title': title, 548 | 'text': cleanout, 549 | 'image': { 550 | 'smallImageUrl': 'https://s3.amazonaws.com/awsiammedia/public/sample/GuardDutyStatisticsFindings/guarddutysmall.png', 551 | 'largeImageUrl': 'https://s3.amazonaws.com/awsiammedia/public/sample/GuardDutyStatisticsFindings/guarddutylarge.png' 552 | } 553 | }, 554 | 'reprompt': { 555 | 'outputSpeech': { 556 | 'type': 'SSML', 557 | 'ssml': reprompt_text 558 | } 559 | }, 560 | 'shouldEndSession': should_end_session 561 | } 562 | 563 | def build_response(session_attributes, speechlet_response): 564 | return { 565 | 'version': '1.0', 566 | 'sessionAttributes': session_attributes, 567 | 'response': speechlet_response 568 | } 569 | --------------------------------------------------------------------------------