├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── aws-auditmanager-conformancepack ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── cft │ ├── aws-auditmanager-confpack.yml │ └── aws-auditmanager-customassessment.yml ├── images │ └── arch-diagram.png ├── lambda │ ├── CustomAuditManagerFramework_Lambda.py │ ├── CustomAuditManagerFramework_Lambda.zip │ └── auditmanagerlayer.zip ├── layer │ └── auditmanagerlayer.zip └── mappingfile │ ├── nerc-cipmappingfile.csv │ └── nistmappingcsv1.csv ├── aws-auditmanager-securityhub ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── cft │ ├── aws-auditmanager-customassessment.yml │ └── aws-auditmanager-securityhub.yml ├── images │ └── arch-diagram.png └── lambda │ └── CustomAuditManagerFramework_Lambda.py ├── aws-cloudfoundations-baseline-demo ├── README.md └── cft │ ├── aws-pci-conformancepack-remediations-v1.yml │ ├── aws-pci-conformancepack-v1.yml │ ├── aws-pci-confpack-ssmautomation-v1.yml │ └── aws-pci-custom-confpack-org.yml ├── aws-config-aggregator ├── README.md ├── cft │ ├── AccountEnableRecorderAndAggregator.yaml │ └── OrganizationEnableRecorderAndAggregator.yaml └── images │ └── aggregator.png ├── aws-config-visualization ├── README.md └── cft │ └── Config-QuickSight-Visualization-SSM-Automation.yaml ├── aws-configremediations-fsbp ├── LICENSE ├── README.md ├── cft │ ├── aws-fsbp-configremediations.yml │ ├── aws-fsbp-systemsmanagerautomations.yml │ └── aws-vpcsetup-v1.yml ├── coverage │ └── AWS SecurityHub Benchmarks-Coverage-v1.xlsx └── images │ └── arch-diagramfsbp.png ├── aws-configremediations-pci ├── LICENSE ├── README.md ├── cft │ ├── aws-pci-configremediations.yml │ ├── aws-pci-systemsmanagerautomations.yml │ └── aws-securevpcsetup.json ├── coverage │ └── AWS SecurityHub Benchmarks-Coverage-v1.xlsx └── images │ └── arch-diagrampci.png ├── aws-devsecops-conformancepack-pci ├── LICENSE ├── README.md ├── cft │ ├── aws-pci-conformancepack-update-v1.yml │ ├── aws-pci-conformancepack-v1-1.yml │ ├── aws-pci-conformancepack-v1-2.yml │ ├── aws-pci-conformancepack-v1-3.yml │ ├── aws-pci-conformancepack-v1.yml │ ├── aws-pci-confpack-codepipeline.yml │ ├── aws-pci-confpack-ssmautomation-reinvent.yml │ ├── aws-pci-confpack-ssmautomation-v1.yml │ ├── buildspec-reinvent.yml │ ├── buildspec-update-reinvent.yml │ └── buildspec.yml ├── coverage │ └── AWS PCI Conformance Packs Auto Healing Coverage.xlsx └── images │ ├── arch-diagram.png │ └── ccoe-devsecopscompliance.png ├── aws-enable-config ├── README.md ├── cft │ ├── AWSCloudFormationStackSetAdministrationRole.yml │ ├── AWSCloudFormationStackSetExecutionRole.yml │ ├── EnableAWSConfig.yml │ └── OrgEnableAWSConfigRule.yml └── images │ └── config.png ├── aws-org-conformancepack ├── README.md └── cft │ ├── AccountEnableConformancePack.yml │ ├── OrgEnableConformancePack.yml │ └── org-confpack-pci.yml ├── aws-org-custom-conformancepacks ├── README.md └── cft │ ├── aws-pci-conformancepack-remediations-v1.yml │ ├── aws-pci-conformancepack-v1.yml │ ├── aws-pci-confpack-ssmautomation-v1.yml │ ├── aws-pci-custom-confpack-org.yml │ └── s3bucketpolicy.json ├── aws-org-enable-cca └── README.md ├── aws-remediate-cis-securityhub ├── README.md ├── cft │ ├── aws-cis-cloudwatchlogmetricfilters-v2.yml │ ├── aws-cis-cloudwatchlogmetricfilters.yml │ ├── aws-cis-securityhubactions.yml │ └── aws-cis-systemsmanagerautomations.yml └── images │ └── arch-diagram.png ├── aws-servicecatalog-prescriptivecompliance ├── README-old.md ├── README.md ├── cft │ ├── aws-servicecatalog-codepipeline.yml │ ├── aws-servicecatalog-configremediations-v2.yml │ ├── aws-servicecatalog-configremediations.yml │ ├── aws-servicecatalog-prescriptivecompliance-v1.yml │ ├── aws-servicecatalog-prescriptivecompliance.yml │ ├── buildspec-update.yml │ └── buildspec.yml └── images │ └── ccoe-prescriptivecompliance.png ├── aws-systemsmanager-automations ├── migrations │ └── cft │ │ ├── AD-Immersionday_Template.yaml │ │ ├── MGN-sourceserver-replication.yml │ │ ├── domain-join-automation-role.yaml │ │ ├── domainJoin_RunDocument_yaml.yaml │ │ └── ssm-parameters.yaml └── patching │ └── aws-ssm-patchmanager-v1.yaml └── aws-systemsmanager-changemanager ├── README.md ├── cft ├── aws-changemanager-configremediation.yaml └── aws-changemanager-ssmautomation.yml └── images └── arch-changemanager.png /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, or recently closed, 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' 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](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/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 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/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, or recently closed, 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 *main* 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' 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](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Automate audit preparation in AWS and integrate across the Three Lines Model - Transform AWS Config Conformance Packs to AWS Audit Manager Assessments 5 | 6 | Converts an AWS Config Conformance Pack into an AWS Audit Manager Assessment 7 | 8 | The Audit Manager assessment is based on a custom AWS Audit Manager framework that is comprised of custom AWS Audit Manager control sets. The Audit Manager control set contains custom AWS Audit Manager controls related to AWS Config Conformance Pack based Config rules. 9 | 10 | Pre-req- Takes a csv as input that comprises of all the Config rules within the AWS Config Conformance Pack 11 | 12 | 13 | 14 | ## Solution Design 15 | 16 | ![](images/arch-diagram.png) 17 | 18 | 19 | ## How To Install 20 | 21 | **Prerequisites** 22 | 23 | 1. Ensure that AWS Config is enabled in your account. 24 | 25 | 2. Follow the steps to set up AWS Audit Manager. 26 | 27 | 3. Create an Amazon Simple Storage Service (Amazon S3) bucket with the following name: s3-customauditmanagerframework-AccountId-Region where AccountId is your AWS account ID and Region is the AWS Region where you plan to deploy the CloudFormation templates in the setup. In this bucket, create a folder named CustomAuditManagerFramework_Lambda. Upload the CustomAuditManagerFramework_Lambda.zip (in the lambda folder) file there. 28 | 29 | 4. Upload the mapping file to the top directory of the S3 bucket you created in Step 3. This mapping file is a csv that maps the control name of the compliance framework to the list of AWS Config Rules in the conformance pack. Sample mapping file for NIST-CSF is provided here--nistmappingcsv1.csv (in the mappingfile folder) 30 | 31 | 5. Create an IAM user with Audit owner permissions. https://docs.aws.amazon.com/audit-manager/latest/userguide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies. You can use the AWSAuditManagerAdministratorAccess policy as a starting point but please remember to scope down these permissions as needed to fit your requirements. 32 | 33 | 6. If you have already configured an assessment reports destination in your Audit Manager settings then you can skip this step. Otherwise for our solution you can simply reuse the S3 bucket from step 3 and create another folder for e.g. evidences. Your assessment reports destination will be the S3 URI for e.g. s3://s3-customauditmanagerframework-AccountId-Region/evidences/ in this case where AccountId is your AWS account ID and Region is the AWS Region where you plan to deploy the CloudFormation templates in the setup. 34 | 35 | 36 | 37 | **Setup** 38 | 39 | The solution automates the initial setup and deployment in two steps: 40 | 41 | 1. Launch the **aws-auditmanager-confpack.yml** template. For parameters - 1) Provide the name of the S3 bucket and folder (from step 3 in the prerequisites) that contains the source CustomAuditManagerFramework_Lambda.zip 2) Provide the name of the mapping file (from step 4) in the ConfPackControlsMappingFile parameter 42 | 43 | 2. Launch the **aws-auditmanager-customassessment.yml** template. Provide the s3 uri (from step 6 in the prerequisites) that is the assessment destination as a parameter and 2) Provide the ARN of the Audit owner IAM user from step 5 in the pre-requisites 44 | 45 | **Cleanup** 46 | 47 | 1. Delete the CloudFormation stacks in sequence- 1) aws-auditmanager-customassessment.yml and then 2) aws-auditmanager-confpack.yml 48 | 2. Delete the custom framework as well as the custom controls created in Audit Manager (you can do this from the console) 49 | 3. Delete the Audit Manager framework ID from the SSM parameter store 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/cft/aws-auditmanager-confpack.yml: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | # Provisions custom AWS Audit Manager assessment based on Config checks that create a conformance pack 5 | # Pre-req: AWS Lambda that creates a custom AWS Audit Manager control set and custom AWS Audit Manager 6 | # framework 7 | 8 | 9 | # kmmahaj 10 | 11 | AWSTemplateFormatVersion: 2010-09-09 12 | Description: >- 13 | AWS CloudFormation template to create custom Audit Manager assessments. You will be 14 | billed for the AWS resources used if you create a stack from this template. (qs-1t0eilb5g) 15 | Parameters: 16 | SourceBucket: 17 | Description: S3 Bucket that contains the Custom Audit Manager Framework Lambda 18 | Type: String 19 | Default: 's3-customauditmanagerframework--' 20 | MinLength: '1' 21 | MaxLength: '255' 22 | ConfPackControlsMappingFile: 23 | Description: CSV file that maps AWS Config rules to the Compliance controls from the Conformance Pack 24 | Type: String 25 | Default: 'nerc-cipmappingfile.csv' 26 | MinLength: '1' 27 | MaxLength: '255' 28 | 29 | Resources: 30 | 31 | #--------------------------------------------------------------------------------------------------- 32 | # 33 | # 1- Create Custom Audit Manager Control Sets based on AWS Config Conformance Pack checks 34 | # 2- Create Custom Audit Manager Framework based on custom Audit Manager control set 35 | # -------------------------------------------------------------------------------------------------- 36 | 37 | #Custom Lambda backed Resource for creating the Custom Audit Manager Framework 38 | CreateCustomAuditManagerFramework: 39 | Type: 'Custom::CreateCustomAuditManagerFramework' 40 | DependsOn: 41 | - CustomAuditManagerFrameworkExecutePermission 42 | Properties: 43 | ServiceToken: !GetAtt 'CustomAuditManagerFrameworkLambda.Arn' 44 | SourceAccountId: !Ref 'AWS::AccountId' 45 | 46 | #Permission for CFN to invoke custom lambda backed resource 47 | CustomAuditManagerFrameworkExecutePermission: 48 | Type: 'AWS::Lambda::Permission' 49 | Properties: 50 | Action: 'lambda:InvokeFunction' 51 | FunctionName: !GetAtt 'CustomAuditManagerFrameworkLambda.Arn' 52 | Principal: 'cloudformation.amazonaws.com' 53 | SourceAccount: !Ref 'AWS::AccountId' 54 | 55 | #Lambda Function that creates the custom Audit Manager framework 56 | CustomAuditManagerFrameworkLambda: 57 | Type: 'AWS::Lambda::Function' 58 | Properties: 59 | FunctionName: !Join 60 | - '' 61 | - - CustomAuditManagerFramework_ 62 | - Lambda 63 | Role: !GetAtt CustomAuditManagerFrameworkLambdaRole.Arn 64 | Code: 65 | S3Bucket: !Ref SourceBucket 66 | S3Key: !Join 67 | - '' 68 | - - CustomAuditManagerFramework_Lambda 69 | - / 70 | - CustomAuditManagerFramework_Lambda 71 | - .zip 72 | Description: CustomAuditManagerFrameworkLambda 73 | Handler: CustomAuditManagerFramework_Lambda.lambda_handler 74 | MemorySize: '256' 75 | Runtime: python3.7 76 | Environment: 77 | Variables: 78 | SourceAccountId : !Ref 'AWS::AccountId' 79 | MappingFile: !Ref ConfPackControlsMappingFile 80 | S3Bucket: !Ref SourceBucket 81 | 82 | Timeout: 300 83 | 84 | #IAM Role for the CustomAuditManagerFramework Lambda 85 | CustomAuditManagerFrameworkLambdaRole: 86 | Type: 'AWS::IAM::Role' 87 | Properties: 88 | RoleName: !Sub confpack-customauditmanagerframeworkrole-${AWS::Region} 89 | AssumeRolePolicyDocument: 90 | Version: 2012-10-17 91 | Statement: 92 | - Sid: AllowLambdaAssumeRole 93 | Effect: Allow 94 | Principal: 95 | Service: lambda.amazonaws.com 96 | Action: 'sts:AssumeRole' 97 | Policies: 98 | - PolicyName: CustomAuditManagerFrameworkLambdaPolicy 99 | PolicyDocument: 100 | Version: 2012-10-17 101 | Statement: 102 | - Effect: Allow 103 | Action: 104 | - s3:PutObject 105 | - s3:PutBucketLogging 106 | - s3:PutBucketVersioning 107 | - s3:GetObject 108 | - s3:GetBucketLocation 109 | - s3:ListBucket 110 | Resource: 111 | - !Sub arn:${AWS::Partition}:s3:::${SourceBucket} 112 | - !Sub arn:${AWS::Partition}:s3:::${SourceBucket}/* 113 | - Effect: Allow 114 | Action: 115 | - kms:Decrypt 116 | - ssm:PutParameter 117 | Resource: '*' 118 | ManagedPolicyArns: 119 | - !Sub 'arn:${AWS::Partition}:iam::aws:policy/AWSAuditManagerAdministratorAccess' 120 | - !Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole' 121 | 122 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/cft/aws-auditmanager-customassessment.yml: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | # Provisions custom AWS Audit Manager assessment based on an AWS Config Conformance Pack 5 | # Pre-req: AWS Lambda that creates a custom AWS Audit Manager control set and custom AWS Audit Manager 6 | # framework 7 | 8 | # kmmahaj 9 | 10 | AWSTemplateFormatVersion: 2010-09-09 11 | Description: >- 12 | AWS CloudFormation template to create custom Audit Manager assessments. You will be 13 | billed for the AWS resources used if you create a stack from this template.(qs-1t0eilb5g) 14 | Parameters: 15 | 16 | AssessmentDestination: 17 | Description: S3 Bucket and folder that stores the Custom Audit Manager Assessment Destination 18 | Type: String 19 | Default: 's3://s3-customauditmanagerframework--/evidences/' 20 | MinLength: '1' 21 | MaxLength: '255' 22 | 23 | AuditOwnerArn: 24 | Description: ARN for IAM Audit Owner in your account. 25 | Type: String 26 | Default: 'arn:aws:iam:::user/AuditManagerAdmin' 27 | MinLength: '1' 28 | MaxLength: '255' 29 | 30 | Resources: 31 | 32 | #--------------------------------------------------------------------------------------------------- 33 | # 1- Provision Custom Audit Manager Assessment 34 | # - Use SSM Parameter Store to retrieve the Framework ID created by the custom backed Lambda 35 | # -------------------------------------------------------------------------------------------------- 36 | 37 | CustomAuditManagerAssessment: 38 | Type: AWS::AuditManager::Assessment 39 | Properties: 40 | AssessmentReportsDestination: 41 | Destination: !Ref AssessmentDestination 42 | DestinationType: 'S3' 43 | Description: 'Custom Config Conformance Pack Assessment' 44 | FrameworkId: '{{resolve:ssm:CustomConfigConformancePackFrameworkID:1}}' 45 | Name: 'CustomConfigConfPackAssessment' 46 | Roles: 47 | - 'RoleArn': !Ref AuditOwnerArn 48 | 'RoleType': 'PROCESS_OWNER' 49 | Scope: 50 | AwsAccounts: 51 | - 'Id': !Ref 'AWS::AccountId' 52 | AwsServices: 53 | - 'ServiceName': 's3' 54 | - 'ServiceName': 'iam' 55 | - 'ServiceName': 'cloudtrail' 56 | - 'ServiceName': 'lambda' 57 | - 'ServiceName': 'ec2' 58 | - 'ServiceName': 'rds' 59 | 60 | 61 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/images/arch-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-auditmanager-conformancepack/images/arch-diagram.png -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/lambda/CustomAuditManagerFramework_Lambda.py: -------------------------------------------------------------------------------- 1 | # CustomAuditManagerFramework Lambda 2 | # - Creates Custom Audit Manager Control Sets and Custom Audit Manager Framework based on AWS Config Conformance Pack 3 | # ---Takes a csv input that lists all Config rules in a Conformance Pack. For e.g. NERC-CIP as an example input here 4 | # 5 | # 6 | # @kmmahaj 7 | # 8 | ## License: 9 | ## This code is made available under the MIT-0 license. See the LICENSE file. 10 | 11 | 12 | import json 13 | import codecs 14 | import copy 15 | import sys 16 | import datetime 17 | import boto3 18 | import botocore 19 | import time 20 | import logging 21 | import random 22 | import urllib3 23 | import csv 24 | import os 25 | from csv import reader 26 | from botocore.exceptions import ClientError 27 | 28 | 29 | logger = logging.getLogger() 30 | logger.setLevel(logging.INFO) 31 | http = urllib3.PoolManager() 32 | 33 | def cfnsend(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False, reason=None): 34 | 35 | responseUrl = '' 36 | StackId ='' 37 | RequestId ='' 38 | LogicalResourceId ='' 39 | 40 | if 'ResponseURL' in event: 41 | responseUrl = event['ResponseURL'] 42 | 43 | if 'StackId' in event: 44 | StackId = event['StackId'] 45 | 46 | if 'RequestId' in event: 47 | RequestId = event['RequestId'] 48 | 49 | if 'LogicalResourceId' in event: 50 | LogicalResourceId = event['LogicalResourceId'] 51 | 52 | responseBody = { 53 | 'Status' : responseStatus, 54 | 'Reason' : reason or "See the details in CloudWatch Log Stream: {}".format(context.log_stream_name), 55 | 'PhysicalResourceId' : physicalResourceId or context.log_stream_name, 56 | 'StackId' : StackId, 57 | 'RequestId' : RequestId, 58 | 'LogicalResourceId' : LogicalResourceId, 59 | 'NoEcho' : noEcho, 60 | 'Data' : responseData 61 | } 62 | 63 | json_responseBody = json.dumps(responseBody) 64 | 65 | print("Response body:") 66 | print(json_responseBody) 67 | 68 | headers = { 69 | 'content-type' : '', 70 | 'content-length' : str(len(json_responseBody)) 71 | } 72 | 73 | try: 74 | response = http.request('PUT', responseUrl, headers=headers, body=json_responseBody) 75 | print("Status code:", response.status) 76 | 77 | 78 | except Exception as e: 79 | 80 | print("send(..) failed executing http.request(..):", e) 81 | 82 | 83 | def create_custom_auditmanager_control(controls): 84 | 85 | auditmanager = boto3.client('auditmanager') 86 | configconfpackcontrol_List= [] 87 | control_id ="" 88 | controltype = controls[0] 89 | controllist = controls[1:] 90 | 91 | #Create a Custom Config Conformance Pack Control Source - Config Conf Pack Control Source 92 | configconfpack_controlmappingsource_template = {} 93 | configconfpack_controlmappingsource_template['sourceName'] = 'Custom Config Conformance Pack Control Source' 94 | configconfpack_controlmappingsource_template['sourceDescription'] = 'Conformance Pack checks' 95 | configconfpack_controlmappingsource_template['sourceSetUpOption'] = 'System_Controls_Mapping' 96 | configconfpack_controlmappingsource_template['sourceType'] = 'AWS_Config' 97 | sourceKeyword = { 98 | 'keywordInputType': 'SELECT_FROM_LIST', 99 | 'keywordValue': 'Conformance Pack checks' 100 | } 101 | configconfpack_controlmappingsource_template['sourceKeyword'] = sourceKeyword 102 | 103 | for controlname in controllist: 104 | configconfpack_controlmappingsource = copy.deepcopy(configconfpack_controlmappingsource_template) 105 | configconfpack_controlmappingsource['sourceKeyword']['keywordValue'] = controlname 106 | configconfpackcontrol_List.append(configconfpack_controlmappingsource) 107 | 108 | 109 | #Create a Custom Config Conformance Pack Control 110 | name = controltype + '-CustomConfigConfpackControl' 111 | response_control = auditmanager.create_control(name=name, controlMappingSources=configconfpackcontrol_List) 112 | control_id = response_control['control']['id'] 113 | 114 | return control_id 115 | 116 | def create_custom_auditmanager_controlset(controlslist): 117 | 118 | 119 | complianceframework_controls_controlid = create_custom_auditmanager_control(controlslist) 120 | 121 | #Add to a Custom NIST Config Conformance Pack Control Set 122 | configconfpack_complianceframework_controlset = {} 123 | configconfpack_complianceframework_controlset['name'] = 'ControlSet- ' + controlslist[0] 124 | configconfpack_complianceframework_controlset['controls'] = [] 125 | configconfpack_controldict ={} 126 | configconfpack_controldict['id'] = complianceframework_controls_controlid 127 | configconfpack_complianceframework_controlset['controls'].append(configconfpack_controldict) 128 | 129 | return configconfpack_complianceframework_controlset 130 | 131 | 132 | def lambda_handler(event, context): 133 | 134 | print ("boto3 version: " + boto3.__version__) 135 | auditmanager = boto3.client('auditmanager') 136 | ssm = boto3.client('ssm') 137 | s3 = boto3.client('s3') 138 | 139 | 140 | logger.info('EVENT Received: {}'.format(event)) 141 | responseData = {} 142 | controlSets_List =[] 143 | 144 | S3Bucket = os.environ['S3Bucket'] 145 | MappingFile = os.environ['MappingFile'] 146 | 147 | #Handle cfnsend delete event 148 | eventType = event['RequestType'] 149 | if eventType == 'Delete': 150 | logger.info(f'Request Type is Delete; unsupported') 151 | cfnsend(event, context, 'SUCCESS', responseData) 152 | return 'SUCCESS' 153 | 154 | 155 | #Create a NIST Control Set 156 | data = s3.get_object(Bucket=S3Bucket, Key=MappingFile) 157 | for row in csv.DictReader(codecs.getreader("utf-8")(data["Body"])): 158 | controlslist =[] 159 | for value in row.values(): 160 | if value != 'none': 161 | controlslist.append(value) 162 | controlSets_List.append(create_custom_auditmanager_controlset(controlslist)) 163 | 164 | 165 | #Create a NIST Control Set 166 | #with open('nistmapping.csv', 'r') as read_obj: 167 | # csv_reader = reader(read_obj) 168 | # for row in csv_reader: 169 | # controlSets_List.append(create_custom_auditmanager_controlset(row)) 170 | 171 | #Create a Custom Config Conformance Pack Framework for NIST controls 172 | 173 | response_framework = auditmanager.create_assessment_framework(name='Config Conformance Pack Custom Framework', 174 | controlSets=controlSets_List) 175 | 176 | #Write the framework id to the parameter 177 | frameworkid = response_framework['framework']['id'] 178 | # write to ssm parameter store 179 | ssm.put_parameter(Name='CustomConfigConformancePackFrameworkID', Type='String', Value=frameworkid, Overwrite=True) 180 | print('frameworkId is ' + frameworkid) 181 | 182 | cfnsend(event, context, 'SUCCESS', responseData) 183 | return 'SUCCESS' 184 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/lambda/CustomAuditManagerFramework_Lambda.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-auditmanager-conformancepack/lambda/CustomAuditManagerFramework_Lambda.zip -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/lambda/auditmanagerlayer.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-auditmanager-conformancepack/lambda/auditmanagerlayer.zip -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/layer/auditmanagerlayer.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-auditmanager-conformancepack/layer/auditmanagerlayer.zip -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/mappingfile/nerc-cipmappingfile.csv: -------------------------------------------------------------------------------- 1 | control-id,configrule1,configrule2,configrule3,configrule4,configrule5,configrule6,configrule7,configrule8,configrule9,configrule10 2 | CIP-003-7-R2-Part 4,securityhub-enabled,guardduty-enabled-centralized,none,none,none,none,none,none,none,none 3 | CIP-003-8-Attachment 1-Section 3.1,dms-replication-not-public,ebs-snapshot-public-restorable-check,ec2-instance-no-public-ip,elasticsearch-in-vpc-only,emr-master-no-public-ip,restricted-ssh,ec2-instances-in-vpc,internet-gateway-authorized-vpc-only,lambda-function-public-access-prohibited,lambda-inside-vpc 4 | CIP-003-8-Attachment 1-Section 3.1-2,rds-instance-public-access-check,rds-snapshots-public-prohibited,redshift-cluster-public-access-check,restricted-common-ports,s3-account-level-public-access-blocks,s3-bucket-public-read-prohibited,s3-bucket-public-write-prohibited,sagemaker-notebook-no-direct-internet-access,vpc-default-security-group-closed,vpc-sg-open-only-to-authorized-ports 5 | CIP-004-6-R4-Part 4.1.1,emr-kerberos-enabled,iam-group-has-users-check,iam-policy-no-statements-with-admin-access,iam-root-access-key-check,iam-user-group-membership-check,iam-user-no-policies-check,iam-user-unused-credentials-check,dms-replication-not-public,ebs-snapshot-public-restorable-check,lambda-function-public-access-prohibited 6 | CIP-004-6-R4-Part 4.1.1-2,rds-instance-public-access-check,rds-snapshots-public-prohibited,redshift-cluster-public-access-check,s3-account-level-public-access-blocks,s3-bucket-public-read-prohibited,s3-bucket-public-write-prohibited,sagemaker-notebook-no-direct-internet-access,none,none,none 7 | CIP-004-6-R4-Part 4.1.3,s3-bucket-policy-grantee-check,s3-bucket-public-read-prohibited,s3-bucket-public-write-prohibited,none,none,none,none,none,none,none 8 | CIP-005-5-R1-Part 1.1,dms-replication-not-public,ebs-snapshot-public-restorable-check,ec2-instance-no-public-ip,elasticsearch-in-vpc-only,emr-master-no-public-ip,ec2-instances-in-vpc,internet-gateway-authorized-vpc-only,lambda-function-public-access-prohibited,lambda-inside-vpc,rds-instance-public-access-check 9 | CIP-005-5-R1-Part 1.1-2,rds-snapshots-public-prohibited,redshift-cluster-public-access-check,s3-account-level-public-access-blocks,s3-bucket-public-read-prohibited,s3-bucket-public-write-prohibited,sagemaker-notebook-no-direct-internet-access,none,none,none,none 10 | CIP-005-5-R1-Part 1.2,alb-waf-enabled,internet-gateway-authorized-vpc-only,none,none,none,none,none,none,none,none 11 | CIP-005-5-R1-Part 1.3,lambda-function-public-access-prohibited,rds-instance-public-access-check,rds-snapshots-public-prohibited,redshift-cluster-public-access-check,restricted-common-ports,s3-account-level-public-access-blocks,s3-bucket-public-read-prohibited,s3-bucket-public-write-prohibited,sagemaker-notebook-no-direct-internet-access,vpc-default-security-group-closed 12 | CIP-005-5-R1-Part 1.3-2,vpc-sg-open-only-to-authorized-ports,emr-master-no-public-ip,restricted-ssh,none,none,none,none,none,none,none 13 | CIP-005-5-R1-Part 1.5,guardduty-enabled-centralized,alb-waf-enabled,none,none,none,none,none,none,none,none 14 | CIP-005-5-R2-Part 2.2,alb-http-drop-invalid-header-enabled,elb-tls-https-listeners-only,elasticsearch-node-to-node-encryption-check,none,none,none,none,none,none,none 15 | CIP-005-5-R2-Part 2.3,iam-user-mfa-enabled,mfa-enabled-for-iam-console-access,none,none,none,none,none,none,none,none 16 | CIP-007-6-R1-Part 1.1,ec2-instance-no-public-ip,emr-master-no-public-ip,restricted-ssh,restricted-common-ports,vpc-default-security-group-closed,vpc-sg-open-only-to-authorized-ports,none,none,none,none 17 | CIP-007-6-R2-Part 2.1,guardduty-non-archived-findings,ec2-managedinstance-patch-compliance-status-check,ec2-managedinstance-association-compliance-status-check,none,none,none,none,none,none,none 18 | CIP-007-6-R3-Part 3.1-2,guardduty-enabled-centralized,alb-waf-enabled,none,none,none,none,none,none,none,none 19 | CIP-007-6-R4-Part 4.1,cloudtrail-enabled,api-gw-execution-logging-enabled,cloud-trail-cloud-watch-logs-enabled,cloudtrail-s3-dataevents-enabled,elb-logging-enabled,multi-region-cloudtrail-enabled,redshift-cluster-configuration-check,s3-bucket-logging-enabled,vpc-flow-logs-enabled,rds-logging-enabled 20 | CIP-007-6-R4-Part 4.1-2,wafv2-logging-enabled,none,none,none,none,none,none,none,none,none 21 | CIP-007-6-R4-Part 4.3,cw-loggroup-retention-period-check,none,none,none,none,none,none,none,none,none 22 | CIP-007-6-R5-Part 5.1,iam-password-policy,none,none,none,none,none,none,none,none,none 23 | CIP-008-5-R1-Part 1.1,guardduty-non-archived-findings,guardduty-enabled-centralized,securityhub-enabled,none,none,none,none,none,none,none 24 | CIP-009-6-R1-Part 1.3,db-instance-backup-enabled,dynamodb-in-backup-plan,dynamodb-pitr-enabled,ebs-in-backup-plan,efs-in-backup-plan,elasticache-redis-cluster-automatic-backup-check,rds-in-backup-plan,s3-bucket-replication-enabled,s3-bucket-versioning-enabled,s3-bucket-default-lock-enabled 25 | CIP-010-2-R1-Part 1.1,ec2-instance-managed-by-systems-manager,ec2-managedinstance-association-compliance-status-check,securityhub-enabled,ec2-stopped-instance,ec2-volume-inuse-check,none,none,none,none,none 26 | CIP-011-2-R1-Part 1.2,acm-certificate-expiration-check,alb-http-drop-invalid-header-enabled,alb-http-to-https-redirection-check,api-gw-cache-enabled-and-encrypted,cloud-trail-encryption-enabled,cloudwatch-log-group-encrypted,cmk-backing-key-rotation-enabled,dynamodb-table-encrypted-kms,ec2-ebs-encryption-by-default,efs-encrypted-check 27 | CIP-011-2-R1-Part 1.2-2,elasticsearch-encrypted-at-rest,elasticsearch-node-to-node-encryption-check,elb-acm-certificate-required,elb-tls-https-listeners-only,encrypted-volumes,kms-cmk-not-scheduled-for-deletion,rds-snapshot-encrypted,rds-storage-encrypted,redshift-cluster-configuration-check,redshift-require-tls-ssl 28 | CIP-011-2-R1-Part 1.2-3,s3-bucket-server-side-encryption-enabled,s3-bucket-ssl-requests-only,s3-default-encryption-kms,sagemaker-endpoint-configuration-kms-key-configured,sagemaker-notebook-instance-kms-key-configured,sns-encrypted-kms,none,none,none,none 29 | 30 | -------------------------------------------------------------------------------- /aws-auditmanager-conformancepack/mappingfile/nistmappingcsv1.csv: -------------------------------------------------------------------------------- 1 | control-id,configrule1,configrule2,configrule3,configrule4,configrule5,configrule6,configrule7,configrule8,configrule9,configrule10 2 | ID.AM-2,ec2-instance-managed-by-systems-manager,ec2-managedinstance-association-compliance-status-check,none,none,none,none,none,none,none,none 3 | ID.AM-3,api-gw-execution-logging-enabled,cloudtrail-enabled,elb-logging-enabled,multi-region-cloudtrail-enabled,redshift-cluster-configuration-check,s3-bucket-logging-enabled,vpc-flow-logs-enabled,none,none,none 4 | ID.AM-6,iam-user-group-membership-check,none,none,none,none,none,none,none,none,none 5 | ID.BE-5,autoscaling-group-elb-healthcheck-required,db-instance-backup-enabled,dynamodb-autoscaling-enabled dynamodb-throughput-limit-check,elasticache-redis-cluster-automatic-backup-check,elb-deletion-protection-enabled,rds-multi-az-support,s3-bucket-replication-enabled,s3-bucket-versioning-enabled,vpc-vpn-2-tunnels-up,none 6 | ID.RA-1,ec2-managedinstance-patch-compliance-status-check,guardduty-enabled-centralized,securityhub-enabled,none,none,none,none,none,none,none 7 | ID.RA-2,guardduty-enabled-centralized,securityhub-enabled,none,none,none,none,none,none,none,none 8 | ID.RA-3,guardduty-enabled-centralized,securityhub-enabled,none,none,none,none,none,none,none,none 9 | PR.AC-1,access-keys-rotated,iam-group-has-users-check,iam-password-policy,iam-policy-no-statements-with-admin-access,iam-root-access-key-check,iam-user-group-membership-check,iam-user-no-policies-check,iam-user-unused-credentials-check,s3-bucket-policy-grantee-check,secretsmanager-rotation-enabled-check 10 | PR.AC-3,dms-replication-not-public,ebs-snapshot-public-restorable-check,ec2-instance-no-public-ip,elasticsearch-in-vpc-only,emr-master-no-public-ip,iam-user-mfa-enabled,restricted-ssh,ec2-instances-in-vpc,internet-gateway-authorized-vpc-only,lambda-function-public-access-prohibited 11 | PR.AC-3-Part2,s3-bucket-policy-grantee-check,s3-bucket-public-read-prohibited,s3-bucket-public-write-prohibited,sagemaker-notebook-no-direct-internet-access,vpc-default-security-group-closed,vpc-sg-open-only-to-authorized-ports,none,none,none,none 12 | PR.AC-4,emr-kerberos-enabled,iam-group-has-users-check,iam-policy-no-statements-with-admin-access,iam-root-access-key-check,iam-user-group-membership-check,iam-user-no-policies-check,iam-user-unused-credentials-check,s3-bucket-policy-grantee-check,none,none 13 | PR.AC-5,acm-certificate-expiration-check,dms-replication-not-public,ebs-snapshot-public-restorable-check,ec2-instance-no-public-ip,none,none,none,none,none,none 14 | -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/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 | -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/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, or recently closed, 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 *main* 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' 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](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Automate audit preparation in AWS and integrate across the Three Lines Model - Build a custom integration of AWS Audit Manager with AWS Security Hub 5 | 6 | Creates a custom AWS Audit Manager framework that is comprised of custom AWS Audit Manager control sets. The custom Audit Manager control set contains custom AWS Audit Manager controls related to AWS Security Hub findings that span across AWS Security Hub FSBP, CIS and PCI compliance checks. So, instead of the control set being specific to an individual AWS Security Hub compliance check (FSBP,CIS or PCI), the control set spans across Security Hub compliance checks and is specific to a security related domain – for e.g. Identity Management or Network Monitoring. 7 | 8 | 9 | ## Solution Design 10 | 11 | ![](images/arch-diagram.png) 12 | 13 | ## How To Install 14 | 15 | **Prerequisites** 16 | 17 | 1. Ensure that AWS Security Hub is enabled in your account. 18 | 19 | 2. Follow the steps to set up AWS Audit Manager. 20 | 21 | 3. Create an Amazon S3 bucket with the following name: s3-customauditmanagerframework-AccountId-Region where the AccountId is your AWS Account ID and Region is the AWS Region where you have deployed this template. In this bucket, create a folder named CustomAuditManagerFramework_Lambda and upload the CustomAuditManagerFramework_Lambda.zip (it's in the lambda folder) file there. 22 | 23 | 4. Audit Manager works with the Boto3 1.7 libraries. AWS Lambda doesn't ship with Boto3 1.7 by default. This implementation provides that version of Boto3 as a Lambda Layer. Upload the auditmanagerlayer.zip (it's in the layer folder) to the root folder of the S3 bucket created in step 2. 24 | 25 | 5. If you have already configured an assessment reports destination in your Audit Manager settings then you can skip this step. Otherwise, create a folder (for e.g. 'evidences) in the S3 bucket in step 2. Your assessment reports destination will be the S3 URI for e.g. s3://s3-customauditmanagerframework-AccountId-Region/evidences/. AWS Audit Manager will save your assessment reports to this bucket. 26 | 27 | 6. Create an IAM user with Audit owner permissions. https://docs.aws.amazon.com/audit-manager/latest/userguide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies 28 | 29 | 30 | **Setup** 31 | 32 | The solution automates the initial setup and deployment in two steps: 33 | 34 | 1. Launch the **aws-auditmanager-securityhub.yml** template. For parameters - 1) Provide the name of the S3 bucket and folder (from step 3 in the prerequisites) that contains the source CustomAuditManagerFramework_Lambda.zip 35 | 36 | 2. Launch the **aws-auditmanager-customassessment.yml** template. Provide the s3 uri (from step 5 in the prerequisites) that is the assessment destination as a parameter and 2) Provide the ARN of the Audit owner IAM user from step 6 in the pre-requisites 37 | 38 | **Cleanup** 39 | 40 | 1. Delete the CloudFormation stacks in sequence- 1) aws-auditmanager-customassessment.yml and then 2) aws-auditmanager-securityhub.yml 41 | 2. Delete the custom framework as well as the custom controls created in Audit Manager (you can do this from the console) 42 | 3. Delete the Audit Manager framework ID from the SSM parameter store 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/cft/aws-auditmanager-customassessment.yml: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | # Provisions custom AWS Audit Manager assessment based on Security Hub checks 5 | # Pre-req: AWS Lambda that creates a custom AWS Audit Manager control set and custom AWS Audit Manager 6 | # framework 7 | 8 | # kmmahaj 9 | 10 | AWSTemplateFormatVersion: 2010-09-09 11 | Description: >- 12 | AWS CloudFormation template to create custom Audit Manager assessments. You will be 13 | billed for the AWS resources used if you create a stack from this template.(qs-1t0eilb5g) 14 | Parameters: 15 | 16 | AssessmentDestination: 17 | Description: S3 Bucket and folder that stores the Custom Audit Manager Assessment Destination 18 | Type: String 19 | Default: 's3://s3-customauditmanagerframework--/evidences/' 20 | MinLength: '1' 21 | MaxLength: '255' 22 | 23 | AuditOwnerArn: 24 | Description: ARN for IAM Audit Owner in your account. 25 | Type: String 26 | Default: 'arn:aws:iam::341476298946:user/AuditManagerAdmin' 27 | MinLength: '1' 28 | MaxLength: '255' 29 | 30 | Resources: 31 | 32 | #--------------------------------------------------------------------------------------------------- 33 | # 1- Provision Custom Audit Manager Assessment 34 | # - Use SSM Parameter Store to retrieve the Framework ID created by the custom backed Lambda 35 | # -------------------------------------------------------------------------------------------------- 36 | 37 | CustomAuditManagerAssessment: 38 | Type: AWS::AuditManager::Assessment 39 | Properties: 40 | AssessmentReportsDestination: 41 | Destination: !Ref AssessmentDestination 42 | DestinationType: 'S3' 43 | Description: 'Custom Security Hub Assessment' 44 | FrameworkId: '{{resolve:ssm:CustomSecurityHubFrameworkID:1}}' 45 | Name: 'CustomSecurityHubAssessment' 46 | Roles: 47 | - 'RoleArn': !Ref AuditOwnerArn 48 | 'RoleType': 'PROCESS_OWNER' 49 | Scope: 50 | AwsAccounts: 51 | - 'Id': !Ref 'AWS::AccountId' 52 | AwsServices: 53 | - 'ServiceName': 's3' 54 | - 'ServiceName': 'iam' 55 | - 'ServiceName': 'cloudtrail' 56 | - 'ServiceName': 'lambda' 57 | - 'ServiceName': 'ec2' 58 | - 'ServiceName': 'rds' 59 | 60 | 61 | -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/cft/aws-auditmanager-securityhub.yml: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | # Provisions custom AWS Audit Manager assessment based on Security Hub checks 5 | # Pre-req: AWS Lambda that creates a custom AWS Audit Manager control set and custom AWS Audit Manager 6 | # framework 7 | 8 | # kmmahaj 9 | 10 | AWSTemplateFormatVersion: 2010-09-09 11 | Description: >- 12 | AWS CloudFormation template to create custom Audit Manager assessments. You will be 13 | billed for the AWS resources used if you create a stack from this template.(qs-1t0eilb5g) 14 | Parameters: 15 | SourceBucket: 16 | Description: S3 Bucket that contains the Custom Audit Manager Framework Lambda 17 | Type: String 18 | Default: 's3-customauditmanagerframework--' 19 | MinLength: '1' 20 | MaxLength: '255' 21 | 22 | Resources: 23 | 24 | #--------------------------------------------------------------------------------------------------- 25 | # 26 | # 1- Create Custom Audit Manager Control Sets for IAM, API and Network Monitoring 27 | # based on Security Hub checks across PCI,CIS and FSBP frameworks 28 | # 2- Create Custom Audit Manager Framework based on custom Audit Manager control set 29 | # -------------------------------------------------------------------------------------------------- 30 | 31 | #Custom Lambda backed Resource for creating the Custom Audit Manager Framework 32 | CreateCustomAuditManagerFramework: 33 | Type: 'Custom::CreateCustomAuditManagerFramework' 34 | DependsOn: 35 | - CustomAuditManagerFrameworkExecutePermission 36 | Properties: 37 | ServiceToken: !GetAtt 'CustomAuditManagerFrameworkLambda.Arn' 38 | SourceAccountId: !Ref 'AWS::AccountId' 39 | 40 | #Permission for CFN to invoke custom lambda backed resource 41 | CustomAuditManagerFrameworkExecutePermission: 42 | Type: 'AWS::Lambda::Permission' 43 | Properties: 44 | Action: 'lambda:InvokeFunction' 45 | FunctionName: !GetAtt 'CustomAuditManagerFrameworkLambda.Arn' 46 | Principal: 'cloudformation.amazonaws.com' 47 | SourceAccount: !Ref 'AWS::AccountId' 48 | 49 | #Lambda Function that creates the custom Audit Manager framework 50 | CustomAuditManagerFrameworkLambda: 51 | Type: 'AWS::Lambda::Function' 52 | Properties: 53 | FunctionName: !Join 54 | - '' 55 | - - CustomAuditManagerFramework_ 56 | - Lambda 57 | Role: !GetAtt CustomAuditManagerFrameworkLambdaRole.Arn 58 | Code: 59 | S3Bucket: !Ref SourceBucket 60 | S3Key: !Join 61 | - '' 62 | - - CustomAuditManagerFramework_Lambda 63 | - / 64 | - CustomAuditManagerFramework_Lambda 65 | - .zip 66 | Description: CustomAuditManagerFrameworkLambda 67 | Handler: CustomAuditManagerFramework_Lambda.lambda_handler 68 | MemorySize: '256' 69 | Runtime: python3.7 70 | Layers: 71 | - !Ref AuditManagerLayer 72 | Environment: 73 | Variables: 74 | SourceAccountId : !Ref 'AWS::AccountId' 75 | Timeout: 300 76 | 77 | #Lambda Layer for AWS Audit Manager 78 | AuditManagerLayer: 79 | Type: AWS::Lambda::LayerVersion 80 | Properties: 81 | CompatibleRuntimes: 82 | - python3.6 83 | - python3.7 84 | - python3.8 85 | Content: 86 | S3Bucket: !Ref SourceBucket 87 | S3Key: auditmanagerlayer.zip 88 | Description: Boto3 layer for audit manager 89 | LayerName: AuditManagerLayer 90 | LicenseInfo: MIT 91 | 92 | #IAM Role for the CustomAuditManagerFramework Lambda 93 | CustomAuditManagerFrameworkLambdaRole: 94 | Type: 'AWS::IAM::Role' 95 | Properties: 96 | RoleName: !Sub securityhub-customauditmanagerframeworkrole-${AWS::Region} 97 | AssumeRolePolicyDocument: 98 | Version: 2012-10-17 99 | Statement: 100 | - Sid: AllowLambdaAssumeRole 101 | Effect: Allow 102 | Principal: 103 | Service: lambda.amazonaws.com 104 | Action: 'sts:AssumeRole' 105 | Policies: 106 | - PolicyName: CustomAuditManagerFrameworkLambdaPolicy 107 | PolicyDocument: 108 | Version: 2012-10-17 109 | Statement: 110 | - Sid: '1' 111 | Action: 112 | - 's3:*' 113 | Effect: Allow 114 | Resource: 115 | - !Sub arn:${AWS::Partition}:s3:::${SourceBucket} 116 | - !Sub arn:${AWS::Partition}:s3:::${SourceBucket}/* 117 | - Sid: '2' 118 | Action: 119 | - 'logs:CreateLogGroup' 120 | - 'logs:CreateLogStream' 121 | - 'logs:PutLogEvents' 122 | - 'logs:DescribeLogStreams' 123 | Effect: Allow 124 | Resource: '*' 125 | - Sid: '3' 126 | Action: 127 | - 'ssm:*' 128 | Effect: Allow 129 | Resource: '*' 130 | ManagedPolicyArns: 131 | - !Sub 'arn:${AWS::Partition}:iam::aws:policy/AWSAuditManagerAdministratorAccess' 132 | - !Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole' 133 | 134 | -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/images/arch-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-auditmanager-securityhub/images/arch-diagram.png -------------------------------------------------------------------------------- /aws-auditmanager-securityhub/lambda/CustomAuditManagerFramework_Lambda.py: -------------------------------------------------------------------------------- 1 | 2 | # CreateAuditManagerAssessment-SecurityHub Lambda 3 | # - Selects several AWS Security Hub checks as a data source 4 | # - Creates Custom Audit Manager Control Sets for IAM, API and Network Monitoring based on 5 | # Security Hub checks across PCI,CIS and FSBP frameworks 6 | # - Creates an AWS Audit Manager custom framework with the control set above that uses Security Hub as a data source 7 | # - Creates an AWS Audit Manager assessment based on the custom framework above 8 | 9 | # @kmmahaj 10 | # 11 | ## License: 12 | ## This code is made available under the MIT-0 license. See the LICENSE file. 13 | 14 | 15 | import json 16 | import copy 17 | import sys 18 | import datetime 19 | import boto3 20 | import botocore 21 | import time 22 | import logging 23 | import random 24 | import urllib3 25 | from botocore.exceptions import ClientError 26 | 27 | 28 | logger = logging.getLogger() 29 | logger.setLevel(logging.INFO) 30 | http = urllib3.PoolManager() 31 | 32 | def cfnsend(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False, reason=None): 33 | 34 | responseUrl = '' 35 | StackId ='' 36 | RequestId ='' 37 | LogicalResourceId ='' 38 | 39 | if 'ResponseURL' in event: 40 | responseUrl = event['ResponseURL'] 41 | 42 | if 'StackId' in event: 43 | StackId = event['StackId'] 44 | 45 | if 'RequestId' in event: 46 | RequestId = event['RequestId'] 47 | 48 | if 'LogicalResourceId' in event: 49 | LogicalResourceId = event['LogicalResourceId'] 50 | 51 | responseBody = { 52 | 'Status' : responseStatus, 53 | 'Reason' : reason or "See the details in CloudWatch Log Stream: {}".format(context.log_stream_name), 54 | 'PhysicalResourceId' : physicalResourceId or context.log_stream_name, 55 | 'StackId' : StackId, 56 | 'RequestId' : RequestId, 57 | 'LogicalResourceId' : LogicalResourceId, 58 | 'NoEcho' : noEcho, 59 | 'Data' : responseData 60 | } 61 | 62 | json_responseBody = json.dumps(responseBody) 63 | 64 | print("Response body:") 65 | print(json_responseBody) 66 | 67 | headers = { 68 | 'content-type' : '', 69 | 'content-length' : str(len(json_responseBody)) 70 | } 71 | 72 | try: 73 | response = http.request('PUT', responseUrl, headers=headers, body=json_responseBody) 74 | print("Status code:", response.status) 75 | 76 | 77 | except Exception as e: 78 | 79 | print("send(..) failed executing http.request(..):", e) 80 | 81 | 82 | def create_custom_auditmanager_control(controls, controltype): 83 | 84 | auditmanager = boto3.client('auditmanager') 85 | securityhubcontrol_List= [] 86 | control_id ="" 87 | 88 | #Create a Custom Security Hub Control Source - Security Hub Control Source 89 | securityhub_controlmappingsource_template = {} 90 | securityhub_controlmappingsource_template['sourceName'] = 'Custom Security Hub Control Source' 91 | securityhub_controlmappingsource_template['sourceDescription'] = 'Security Hub checks' 92 | securityhub_controlmappingsource_template['sourceSetUpOption'] = 'System_Controls_Mapping' 93 | securityhub_controlmappingsource_template['sourceType'] = 'AWS_Security_Hub' 94 | sourceKeyword = { 95 | 'keywordInputType': 'SELECT_FROM_LIST', 96 | 'keywordValue': 'Security Hub checks' 97 | } 98 | securityhub_controlmappingsource_template['sourceKeyword'] = sourceKeyword 99 | 100 | for controlname in controls: 101 | securityhub_controlmappingsource = copy.deepcopy(securityhub_controlmappingsource_template) 102 | securityhub_controlmappingsource['sourceKeyword']['keywordValue'] = controlname 103 | securityhubcontrol_List.append(securityhub_controlmappingsource) 104 | 105 | 106 | #Create a Custom Security Hub Control 107 | name = 'Custom' + controltype + 'SecurityHubControl' 108 | response_control = auditmanager.create_control(name=name, controlMappingSources=securityhubcontrol_List) 109 | control_id = response_control['control']['id'] 110 | 111 | return control_id 112 | 113 | 114 | def lambda_handler(event, context): 115 | 116 | print ("boto3 version: " + boto3.__version__) 117 | auditmanager = boto3.client('auditmanager') 118 | ssm = boto3.client('ssm') 119 | 120 | logger.info('EVENT Received: {}'.format(event)) 121 | responseData = {} 122 | controlSets_List =[] 123 | 124 | #Handle cfnsend delete event 125 | eventType = event['RequestType'] 126 | if eventType == 'Delete': 127 | logger.info(f'Request Type is Delete; unsupported') 128 | cfnsend(event, context, 'SUCCESS', responseData) 129 | return 'SUCCESS' 130 | 131 | #Create a Custom Security Hub IAM Audit Manager Control 132 | iam_controls = ['IAM.1', 'IAM.2', 'IAM.3', 'IAM.4', 'IAM.5', 'IAM.6', 'PCI.IAM.7', '1.16', '1.20', 'PCI.IAM.8'] 133 | iam_controlid = create_custom_auditmanager_control(iam_controls,'IAM') 134 | 135 | #Create a Custom Security Hub IAM Control Set 136 | sh_iam_controlset = {} 137 | sh_iam_controlset['name'] = 'Custom Security Hub IAM Control Set' 138 | sh_iam_controlset['controls'] = [] 139 | iam_controldict ={} 140 | iam_controldict['id'] = iam_controlid 141 | sh_iam_controlset['controls'].append(iam_controldict) 142 | controlSets_List.append(sh_iam_controlset) 143 | 144 | #Create a Custom Security Hub Montoring Audit Manager Control 145 | monitoring_controls = ['APIGateway.1', '2.9', '3.10', '3.11', '3.12', '3.13', '3.14', 'PCI.EC2.6'] 146 | monitoring_controlid = create_custom_auditmanager_control(monitoring_controls, 'Monitoring') 147 | 148 | #Create a Custom Security Hub Monitoring Control Set 149 | sh_mon_controlset = {} 150 | sh_mon_controlset['name'] = 'Custom Security Hub Monitoring Control Set' 151 | sh_mon_controlset['controls'] = [] 152 | mon_controldict ={} 153 | mon_controldict['id'] = monitoring_controlid 154 | sh_mon_controlset['controls'].append(mon_controldict) 155 | controlSets_List.append(sh_mon_controlset) 156 | 157 | #Create a Custom Security Hub Framework that contains 1) IAM Control Set and 2) Network Monitoring Control Set 158 | 159 | response_framework = auditmanager.create_assessment_framework(name='Security Hub Custom Framework', 160 | controlSets=controlSets_List) 161 | 162 | #Write the framework id to the parameter 163 | frameworkid = response_framework['framework']['id'] 164 | # write to ssm parameter store 165 | ssm.put_parameter(Name='CustomSecurityHubFrameworkID', Type='String', Value=frameworkid, Overwrite=True) 166 | print('frameworkId is ' + frameworkid) 167 | 168 | cfnsend(event, context, 'SUCCESS', responseData) 169 | return 'SUCCESS' 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /aws-cloudfoundations-baseline-demo/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # DevSecOps for Auto Healing PCI Compliance using custom AWS Config Conformance Packs and AWS CodePipeline 5 | 6 | Augments the AWS Config Conformance Pack for Operational Best Practices for PCI DSS 3.2.1 with 2 features – 7 | 1. Auto healing for PCI related AWS Config Managed rules. Adds Remediation to the PCI Conformance Packs. Implemented using Custom AWS Config Conformance Packs that leverage custom AWS Systems Manager Automation Documents provided via AWS CloudFormation 8 | 2. DevSecOps CI/CD pipeline for PCI compliance that incorporates “PCI Compliance as code” in an existing DevOps workflows. Implemented via integrating AWS Custom Config Conformance Packs with AWS CodePipeline and provided via AWS CloudFormation. 9 | 10 | 11 | 12 | ## How it Works 13 | 14 | 1. aws-pci-confpack-codepipeline.yml 15 | - Triggers an AWS CodePipeline based CI/CD pipeline whenever there is an update to the source AWS CloudFormation templates in your local Git repository. These source AWS CloudFormation templates incorporate the code for the custom AWS Config Conformance Packs. 16 | - Provisions an AWS CodePipeline automation with AWS CodeCommit and AWS CodeBuild stages for the build and deployment of the AWS Config Conformance Packs 17 | 2. aws-pci-confpack-ssmautomation-v1.yml 18 | - Provisions custom AWS Systems Manager automation documents for PCI remediation. These documents are used to provide automated remediations within the provisioned AWS Config rule using the AWS:Config:RemediationConfiguration CloudFormation construct in the AWS Config Conformance Pack. 19 | - Provisions pre-requisites for the AWS Config Conformance Pack deployment such as the AWS Systems Manager automation role, S3 buckets for logging and replication for S3 related remediations and CloudWatch logs and CloudWatch role for AWS CloudTrail related remediations for PCI compliance 20 | 3. Custom AWS Config Conformance Packs 21 | - aws-pci-conformancepack-v1-1.yml – Provisions a custom AWS Config Conformance Pack for the detection and remediation for Amazon EC2, AWS Auto Scaling and AWS Lambda based PCI Compliance violations 22 | - aws-pci-conformancepack-v1-2.yml - Provisions a custom AWS Config Conformance Pack for the detection and remediation for AWS CloudTrail, AWS KMS and AWS CodeBuild based PCI Compliance violations 23 | - aws-pci-conformancepack-v1-3.yml - Provisions a custom AWS Config Conformance Pack for the detection and remediation for Amazon Redshift, AWS RDS and AWS IAM based PCI Compliance violations. 24 | 25 | 26 | ## Solution Design 27 | 28 | ![](images/arch-diagram.png) 29 | 30 | ## Prerequisites 31 | 1. Custom AWS Config Conformance Packs - Set up prerequisites for deploying and building with both AWS Config Conformance Packs as well as custom AWS Config Conformance Packs with remediations. Refer to AWS documentation 32 | 2. Local Git repository and AWS CodeCommit Git repository setup – Create an AWS CodeCommit Git Repository in your AWS account and integrate it with your local Git repository. Refer to AWS documentation. 33 | 3. Staging S3 bucket – The solution creates a staging S3 bucket with the following naming convention: **s3-pciautohealconfpack--accountid-region. Substitute the accountid and region parameters in the buildspec.yml with your AWS Account ID and Region.** The buildspec.yml uses the staging S3 bucket as the template-s3-uri parameter while invoking the aws configservice put-conformance-pack cli. 34 | 4. In each of the aws-pci-conformancpack-v1-[1,2,3] templates **substitute the accountid and region parameters in the AutomationAssumeRole ARN parameter with your AWS Account ID and Region.** 35 | 36 | 37 | ## How To Install 38 | 39 | 1. **Template 1 of 2:** aws-pci-confpack-ssmautomation-v1.yml 40 | * Sets up AWS Systems Manager Automation Documents for PCI related Auto Healing and the required PCI remediation related pre-requisites. No parameters needed. Installs in approx 2-3 mins. 41 | 42 | 2. **Template 2 of 2:** aws-pci-confpack-codepipeline.yml 43 | * Sets up AWS CodePipeline based DevSecOps automation 44 | * Installs aws-pci-conformancepack-v1-[1,2,3].yml for custom AWS Config Conformance Packs with Remediation for PCI 45 | 46 | ## COVERAGE 47 | 48 | The [Coverage Matrix](coverage/AWSPCIConformancePacksAutoHealingCoverage.xlsx) provides the current coverage of this solution versus the PCI Benchmarks 49 | 50 | ## @kmmahaj 51 | -------------------------------------------------------------------------------- /aws-cloudfoundations-baseline-demo/cft/aws-pci-custom-confpack-org.yml: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 3 | # Provisions Org Custom Conformance Packs 4 | # 5 | # @kmmahaj 6 | # 7 | # License: 8 | # This code is made available under the MIT-0 license. See the LICENSE file. 9 | ################################################################################ 10 | 11 | Parameters: 12 | 13 | DeliveryS3Bucket: 14 | Description: The name of the Amazon S3 bucket where AWS Config stores conformance pack templates. 15 | Type: String 16 | Default: 'awsconfigconforms-orgbucket' 17 | 18 | OrganizationConformancePackName: 19 | Description: Name of the custom config conformance pack 20 | Type: String 21 | Default: 'aws-pcicustomconfpack-remediations-org' 22 | 23 | TemplateS3Uri: 24 | Description: Location of S3 file containing the conformance pack template body. Points to the conformance pack template 25 | Type: String 26 | Default: 's3://s3-pci-confpack-org/aws-pci-conformancepack-remediations-v1.yml' 27 | 28 | Resources: 29 | 30 | OrganizationConformancePack: 31 | Type: 'AWS::Config::OrganizationConformancePack' 32 | Properties: 33 | OrganizationConformancePackName: !Ref OrganizationConformancePackName 34 | DeliveryS3Bucket: !Ref DeliveryS3Bucket 35 | TemplateS3Uri: !Ref TemplateS3Uri 36 | -------------------------------------------------------------------------------- /aws-config-aggregator/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Enable AWS Config Aggregator across accounts and regions 5 | 6 | 1. An AWS Config Aggregator is an AWS Config resource type that collects AWS Config configuration and compliance data from multiple accounts and regions or from an AWS organization. All accounts must have AWS Config enabled. 7 | 2. The AWS account where the AWS Config Aggregator is created is called the aggregator account. The AWS account(s) that provide configuration and compliance data to this aggregator account are called the source accounts. 8 | 3. The aggregator account can be either the management account or a registered delegated administrator account. All features must be enabled in your organization. 9 | - If you are using a delegated administrator account as the aggregator account then ensure that the management account registers this account as the delegated administrator for the AWS Config service principle name (config.amazonaws.com). 10 | 4. If the Config Aggregator is configured to collect data from individual source accounts then each source account must provide authorization for the data to be collected. If the Config Aggregator is configured to collect data from an AWS organization then explicit authorization from a source account is not required. 11 | 12 | 13 | ## Option 1: Use OrganizationEnableRecorderAndAggregator.yaml - Create Config Aggregator in aggregator account for data collection across the AWS Organization 14 | 15 | 1. Enables AWS Config in your account if Config is not already enabled. Provisions recorder, delivery channel, S3 bucket and bucket policy required to enable Config 16 | 2. Launch this template from the aggregator account. Creates an AWS Config Aggregator from the aggregator account. It uses a service linked role that retrieves AWS Organization details associated with the aggregator account. 17 | - This creates an IAM role that attaches the AWSConfigRoleForOrganizations managed policy to your IAM role. Attaching this policy allows AWS Config obtain Organization details associated with the aggregator account. 18 | 19 | 20 | ## Option 2: Use AccountEnableRecorderAndAggregator-v1.yaml - Create Config Aggregator in aggregator account and add authorization in individual source region(s) of that same account 21 | 22 | 1. Enables AWS Config in your account if Config is not already enabled. Provisions recorder, delivery channel, S3 bucket and bucket policy required to enable Config 23 | 2. Launch this template from the aggregator account. Provide input for the following parameters: 24 | *AggregatorAccount*: AWS Account ID of the aggregator account 25 | *AggregatorRegion*: AWS region of the aggregator 26 | *SourceRegion1:* AWS region to aggregate 27 | *SourceRegion2:* AWS region to aggregate 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /aws-config-aggregator/cft/AccountEnableRecorderAndAggregator.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Enable AWS Config (qs-1t0eilb5g) 3 | 4 | Metadata: 5 | AWS::CloudFormation::Interface: 6 | ParameterGroups: 7 | - Label: 8 | default: Configuration Recorder Configuration 9 | Parameters: 10 | - GlobalResourceTypesRegion 11 | - Label: 12 | default: Configuration Aggregator Configuration 13 | Parameters: 14 | - AggregatorAccount 15 | - AggregatorRegion 16 | ParameterLabels: 17 | GlobalResourceTypesRegion: 18 | default: Global resource types region 19 | AggregatorAccount: 20 | default: Aggregator account 21 | AggregatorRegion: 22 | default: Aggregator account 23 | SourceRegion1: 24 | default: Source region 1 25 | SourceRegion2: 26 | default: Source region 2 27 | 28 | 29 | Parameters: 30 | GlobalResourceTypesRegion: 31 | Type: String 32 | Default: us-east-1 33 | Description: AWS region used to record global resources types 34 | AggregatorAccount: 35 | Type: String 36 | Description: Account ID of the aggregator 37 | AggregatorRegion: 38 | Type: String 39 | Default: us-east-1 40 | Description: AWS region of the aggregator 41 | SourceRegion1: 42 | Type: String 43 | Description: 1st region to aggregate 44 | SourceRegion2: 45 | Type: String 46 | Description: 2nd region to aggregate 47 | CreateRecorder: 48 | Type: String 49 | Default: 'yes' 50 | AllowedValues: 51 | - 'yes' 52 | - 'no' 53 | Description: Should this template create the recorder 54 | 55 | Conditions: 56 | IncludeGlobalResourceTypes: !Equals 57 | - !Ref GlobalResourceTypesRegion 58 | - !Ref AWS::Region 59 | CreateAggregator: !And 60 | - !Equals 61 | - !Ref AggregatorAccount 62 | - !Ref AWS::AccountId 63 | - !Equals 64 | - !Ref AggregatorRegion 65 | - !Ref AWS::Region 66 | CreateConfigRecorder: !Equals 67 | - !Ref CreateRecorder 68 | - 'yes' 69 | 70 | 71 | Resources: 72 | 73 | ConfigBucket: 74 | DeletionPolicy: Retain 75 | Type: AWS::S3::Bucket 76 | Properties: 77 | BucketEncryption: 78 | ServerSideEncryptionConfiguration: 79 | - ServerSideEncryptionByDefault: 80 | SSEAlgorithm: AES256 81 | 82 | ConfigBucketPolicy: 83 | Type: AWS::S3::BucketPolicy 84 | Condition: CreateConfigRecorder 85 | Properties: 86 | Bucket: !Ref ConfigBucket 87 | PolicyDocument: 88 | Version: 2012-10-17 89 | Statement: 90 | - Sid: AWSConfigBucketPermissionsCheck 91 | Effect: Allow 92 | Principal: 93 | Service: 94 | - config.amazonaws.com 95 | Action: s3:GetBucketAcl 96 | Resource: 97 | - !Sub "arn:aws:s3:::${ConfigBucket}" 98 | - Sid: DisallowHTTP 99 | Effect: Deny 100 | Principal: '*' 101 | Action: 's3:*' 102 | Resource: 103 | - !Sub "arn:aws:s3:::${ConfigBucket}" 104 | Condition: 105 | Bool: 106 | 'aws:SecureTransport': false 107 | - Sid: AWSConfigBucketDelivery 108 | Effect: Allow 109 | Principal: 110 | Service: 111 | - config.amazonaws.com 112 | Action: s3:PutObject 113 | Resource: 114 | - !Sub "arn:aws:s3:::${ConfigBucket}/AWSLogs/${AWS::AccountId}/*" 115 | 116 | ConfigRecorderRole: 117 | Type: AWS::IAM::Role 118 | Condition: CreateConfigRecorder 119 | Properties: 120 | AssumeRolePolicyDocument: 121 | Version: 2012-10-17 122 | Statement: 123 | - Effect: Allow 124 | Principal: 125 | Service: 126 | - config.amazonaws.com 127 | Action: 128 | - sts:AssumeRole 129 | Path: / 130 | ManagedPolicyArns: 131 | - arn:aws:iam::aws:policy/service-role/AWSConfigRole 132 | 133 | ConfigRecorder: 134 | Type: AWS::Config::ConfigurationRecorder 135 | Condition: CreateConfigRecorder 136 | DependsOn: 137 | - ConfigRecorderRole 138 | - ConfigBucketPolicy 139 | Properties: 140 | RoleARN: !GetAtt ConfigRecorderRole.Arn 141 | RecordingGroup: 142 | AllSupported: True 143 | IncludeGlobalResourceTypes: !If 144 | - IncludeGlobalResourceTypes 145 | - True 146 | - False 147 | 148 | DeliveryChannel: 149 | Type: AWS::Config::DeliveryChannel 150 | Condition: CreateConfigRecorder 151 | DependsOn: 152 | - ConfigBucketPolicy 153 | Properties: 154 | Name: default 155 | S3BucketName: !Ref ConfigBucket 156 | 157 | S3BucketPublicReadRule: 158 | Type: AWS::Config::ConfigRule 159 | Condition: CreateConfigRecorder 160 | DependsOn: 161 | - ConfigRecorder 162 | Properties: 163 | ConfigRuleName: stackset-s3-bucket-public-read-prohibited 164 | Description: s3-bucket-public-read-prohibited from stackset 165 | Scope: 166 | ComplianceResourceTypes: 167 | - AWS::S3::Bucket 168 | Source: 169 | Owner: AWS 170 | SourceIdentifier: S3_BUCKET_PUBLIC_READ_PROHIBITED 171 | 172 | 173 | ConfigAggregator: 174 | Type: AWS::Config::ConfigurationAggregator 175 | Condition: CreateAggregator 176 | Properties: 177 | ConfigurationAggregatorName: default 178 | AccountAggregationSources: 179 | - AccountIds: 180 | - !Ref AggregatorAccount 181 | AwsRegions: 182 | - !Ref SourceRegion1 183 | - !Ref SourceRegion2 184 | 185 | -------------------------------------------------------------------------------- /aws-config-aggregator/cft/OrganizationEnableRecorderAndAggregator.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Enable AWS Config Aggregator and Recorder for an Organization (qs-1t0eilb5g) 3 | 4 | Parameters: 5 | GlobalResourceTypesRegion: 6 | Type: String 7 | Default: us-east-1 8 | Description: AWS region used to record global resources types 9 | OrgAggregatorName: 10 | Type: String 11 | Default: OrganizationalRecorder 12 | AllowedPattern: "^[\\w\\-]+" 13 | ConstraintDescription: "" 14 | Description: Name of the organizational aggregator 15 | CreateRecorder: 16 | Type: String 17 | Default: 'yes' 18 | AllowedValues: 19 | - 'yes' 20 | - 'no' 21 | Description: Should this template create the recorder 22 | 23 | 24 | Conditions: 25 | IncludeGlobalResourceTypes: !Equals 26 | - !Ref GlobalResourceTypesRegion 27 | - !Ref AWS::Region 28 | CreateConfigRecorder: !Equals 29 | - !Ref CreateRecorder 30 | - 'yes' 31 | 32 | 33 | Resources: 34 | 35 | ConfigBucket: 36 | Type: AWS::S3::Bucket 37 | Properties: 38 | BucketEncryption: 39 | ServerSideEncryptionConfiguration: 40 | - ServerSideEncryptionByDefault: 41 | SSEAlgorithm: AES256 42 | 43 | ConfigBucketPolicy: 44 | Type: AWS::S3::BucketPolicy 45 | Condition: CreateConfigRecorder 46 | Properties: 47 | Bucket: !Ref ConfigBucket 48 | PolicyDocument: 49 | Version: 2012-10-17 50 | Statement: 51 | - Sid: AWSConfigBucketPermissionsCheck 52 | Effect: Allow 53 | Principal: 54 | Service: 55 | - config.amazonaws.com 56 | Action: s3:GetBucketAcl 57 | Resource: 58 | - !Sub "arn:aws:s3:::${ConfigBucket}" 59 | - Sid: DisallowHTTP 60 | Effect: Deny 61 | Principal: '*' 62 | Action: 's3:*' 63 | Resource: 64 | - !Sub "arn:aws:s3:::${ConfigBucket}" 65 | Condition: 66 | Bool: 67 | 'aws:SecureTransport': false 68 | - Sid: AWSConfigBucketDelivery 69 | Effect: Allow 70 | Principal: 71 | Service: 72 | - config.amazonaws.com 73 | Action: s3:PutObject 74 | Resource: 75 | - !Sub "arn:aws:s3:::${ConfigBucket}/AWSLogs/${AWS::AccountId}/*" 76 | 77 | ConfigRecorderRole: 78 | Type: AWS::IAM::Role 79 | Condition: CreateConfigRecorder 80 | Properties: 81 | AssumeRolePolicyDocument: 82 | Version: 2012-10-17 83 | Statement: 84 | - Effect: Allow 85 | Principal: 86 | Service: 87 | - config.amazonaws.com 88 | Action: 89 | - sts:AssumeRole 90 | Path: / 91 | ManagedPolicyArns: 92 | - arn:aws:iam::aws:policy/service-role/AWSConfigRole 93 | 94 | ConfigRecorder: 95 | Type: AWS::Config::ConfigurationRecorder 96 | Condition: CreateConfigRecorder 97 | DependsOn: 98 | - ConfigBucketPolicy 99 | Properties: 100 | RoleARN: !GetAtt ConfigRecorderRole.Arn 101 | RecordingGroup: 102 | AllSupported: True 103 | IncludeGlobalResourceTypes: !If 104 | - IncludeGlobalResourceTypes 105 | - True 106 | - False 107 | 108 | DeliveryChannel: 109 | Type: AWS::Config::DeliveryChannel 110 | Condition: CreateConfigRecorder 111 | DependsOn: 112 | - ConfigBucketPolicy 113 | Properties: 114 | Name: default 115 | S3BucketName: !Ref ConfigBucket 116 | 117 | S3BucketPublicReadRule: 118 | Type: AWS::Config::ConfigRule 119 | Condition: CreateConfigRecorder 120 | DependsOn: 121 | - ConfigRecorder 122 | Properties: 123 | ConfigRuleName: stackset-s3-bucket-public-read-prohibited 124 | Description: s3-bucket-public-read-prohibited from stackset 125 | Scope: 126 | ComplianceResourceTypes: 127 | - AWS::S3::Bucket 128 | Source: 129 | Owner: AWS 130 | SourceIdentifier: S3_BUCKET_PUBLIC_READ_PROHIBITED 131 | 132 | 133 | ConfigurationAggregator: 134 | Type: 'AWS::Config::ConfigurationAggregator' 135 | Properties: 136 | OrganizationAggregationSource: 137 | RoleArn: 138 | !Join 139 | - '' 140 | - - 'arn:aws:iam::' 141 | - !Ref 'AWS::AccountId' 142 | - ':role/aws-service-role/organizations.amazonaws.com/AWSServiceRoleForOrganizations' 143 | AllAwsRegions: true 144 | ConfigurationAggregatorName: !Ref OrgAggregatorName -------------------------------------------------------------------------------- /aws-config-aggregator/images/aggregator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-config-aggregator/images/aggregator.png -------------------------------------------------------------------------------- /aws-config-visualization/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | ## AWS SSM Automation Runbook to Setup AWS Config with Amazon Athena and Amazon QuickSights 5 | This solution is based on the blog [Visualizing AWS Config data using Amazon Athena and Amazon QuickSight](https://aws.amazon.com/blogs/mt/visualizing-aws-config-data-using-amazon-athena-and-amazon-quicksight/). 6 | 7 | ### What does this cloudformation template do? 8 | This template will deploy a SSM Automation runbook called **Config-QuickSight-Visualization** that can be used to setup AWS Config to be used with Amazon Athena and setup Amazon Quicksights to be able to create visualize dashboards 9 | 10 | ## Running the Config-QuickSight-Visualization Automation Runbook 11 | 12 | ### Prerequisite 13 | 1. Configure [Delivering Configuration Snapshot to an Amazon S3 Bucket](https://docs.aws.amazon.com/config/latest/developerguide/deliver-snapshot-cli.html) for AWS. 14 | 1. Ensure access to your S3 Bucket that is used for AWS Config. 15 | 1. The S3 Bucket Name used with AWS Config. 16 | 1. [Amazon Quicksight Subscription](https://docs.aws.amazon.com/quicksight/latest/user/signing-up.html) enabled in your AWS Account. 17 | 1. Authorize [Amazon QuickSight access](https://docs.aws.amazon.com/quicksight/latest/user/athena.html) to the S3 bucket Athena will be using for AWS Config under Security and Permissions within Amazon Quicksights. 18 | 1. The Amazon Quicksight Username. 19 | 20 | ### Input Parameters for the Config-QuickSight-Visualization Automation Runbook 21 | * **ConfigDeliveryChannelName:** (Required) Name of your AWS Config Delievery Channel. The default is set to the value of default. 22 | * **ConfigS3BucketLocation:** (Required) AWS Config S3 Bucket Name, this is the name of your S3 Bucket you currently use for AWS Config. (ie config-bucket-1234567891) 23 | * **QuickSightUserName:** (Required) The Amazon QuickSight Username. 24 | * **AutomationAssumeRole:** (Optional) The ARN of the role that allows Automation to perform the actions on your behalf. 25 | * **DeleteConfigVisualization:** (Optional) Set this to true if you would like to delete the resources created to enable this solution. The default is set to false which will setup the solution. 26 | 27 | ## Creating Visuals in Amazon QuickSight 28 | 29 | The **Config-QuickSight-Visualization** Automation Runbook will create the below views and datasets within Amazon Athena and Amazon QuickSight. You can then use these to create your visualization dashboard. 30 | 31 | * v_config_rules_compliance 32 | * v_config_resource_compliance 33 | * v_config_rds_dbinstances 34 | * v_config_iam_resources 35 | * v_config_ec2_vpcs 36 | * v_config_ec2_instances 37 | * v_config_resources 38 | 39 | #### Creating your Analyses in Amazon QuickSight 40 | 41 | 1. From Amazon QuickSight, choose **New analysis**. 42 | 1. On the **Datasets** page, choose the **v_config_resource_compliance** data set and then choose **Create Analysis**. 43 | 44 | #### Create a Visual By Using AutoGraph 45 | 46 | 1. Create a visual by using AutoGraph, which is selected by default. 47 | 1. On the analysis page, choose **accountid** and **compliancetype** in the Fields list pane. 48 | 1. Amazon QuickSight creates a **Horizontal bar chart** using this data. 49 | 50 | #### Adding Additional Datasets to your Analyses 51 | 52 | 1. You can add more data sets to the analysis to create more visuals. 53 | 1. From within the analysis, click the **Add,edit,replace and remove datasets** icon. 54 | 1. Click **Add Datasets**. 55 | 1. Select the **v_config_rules_compliance** and click **Select** 56 | 1. In the **Visual types** pane, choose the **Vertical Bar Chart** icon. 57 | 1. On the analysis page, choose **configrulename** and **compliancetype** in the Fields list pane. 58 | 1. You can create a filter on any field in the currently selected visual. When you create a filter, it applies by default to the currently selected visual only. 59 | 1. Click on the **Filter** icon within the Amazon QuickSight side bar. 60 | 1. Under the Filters section click "**Create one...**" and select the **configrulename** field. 61 | 1. Click on the **configrulename** field and uncheck the **Select all** check box. 62 | 1. Select a couple of Config Rules you would like to dispaly in your visual and clikc **Apply**. 63 | 1. You can then click on the **Visualize** button on the side bar to return to make changes to your visual. 64 | 65 | #### Create a Dashboard 66 | 67 | 1. In the analysis, choose **Share** in the application bar at upper-right, and then choose **Publish dashboard**. 68 | 1. In the **Publish dashboard** page that opens, choose **Publish new dashboard as**, and enter the name **Config Dashboard**. 69 | 1. Choose **Publish dashboard**. 70 | 1. On the **Share dashboard** page that opens, choose the **X** icon to close it. 71 | -------------------------------------------------------------------------------- /aws-configremediations-fsbp/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kanishk Mahajan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /aws-configremediations-fsbp/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Remediations for AWS FSBP Benchmarks using AWS Config and custom AWS Systems Manager Automation Documents 5 | 6 | Template 1 first provisions AWS Systems Manager Automation Documents as well as all the required pre-reqs. Template 2 then leverages the Systems Manager Automation documents within AWS Config Remediation Rules. 7 | 8 | 9 | ## COVERAGE 10 | 11 | The solution provides remediations for the following AWS FSBP checks: 12 | * [EC2.3] Attached EBS volumes should be encrypted at-rest 13 | * [GuardDuty.1] GuardDuty should be enabled 14 | * [IAM.3] IAM users' access keys should be rotated every 90 days or less 15 | * [Lambda.1] Lambda functions should prohibit public access by other accounts 16 | * [Lambda.2] Lambda functions should use latest runtimes 17 | * [RDS.3] RDS DB instances should have encryption at-rest enabled 18 | * [SSM.1] EC2 instances should be managed by AWS Systems Manager 19 | * [AutoScaling.1] Auto Scaling groups associated with a load balancer should use load balancer health checks 20 | * [CloudTrail.1] CloudTrail should be enabled and configured with at least one multi-Region trail 21 | * [CloudTrail.2] CloudTrail should have encryption at-rest enabled 22 | * [CodeBuild.2] CodeBuild project environment variables should not contain clear text credentials 23 | * [Config.1] AWS Config should be enabled 24 | * [EC2.1] Amazon EBS snapshots should not be public, determined by the ability to be restorable by anyone 25 | * [EC2.2] The VPC default security group should not allow inbound and outbound traffic 26 | * [IAM.1] IAM policies should not allow full * administrative privileges 27 | * [IAM.2] IAM users should not have IAM policies attached 28 | * [IAM.4] IAM root user access key should not exist 29 | * [IAM.7] Password policies for IAM users should have strong configurations 30 | * [S3.1] S3 Block Public Access setting should be enabled 31 | * [S3.2] S3 buckets should prohibit public read access 32 | * [S3.3] S3 buckets should prohibit public write access 33 | * [S3.4] S3 buckets should have server-side encryption enabled 34 | * [RDS.1] RDS snapshots should be private 35 | * [RDS.2] RDS DB instances should prohibit public access, determined by the PubliclyAccessible configuration 36 | * [SSM.2] Amazon EC2 instances managed by Systems Manager should have a patch compliance status of COMPLIANT after a patch installation 37 | 38 | ## Solution Design 39 | 40 | ![](images/arch-diagramfsbp.png) 41 | 42 | 43 | ## How To Install 44 | 45 | 1. **Template 1 of 2:** aws-fsbp-systemsmanagerautomations.yml 46 | * Provisions AWS Systems Manager automation documents. These documents are used to provide automated remediations within the provisioned AWS Config Rule. 47 | * Provisions with fully built-in pre-reqs. No input parameters required. Simply install on the CloudFormation console (or CLI). Installs in approx 3-4 mins. 48 | 49 | 2. **Template 2 of 2:** aws-fsbp-configremediations.yml 50 | * Provisions AWS Config Managed Rules and attaches the custom AWS Systems Manager automation documents as AWS Config Remediations to the AWS Config Managed Rule. No input parameters. Simply install on the CloudFormation console (or CLI). Installs in approx 3-4 mins. 51 | * Leverages the output from the previous template specifically the AWS Systems Manager Automation documents 52 | 53 | 54 | ## Author 55 | 56 | Kanishk Mahajan; kmmahaj@amazon.com 57 | -------------------------------------------------------------------------------- /aws-configremediations-fsbp/coverage/AWS SecurityHub Benchmarks-Coverage-v1.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-configremediations-fsbp/coverage/AWS SecurityHub Benchmarks-Coverage-v1.xlsx -------------------------------------------------------------------------------- /aws-configremediations-fsbp/images/arch-diagramfsbp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-configremediations-fsbp/images/arch-diagramfsbp.png -------------------------------------------------------------------------------- /aws-configremediations-pci/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kanishk Mahajan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /aws-configremediations-pci/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Remediations for PCI DSS 3.2.1 using AWS Config and custom AWS Systems Manager Automation Documents 5 | 6 | Template 1 first provisions AWS Systems Manager Automation Documents as well as all the required pre-reqs. Template 2 then leverages the Systems Manager Automation documents within AWS Config Remediation Rules. 7 | 8 | 9 | ## COVERAGE 10 | 11 | The solution provides remediations for the following PCI checks: 12 | ``` 13 | * [PCI.AutoScaling.1] Auto scaling groups associated with a load balancer should use health checks 14 | * [PCI.CloudTrail.1] CloudTrail logs should be encrypted at rest using AWS KMS CMK 15 | * [PCI.CloudTrail.2] CloudTrail should be enabled 16 | * [PCI.CloudTrail.3] CloudTrail log file validation should be enabled 17 | * [PCI.CloudTrail.4] CloudTrail trails should be integrated with CloudWatch Logs 18 | * [PCI.CodeBuild.2] CodeBuild project environment variables should not contain clear text credentials 19 | * [PCI.CW.1] A log metric filter and alarm should exist for usage of the "root" user 20 | * [PCI.Config.1] AWS Config should be enabled 21 | * [PCI.EC2.1] Amazon EBS snapshots should not be publicly restorable 22 | * [PCI.EC2.2] VPC default security group should prohibit inbound and outbound traffic 23 | * [PCI.EC2.3] Unused EC2 security groups should be removed 24 | * [PCI.EC2.4] Unused EC2 EIPs should be removed 25 | * [PCI EC2.5] Security groups should not allow ingress from 0.0.0.0/0 to port 22 26 | * [PCI.EC2.6] Ensure VPC flow logging is enabled in all VPCs 27 | * [PCI.IAM.1] IAM root user access key should not exist 28 | * [PCI.IAM.2] IAM users should not have IAM policies attached 29 | * [PCI.IAM.3] IAM policies should not allow full * administrative privileges 30 | * [PCI.KMS.1] Customer master key (CMK) rotation should be enabled 31 | * [PCI.Lambda.1] Lambda functions should prohibit public access 32 | * [PCI.Lambda.2] Lambda functions should be in a VPC 33 | * [PCI.RDS.1] RDS snapshots should prohibit public access 34 | * [PCI.RDS.2] RDS DB Instances should prohibit public access 35 | * [PCI.Redshift.1] Amazon Redshift clusters should prohibit public access 36 | * [PCI.S3.1] S3 buckets should prohibit public write access 37 | * [PCI.S3.2] S3 buckets should prohibit public read access 38 | * [PCI.S3.3] S3 buckets should have cross-region replication enabled 39 | * [PCI.S3.4] S3 buckets should have server-side encryption enabled 40 | * [PCI.SSM.1] Amazon EC2 instances managed by Systems Manager should have a patch compliance status of COMPLIANT after a patch installation 41 | ``` 42 | 43 | ## Solution Design 44 | 45 | ![](images/arch-diagrampci.png) 46 | 47 | 48 | ## How To Install 49 | 50 | 1. **Template 1 of 2:** aws-pci-systemsmanagerautomations.yml 51 | * Provisions AWS Systems Manager automation documents. These documents are used to provide automated remediations within the provisioned AWS Config Rule. 52 | * Provisions with fully built-in pre-reqs. No input parameters required. Simply install on the CloudFormation console (or CLI). Installs in approx 3-4 mins. 53 | 54 | 2. **Template 2 of 2:** aws-pci-configremediations.yml 55 | * Provisions AWS Config Managed Rules and attaches the custom AWS Systems Manager automation documents as AWS Config Remediations to the AWS Config Managed Rule. No input parameters. Simply install on the CloudFormation console (or CLI). Installs in approx 3-4 mins. 56 | * Leverages the output from the previous template specifically the AWS Systems Manager Automation documents 57 | 58 | 59 | -------------------------------------------------------------------------------- /aws-configremediations-pci/coverage/AWS SecurityHub Benchmarks-Coverage-v1.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-configremediations-pci/coverage/AWS SecurityHub Benchmarks-Coverage-v1.xlsx -------------------------------------------------------------------------------- /aws-configremediations-pci/images/arch-diagrampci.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-configremediations-pci/images/arch-diagrampci.png -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kanishk Mahajan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # DevSecOps for Auto Healing PCI Compliance using custom AWS Config Conformance Packs and AWS CodePipeline 5 | 6 | Augments the AWS Config Conformance Pack for Operational Best Practices for PCI DSS 3.2.1 with 2 features – 7 | 1. Auto healing for PCI related AWS Config Managed rules. Adds Remediation to the PCI Conformance Packs. Implemented using Custom AWS Config Conformance Packs that leverage custom AWS Systems Manager Automation Documents provided via AWS CloudFormation 8 | 2. DevSecOps CI/CD pipeline for PCI compliance that incorporates “PCI Compliance as code” in an existing DevOps workflows. Implemented via integrating AWS Custom Config Conformance Packs with AWS CodePipeline and provided via AWS CloudFormation. 9 | 10 | 11 | 12 | ## How it Works 13 | 14 | 1. aws-pci-confpack-codepipeline.yml 15 | - Triggers an AWS CodePipeline based CI/CD pipeline whenever there is an update to the source AWS CloudFormation templates in your local Git repository. These source AWS CloudFormation templates incorporate the code for the custom AWS Config Conformance Packs. 16 | - Provisions an AWS CodePipeline automation with AWS CodeCommit and AWS CodeBuild stages for the build and deployment of the AWS Config Conformance Packs 17 | 2. aws-pci-confpack-ssmautomation-v1.yml 18 | - Provisions custom AWS Systems Manager automation documents for PCI remediation. These documents are used to provide automated remediations within the provisioned AWS Config rule using the AWS:Config:RemediationConfiguration CloudFormation construct in the AWS Config Conformance Pack. 19 | - Provisions pre-requisites for the AWS Config Conformance Pack deployment such as the AWS Systems Manager automation role, S3 buckets for logging and replication for S3 related remediations and CloudWatch logs and CloudWatch role for AWS CloudTrail related remediations for PCI compliance 20 | 3. Custom AWS Config Conformance Packs 21 | - aws-pci-conformancepack-v1-1.yml – Provisions a custom AWS Config Conformance Pack for the detection and remediation for Amazon EC2, AWS Auto Scaling and AWS Lambda based PCI Compliance violations 22 | - aws-pci-conformancepack-v1-2.yml - Provisions a custom AWS Config Conformance Pack for the detection and remediation for AWS CloudTrail, AWS KMS and AWS CodeBuild based PCI Compliance violations 23 | - aws-pci-conformancepack-v1-3.yml - Provisions a custom AWS Config Conformance Pack for the detection and remediation for Amazon Redshift, AWS RDS and AWS IAM based PCI Compliance violations. 24 | 25 | 26 | ## Solution Design 27 | 28 | ![](images/arch-diagram.png) 29 | 30 | ## Prerequisites 31 | 1. Custom AWS Config Conformance Packs - Set up prerequisites for deploying and building with both AWS Config Conformance Packs as well as custom AWS Config Conformance Packs with remediations. Refer to AWS documentation 32 | 2. Local Git repository and AWS CodeCommit Git repository setup – Create an AWS CodeCommit Git Repository in your AWS account and integrate it with your local Git repository. Refer to AWS documentation. 33 | 3. Staging S3 bucket – The solution creates a staging S3 bucket with the following naming convention: **s3-pciautohealconfpack--accountid-region. Substitute the accountid and region parameters in the buildspec.yml with your AWS Account ID and Region.** The buildspec.yml uses the staging S3 bucket as the template-s3-uri parameter while invoking the aws configservice put-conformance-pack cli. 34 | 4. In each of the aws-pci-conformancpack-v1-[1,2,3] templates **substitute the accountid and region parameters in the AutomationAssumeRole ARN parameter with your AWS Account ID and Region.** 35 | 36 | 37 | ## How To Install 38 | 39 | 1. **Template 1 of 2:** aws-pci-confpack-ssmautomation-v1.yml 40 | * Sets up AWS Systems Manager Automation Documents for PCI related Auto Healing and the required PCI remediation related pre-requisites. No parameters needed. Installs in approx 2-3 mins. 41 | 42 | 2. **Template 2 of 2:** aws-pci-confpack-codepipeline.yml 43 | * Sets up AWS CodePipeline based DevSecOps automation 44 | * Installs aws-pci-conformancepack-v1-[1,2,3].yml for custom AWS Config Conformance Packs with Remediation for PCI 45 | 46 | ## COVERAGE 47 | 48 | The [Coverage Matrix](coverage/AWSPCIConformancePacksAutoHealingCoverage.xlsx) provides the current coverage of this solution versus the PCI Benchmarks 49 | 50 | -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/cft/aws-pci-conformancepack-update-v1.yml: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 3 | # PCI Conformance Pack with Remediations - EC2, Autoscaling, Lambda 4 | # 5 | # @kmmahaj 6 | # 7 | # License: 8 | # This code is made available under the MIT-0 license. See the LICENSE file. 9 | ################################################################################ 10 | AWSTemplateFormatVersion: '2010-09-09' 11 | Description: PCI Conformance Pack with Remediations - EC2, Autoscaling, Lambda (qs-1t0eilb5g) 12 | 13 | Parameters: 14 | 15 | DeliveryS3Bucket: 16 | Description: Delivery Bucket from AWS Config settings 17 | Type: String 18 | Default: 'config-bucket-accountid' 19 | 20 | Resources: 21 | 22 | ConformancePack: 23 | Type: 'AWS::Config::ConformancePack' 24 | Properties: 25 | ConformancePackName: CustomPCIEC2LambdaConfPack 26 | DeliveryS3Bucket: !Ref DeliveryS3Bucket 27 | TemplateBody: |- 28 | Resources: 29 | AutoScalingELBHealthCheck: 30 | Type: AWS::Config::ConfigRule 31 | Properties: 32 | ConfigRuleName: AutoScalingELBHealthCheck 33 | Description: >- 34 | [PCI.AutoScaling.1] Auto scaling groups associated with a load balancer should use health checks 35 | Scope: 36 | ComplianceResourceTypes: 37 | - "AWS::AutoScaling::AutoScalingGroup" 38 | Source: 39 | Owner: AWS 40 | SourceIdentifier: AUTOSCALING_GROUP_ELB_HEALTHCHECK_REQUIRED 41 | AutoScalingELBHealthCheckRemediation: 42 | DependsOn: AutoScalingELBHealthCheck 43 | Type: 'AWS::Config::RemediationConfiguration' 44 | Properties: 45 | ConfigRuleName: AutoScalingELBHealthCheck 46 | ResourceType: "AWS::AutoScaling::AutoScalingGroup" 47 | TargetId: "Custom-AutoScalingELBHealthCheck" 48 | TargetType: "SSM_DOCUMENT" 49 | TargetVersion: "1" 50 | Parameters: 51 | AutomationAssumeRole: 52 | StaticValue: 53 | Values: 54 | - arn:aws:iam::accountid:role/pciautomationassumerole-region 55 | ASGGroupArn: 56 | ResourceValue: 57 | Value: "RESOURCE_ID" 58 | ExecutionControls: 59 | SsmControls: 60 | ConcurrentExecutionRatePercentage: 10 61 | ErrorPercentage: 10 62 | Automatic: True 63 | MaximumAutomaticAttempts: 10 64 | RetryAttemptSeconds: 600 65 | RemoveUnusedEC2SecurityGroups: 66 | Type: AWS::Config::ConfigRule 67 | Properties: 68 | ConfigRuleName: RemoveUnusedEC2SecurityGroups 69 | Description: >- 70 | PCI.EC2.3 – Unused EC2 Security Groups should be removed 71 | Scope: 72 | ComplianceResourceTypes: 73 | - "AWS::EC2::SecurityGroup" 74 | Source: 75 | Owner: AWS 76 | SourceIdentifier: EC2_SECURITY_GROUP_ATTACHED_TO_ENI 77 | RemoveUnusedEC2SecurityGroupsRemediation: 78 | DependsOn: RemoveUnusedEC2SecurityGroups 79 | Type: 'AWS::Config::RemediationConfiguration' 80 | Properties: 81 | ConfigRuleName: RemoveUnusedEC2SecurityGroups 82 | ResourceType: "AWS::EC2::SecurityGroup" 83 | TargetId: "Custom-RemoveSecurityGroup" 84 | TargetType: "SSM_DOCUMENT" 85 | TargetVersion: "1" 86 | Parameters: 87 | AutomationAssumeRole: 88 | StaticValue: 89 | Values: 90 | - arn:aws:iam::accountid:role/pciautomationassumerole-region 91 | groupId: 92 | ResourceValue: 93 | Value: "RESOURCE_ID" 94 | ExecutionControls: 95 | SsmControls: 96 | ConcurrentExecutionRatePercentage: 10 97 | ErrorPercentage: 10 98 | Automatic: True 99 | MaximumAutomaticAttempts: 10 100 | RetryAttemptSeconds: 600 101 | RestrictDefaultSecurityGroup: 102 | Type: AWS::Config::ConfigRule 103 | Properties: 104 | ConfigRuleName: RestrictDefaultSecurityGroup 105 | Description: >- 106 | PCI.EC2.2 VPC default security group should prohibit inbound and outbound traffic 107 | Scope: 108 | ComplianceResourceTypes: 109 | - "AWS::EC2::SecurityGroup" 110 | Source: 111 | Owner: AWS 112 | SourceIdentifier: VPC_DEFAULT_SECURITY_GROUP_CLOSED 113 | RestrictDefaultSecurityGroupRemediation: 114 | DependsOn: RestrictDefaultSecurityGroup 115 | Type: 'AWS::Config::RemediationConfiguration' 116 | Properties: 117 | ConfigRuleName: RestrictDefaultSecurityGroup 118 | ResourceType: "AWS::EC2::SecurityGroup" 119 | TargetId: "Custom-RestrictSecurityGroup" 120 | TargetType: "SSM_DOCUMENT" 121 | TargetVersion: "1" 122 | Parameters: 123 | AutomationAssumeRole: 124 | StaticValue: 125 | Values: 126 | - arn:aws:iam::accountid:role/pciautomationassumerole-region 127 | IpAddressToBlock: 128 | StaticValue: 129 | Values: 130 | - '0.0.0.0/0' 131 | groupId: 132 | ResourceValue: 133 | Value: "RESOURCE_ID" 134 | ExecutionControls: 135 | SsmControls: 136 | ConcurrentExecutionRatePercentage: 10 137 | ErrorPercentage: 10 138 | Automatic: True 139 | MaximumAutomaticAttempts: 10 140 | RetryAttemptSeconds: 600 141 | ReleaseElasticIP: 142 | Type: AWS::Config::ConfigRule 143 | Properties: 144 | ConfigRuleName: ReleaseElasticIP 145 | Description: >- 146 | [PCI.EC2.4] Unused EC2 EIPs should be removed 147 | Scope: 148 | ComplianceResourceTypes: 149 | - "AWS::EC2::EIP" 150 | Source: 151 | Owner: AWS 152 | SourceIdentifier: EIP_ATTACHED 153 | ReleaseElasticIPRemediation: 154 | DependsOn: ReleaseElasticIP 155 | Type: 'AWS::Config::RemediationConfiguration' 156 | Properties: 157 | ConfigRuleName: ReleaseElasticIP 158 | ResourceType: "AWS::EC2::EIP" 159 | TargetId: "AWS-ReleaseElasticIP" 160 | TargetType: "SSM_DOCUMENT" 161 | TargetVersion: "1" 162 | Parameters: 163 | AutomationAssumeRole: 164 | StaticValue: 165 | Values: 166 | - arn:aws:iam::accountid:role/pciautomationassumerole-region 167 | AllocationId: 168 | ResourceValue: 169 | Value: "RESOURCE_ID" 170 | ExecutionControls: 171 | SsmControls: 172 | ConcurrentExecutionRatePercentage: 10 173 | ErrorPercentage: 10 174 | Automatic: True 175 | MaximumAutomaticAttempts: 10 176 | RetryAttemptSeconds: 600 177 | -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/cft/aws-pci-conformancepack-v1-1.yml: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 3 | # PCI Conformance Pack with Remediations - EC2, Autoscaling, Lambda 4 | # 5 | # @kmmahaj 6 | # 7 | # License: 8 | # This code is made available under the MIT-0 license. See the LICENSE file. 9 | ################################################################################ 10 | AWSTemplateFormatVersion: '2010-09-09' 11 | Description: PCI Conformance Pack with Remediations - EC2, Autoscaling, Lambda (qs-1t0eilb5g) 12 | 13 | Resources: 14 | AutoScalingELBHealthCheck: 15 | Type: AWS::Config::ConfigRule 16 | Properties: 17 | ConfigRuleName: AutoScalingELBHealthCheck 18 | Description: >- 19 | [PCI.AutoScaling.1] Auto scaling groups associated with a load balancer should use health checks 20 | Scope: 21 | ComplianceResourceTypes: 22 | - "AWS::AutoScaling::AutoScalingGroup" 23 | Source: 24 | Owner: AWS 25 | SourceIdentifier: AUTOSCALING_GROUP_ELB_HEALTHCHECK_REQUIRED 26 | AutoScalingELBHealthCheckRemediation: 27 | DependsOn: AutoScalingELBHealthCheck 28 | Type: 'AWS::Config::RemediationConfiguration' 29 | Properties: 30 | ConfigRuleName: AutoScalingELBHealthCheck 31 | ResourceType: "AWS::AutoScaling::AutoScalingGroup" 32 | TargetId: "Custom-AutoScalingELBHealthCheck" 33 | TargetType: "SSM_DOCUMENT" 34 | TargetVersion: "1" 35 | Parameters: 36 | AutomationAssumeRole: 37 | StaticValue: 38 | Values: 39 | - arn:aws:iam:::role/automationassumerole- 40 | ASGGroupArn: 41 | ResourceValue: 42 | Value: "RESOURCE_ID" 43 | ExecutionControls: 44 | SsmControls: 45 | ConcurrentExecutionRatePercentage: 10 46 | ErrorPercentage: 10 47 | Automatic: True 48 | MaximumAutomaticAttempts: 10 49 | RetryAttemptSeconds: 600 50 | 51 | ReleaseElasticIP: 52 | Type: AWS::Config::ConfigRule 53 | Properties: 54 | ConfigRuleName: ReleaseElasticIP 55 | Description: >- 56 | [PCI.EC2.4] Unused EC2 EIPs should be removed 57 | Scope: 58 | ComplianceResourceTypes: 59 | - "AWS::EC2::EIP" 60 | Source: 61 | Owner: AWS 62 | SourceIdentifier: EIP_ATTACHED 63 | ReleaseElasticIPRemediation: 64 | DependsOn: ReleaseElasticIP 65 | Type: 'AWS::Config::RemediationConfiguration' 66 | Properties: 67 | ConfigRuleName: ReleaseElasticIP 68 | ResourceType: "AWS::EC2::EIP" 69 | TargetId: "AWS-ReleaseElasticIP" 70 | TargetType: "SSM_DOCUMENT" 71 | TargetVersion: "1" 72 | Parameters: 73 | AutomationAssumeRole: 74 | StaticValue: 75 | Values: 76 | - arn:aws:iam:::role/automationassumerole- 77 | AllocationId: 78 | ResourceValue: 79 | Value: "RESOURCE_ID" 80 | ExecutionControls: 81 | SsmControls: 82 | ConcurrentExecutionRatePercentage: 10 83 | ErrorPercentage: 10 84 | Automatic: True 85 | MaximumAutomaticAttempts: 10 86 | RetryAttemptSeconds: 600 87 | 88 | EBSPublicNonRestoreSnapshotEnabled: 89 | Type: "AWS::Config::ConfigRule" 90 | Properties: 91 | ConfigRuleName: EBSPublicNonRestoreSnapshotEnabled 92 | Description: "[PCI.EC2.1] Amazon EBS snapshots should not be publicly restorable" 93 | Source: 94 | Owner: AWS 95 | SourceIdentifier: EBS_SNAPSHOT_PUBLIC_RESTORABLE_CHECK 96 | EBSPublicNonRestoreSnapshotRemediation: 97 | DependsOn: EBSPublicNonRestoreSnapshotEnabled 98 | Type: 'AWS::Config::RemediationConfiguration' 99 | Properties: 100 | ConfigRuleName: EBSPublicNonRestoreSnapshotEnabled 101 | TargetId: "Custom-ModifySnapshot" 102 | TargetType: "SSM_DOCUMENT" 103 | TargetVersion: "1" 104 | Parameters: 105 | AutomationAssumeRole: 106 | StaticValue: 107 | Values: 108 | - arn:aws:iam:::role/automationassumerole- 109 | snapshotId: 110 | ResourceValue: 111 | Value: "RESOURCE_ID" 112 | ExecutionControls: 113 | SsmControls: 114 | ConcurrentExecutionRatePercentage: 10 115 | ErrorPercentage: 10 116 | Automatic: True 117 | MaximumAutomaticAttempts: 10 118 | RetryAttemptSeconds: 600 119 | 120 | RemoveUnusedEC2SecurityGroups: 121 | Type: AWS::Config::ConfigRule 122 | Properties: 123 | ConfigRuleName: RemoveUnusedEC2SecurityGroups 124 | Description: >- 125 | PCI.EC2.3 – Unused EC2 Security Groups should be removed 126 | Scope: 127 | ComplianceResourceTypes: 128 | - "AWS::EC2::SecurityGroup" 129 | Source: 130 | Owner: AWS 131 | SourceIdentifier: EC2_SECURITY_GROUP_ATTACHED_TO_ENI 132 | RemoveUnusedEC2SecurityGroupsRemediation: 133 | DependsOn: RemoveUnusedEC2SecurityGroups 134 | Type: 'AWS::Config::RemediationConfiguration' 135 | Properties: 136 | ConfigRuleName: RemoveUnusedEC2SecurityGroups 137 | ResourceType: "AWS::EC2::SecurityGroup" 138 | TargetId: "Custom-RemoveSecurityGroup" 139 | TargetType: "SSM_DOCUMENT" 140 | TargetVersion: "1" 141 | Parameters: 142 | AutomationAssumeRole: 143 | StaticValue: 144 | Values: 145 | - arn:aws:iam:::role/automationassumerole- 146 | groupId: 147 | ResourceValue: 148 | Value: "RESOURCE_ID" 149 | ExecutionControls: 150 | SsmControls: 151 | ConcurrentExecutionRatePercentage: 10 152 | ErrorPercentage: 10 153 | Automatic: True 154 | MaximumAutomaticAttempts: 10 155 | RetryAttemptSeconds: 600 156 | 157 | RestrictDefaultSecurityGroup: 158 | Type: AWS::Config::ConfigRule 159 | Properties: 160 | ConfigRuleName: RestrictDefaultSecurityGroup 161 | Description: >- 162 | PCI.EC2.2 VPC default security group should prohibit inbound and outbound traffic 163 | Scope: 164 | ComplianceResourceTypes: 165 | - "AWS::EC2::SecurityGroup" 166 | Source: 167 | Owner: AWS 168 | SourceIdentifier: VPC_DEFAULT_SECURITY_GROUP_CLOSED 169 | RestrictDefaultSecurityGroupRemediation: 170 | DependsOn: RestrictDefaultSecurityGroup 171 | Type: 'AWS::Config::RemediationConfiguration' 172 | Properties: 173 | ConfigRuleName: RestrictDefaultSecurityGroup 174 | ResourceType: "AWS::EC2::SecurityGroup" 175 | TargetId: "Custom-RestrictSecurityGroup" 176 | TargetType: "SSM_DOCUMENT" 177 | TargetVersion: "1" 178 | Parameters: 179 | AutomationAssumeRole: 180 | StaticValue: 181 | Values: 182 | - arn:aws:iam:::role/automationassumerole- 183 | IpAddressToBlock: 184 | StaticValue: 185 | Values: 186 | - '0.0.0.0/0' 187 | groupId: 188 | ResourceValue: 189 | Value: "RESOURCE_ID" 190 | ExecutionControls: 191 | SsmControls: 192 | ConcurrentExecutionRatePercentage: 10 193 | ErrorPercentage: 10 194 | Automatic: True 195 | MaximumAutomaticAttempts: 10 196 | RetryAttemptSeconds: 600 197 | 198 | RestrictPublicAccessLambdaEnabled: 199 | Type: "AWS::Config::ConfigRule" 200 | Properties: 201 | ConfigRuleName: RestrictPublicAccessLambdaEnabled 202 | Description: "PCI.Lambda.1 Lambda functions should prohibit public access" 203 | Scope: 204 | ComplianceResourceTypes: 205 | - "AWS::Lambda::Function" 206 | Source: 207 | Owner: AWS 208 | SourceIdentifier: LAMBDA_FUNCTION_PUBLIC_ACCESS_PROHIBITED 209 | RestrictPublicAccessLambdaRemediation: 210 | DependsOn: RestrictPublicAccessLambdaEnabled 211 | Type: 'AWS::Config::RemediationConfiguration' 212 | Properties: 213 | ConfigRuleName: RestrictPublicAccessLambdaEnabled 214 | ResourceType: "AWS::Lambda::Function" 215 | TargetId: "Custom-RestrictPublicLambda" 216 | TargetType: "SSM_DOCUMENT" 217 | TargetVersion: "1" 218 | Parameters: 219 | AutomationAssumeRole: 220 | StaticValue: 221 | Values: 222 | - arn:aws:iam:::role/automationassumerole- 223 | accountID: 224 | StaticValue: 225 | Values: 226 | - !Ref 'AWS::AccountId' 227 | functionname: 228 | ResourceValue: 229 | Value: "RESOURCE_ID" 230 | ExecutionControls: 231 | SsmControls: 232 | ConcurrentExecutionRatePercentage: 10 233 | ErrorPercentage: 10 234 | Automatic: True 235 | MaximumAutomaticAttempts: 10 236 | RetryAttemptSeconds: 600 -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/cft/aws-pci-conformancepack-v1-2.yml: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 3 | # PCI Conformance Pack with Remediations - KMS, CloudTrail, CodeBuild 4 | # 5 | # @kmmahaj 6 | # 7 | # License: 8 | # This code is made available under the MIT-0 license. See the LICENSE file. 9 | ################################################################################ 10 | AWSTemplateFormatVersion: '2010-09-09' 11 | Description: PCI Conformance Pack with Remediations - KMS, CloudTrail, CodeBuild (qs-1t0eilb5g) 12 | 13 | Resources: 14 | 15 | CMKBackingKeyRotation: 16 | Type: AWS::Config::ConfigRule 17 | Properties: 18 | ConfigRuleName: cmk-backing-key-rotation-enabled 19 | Description: >- 20 | PCI.KMS.1 – Ensure rotation for customer created CMKs is enabled 21 | Scope: 22 | ComplianceResourceTypes: 23 | - "AWS::KMS::Key" 24 | Source: 25 | Owner: AWS 26 | SourceIdentifier: CMK_BACKING_KEY_ROTATION_ENABLED 27 | MaximumExecutionFrequency: One_Hour 28 | CMKBackingKeyRotationRemediation: 29 | DependsOn: CMKBackingKeyRotation 30 | Type: 'AWS::Config::RemediationConfiguration' 31 | Properties: 32 | ConfigRuleName: cmk-backing-key-rotation-enabled 33 | ResourceType: "AWS::KMS::Key" 34 | TargetId: "Custom-CMKBackingKeyRotationCF" 35 | TargetType: "SSM_DOCUMENT" 36 | TargetVersion: "1" 37 | Parameters: 38 | AutomationAssumeRole: 39 | StaticValue: 40 | Values: 41 | - arn:aws:iam:::role/automationassumerole- 42 | KMSKeyArn: 43 | ResourceValue: 44 | Value: "RESOURCE_ID" 45 | ExecutionControls: 46 | SsmControls: 47 | ConcurrentExecutionRatePercentage: 10 48 | ErrorPercentage: 10 49 | Automatic: True 50 | MaximumAutomaticAttempts: 10 51 | RetryAttemptSeconds: 600 52 | 53 | CodeBuildProjectEnvVariableCheck: 54 | Type: AWS::Config::ConfigRule 55 | Properties: 56 | ConfigRuleName: CodeBuildProjectEnvVariableCheck 57 | Description: >- 58 | PCI.CodeBuild.2- CodeBuild project environment variables should not contain clear text credentials 59 | Scope: 60 | ComplianceResourceTypes: 61 | - "AWS::CodeBuild::Project" 62 | Source: 63 | Owner: AWS 64 | SourceIdentifier: CODEBUILD_PROJECT_ENVVAR_AWSCRED_CHECK 65 | CodeBuildProjectEnvVariableCheckRemediation: 66 | DependsOn: CodeBuildProjectEnvVariableCheck 67 | Type: 'AWS::Config::RemediationConfiguration' 68 | Properties: 69 | ConfigRuleName: CodeBuildProjectEnvVariableCheck 70 | ResourceType: "AWS::CodeBuild::Project" 71 | TargetId: "Custom-CodeBuildUpdateProject" 72 | TargetType: "SSM_DOCUMENT" 73 | TargetVersion: "1" 74 | Parameters: 75 | AutomationAssumeRole: 76 | StaticValue: 77 | Values: 78 | - arn:aws:iam:::role/automationassumerole- 79 | projectName: 80 | ResourceValue: 81 | Value: "RESOURCE_ID" 82 | ExecutionControls: 83 | SsmControls: 84 | ConcurrentExecutionRatePercentage: 10 85 | ErrorPercentage: 10 86 | Automatic: True 87 | MaximumAutomaticAttempts: 10 88 | RetryAttemptSeconds: 600 89 | 90 | CloudTrailLogFileValidationEnabled: 91 | Type: AWS::Config::ConfigRule 92 | Properties: 93 | ConfigRuleName: cloud-trail-log-file-validation-enabled 94 | Description: >- 95 | PCI.CloudTrail.3 – Ensure CloudTrail log file validation is enabled 96 | Scope: 97 | ComplianceResourceTypes: 98 | - "AWS::CloudTrail::Trail" 99 | Source: 100 | Owner: AWS 101 | SourceIdentifier: CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED 102 | MaximumExecutionFrequency: One_Hour 103 | CloudTrailLogFileValidationRemediation: 104 | DependsOn: CloudTrailLogFileValidationEnabled 105 | Type: 'AWS::Config::RemediationConfiguration' 106 | Properties: 107 | ConfigRuleName: cloud-trail-log-file-validation-enabled 108 | ResourceType: "AWS::CloudTrail::Trail" 109 | TargetId: "Custom-LogFileValidationCF" 110 | TargetType: "SSM_DOCUMENT" 111 | TargetVersion: "1" 112 | Automatic: True 113 | MaximumAutomaticAttempts: 10 114 | RetryAttemptSeconds: 600 115 | Parameters: 116 | AutomationAssumeRole: 117 | StaticValue: 118 | Values: 119 | - arn:aws:iam:::role/automationassumerole- 120 | CloudTrailLogGroupArn: 121 | StaticValue: 122 | Values: 123 | - !ImportValue CloudTrailLogGroupArn 124 | CloudWatchRoleArn: 125 | StaticValue: 126 | Values: 127 | - !ImportValue CloudWatchRoleArn 128 | TrailName: 129 | ResourceValue: 130 | Value: "RESOURCE_ID" 131 | ExecutionControls: 132 | SsmControls: 133 | ConcurrentExecutionRatePercentage: 10 134 | ErrorPercentage: 10 135 | 136 | CloudTrailCloudWatchLogsEnabled: 137 | Type: AWS::Config::ConfigRule 138 | Properties: 139 | ConfigRuleName: cloud_trail_cloud_watch_logs_enabled 140 | Description: >- 141 | PCI.CloudTrail.4 – Ensure CloudTrail trails are integrated with Amazon CloudWatch Logs 142 | Scope: 143 | ComplianceResourceTypes: 144 | - "AWS::CloudTrail::Trail" 145 | Source: 146 | Owner: AWS 147 | SourceIdentifier: CLOUD_TRAIL_CLOUD_WATCH_LOGS_ENABLED 148 | MaximumExecutionFrequency: One_Hour 149 | CloudTrailCloudWatchLogsRemediation: 150 | DependsOn: CloudTrailCloudWatchLogsEnabled 151 | Type: 'AWS::Config::RemediationConfiguration' 152 | Properties: 153 | ConfigRuleName: cloud_trail_cloud_watch_logs_enabled 154 | ResourceType: "AWS::CloudTrail::Trail" 155 | TargetId: "Custom-CloudTrailUpdateCF" 156 | TargetType: "SSM_DOCUMENT" 157 | TargetVersion: "1" 158 | Automatic: True 159 | MaximumAutomaticAttempts: 10 160 | RetryAttemptSeconds: 600 161 | Parameters: 162 | AutomationAssumeRole: 163 | StaticValue: 164 | Values: 165 | - arn:aws:iam:::role/automationassumerole- 166 | CloudTrailLogGroupArn: 167 | StaticValue: 168 | Values: 169 | - !ImportValue CloudTrailLogGroupArn 170 | CloudWatchRoleArn: 171 | StaticValue: 172 | Values: 173 | - !ImportValue CloudWatchRoleArn 174 | TrailName: 175 | ResourceValue: 176 | Value: "RESOURCE_ID" 177 | ExecutionControls: 178 | SsmControls: 179 | ConcurrentExecutionRatePercentage: 10 180 | ErrorPercentage: 10 181 | -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/cft/aws-pci-conformancepack-v1.yml: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 3 | # PCI Conformance Pack with Remediations - EC2, Autoscaling, Lambda 4 | # 5 | # @kmmahaj 6 | # 7 | # License: 8 | # This code is made available under the MIT-0 license. See the LICENSE file. 9 | ################################################################################ 10 | AWSTemplateFormatVersion: '2010-09-09' 11 | Description: PCI Conformance Pack with Remediations - EC2, Autoscaling, Lambda (qs-1t0eilb5g) 12 | 13 | Parameters: 14 | 15 | DeliveryS3Bucket: 16 | Description: Delivery Bucket from AWS Config settings 17 | Type: String 18 | Default: 'config-bucket-accountid' 19 | 20 | Resources: 21 | 22 | ConformancePack: 23 | Type: 'AWS::Config::ConformancePack' 24 | Properties: 25 | ConformancePackName: CustomPCIEC2LambdaConfPack 26 | DeliveryS3Bucket: !Ref DeliveryS3Bucket 27 | TemplateBody: |- 28 | Resources: 29 | AutoScalingELBHealthCheck: 30 | Type: AWS::Config::ConfigRule 31 | Properties: 32 | ConfigRuleName: AutoScalingELBHealthCheck 33 | Description: >- 34 | [PCI.AutoScaling.1] Auto scaling groups associated with a load balancer should use health checks 35 | Scope: 36 | ComplianceResourceTypes: 37 | - "AWS::AutoScaling::AutoScalingGroup" 38 | Source: 39 | Owner: AWS 40 | SourceIdentifier: AUTOSCALING_GROUP_ELB_HEALTHCHECK_REQUIRED 41 | AutoScalingELBHealthCheckRemediation: 42 | DependsOn: AutoScalingELBHealthCheck 43 | Type: 'AWS::Config::RemediationConfiguration' 44 | Properties: 45 | ConfigRuleName: AutoScalingELBHealthCheck 46 | ResourceType: "AWS::AutoScaling::AutoScalingGroup" 47 | TargetId: "Custom-AutoScalingELBHealthCheck" 48 | TargetType: "SSM_DOCUMENT" 49 | TargetVersion: "1" 50 | Parameters: 51 | AutomationAssumeRole: 52 | StaticValue: 53 | Values: 54 | - arn:aws:iam:::role/pciautomationassumerole- 55 | ASGGroupArn: 56 | ResourceValue: 57 | Value: "RESOURCE_ID" 58 | ExecutionControls: 59 | SsmControls: 60 | ConcurrentExecutionRatePercentage: 10 61 | ErrorPercentage: 10 62 | Automatic: True 63 | MaximumAutomaticAttempts: 10 64 | RetryAttemptSeconds: 600 65 | RemoveUnusedEC2SecurityGroups: 66 | Type: AWS::Config::ConfigRule 67 | Properties: 68 | ConfigRuleName: RemoveUnusedEC2SecurityGroups 69 | Description: >- 70 | PCI.EC2.3 – Unused EC2 Security Groups should be removed 71 | Scope: 72 | ComplianceResourceTypes: 73 | - "AWS::EC2::SecurityGroup" 74 | Source: 75 | Owner: AWS 76 | SourceIdentifier: EC2_SECURITY_GROUP_ATTACHED_TO_ENI 77 | RemoveUnusedEC2SecurityGroupsRemediation: 78 | DependsOn: RemoveUnusedEC2SecurityGroups 79 | Type: 'AWS::Config::RemediationConfiguration' 80 | Properties: 81 | ConfigRuleName: RemoveUnusedEC2SecurityGroups 82 | ResourceType: "AWS::EC2::SecurityGroup" 83 | TargetId: "Custom-RemoveSecurityGroup" 84 | TargetType: "SSM_DOCUMENT" 85 | TargetVersion: "1" 86 | Parameters: 87 | AutomationAssumeRole: 88 | StaticValue: 89 | Values: 90 | - arn:aws:iam:::role/pciautomationassumerole- 91 | groupId: 92 | ResourceValue: 93 | Value: "RESOURCE_ID" 94 | ExecutionControls: 95 | SsmControls: 96 | ConcurrentExecutionRatePercentage: 10 97 | ErrorPercentage: 10 98 | Automatic: True 99 | MaximumAutomaticAttempts: 10 100 | RetryAttemptSeconds: 600 101 | RestrictDefaultSecurityGroup: 102 | Type: AWS::Config::ConfigRule 103 | Properties: 104 | ConfigRuleName: RestrictDefaultSecurityGroup 105 | Description: >- 106 | PCI.EC2.2 VPC default security group should prohibit inbound and outbound traffic 107 | Scope: 108 | ComplianceResourceTypes: 109 | - "AWS::EC2::SecurityGroup" 110 | Source: 111 | Owner: AWS 112 | SourceIdentifier: VPC_DEFAULT_SECURITY_GROUP_CLOSED 113 | RestrictDefaultSecurityGroupRemediation: 114 | DependsOn: RestrictDefaultSecurityGroup 115 | Type: 'AWS::Config::RemediationConfiguration' 116 | Properties: 117 | ConfigRuleName: RestrictDefaultSecurityGroup 118 | ResourceType: "AWS::EC2::SecurityGroup" 119 | TargetId: "Custom-RestrictSecurityGroup" 120 | TargetType: "SSM_DOCUMENT" 121 | TargetVersion: "1" 122 | Parameters: 123 | AutomationAssumeRole: 124 | StaticValue: 125 | Values: 126 | - arn:aws:iam:::role/pciautomationassumerole- 127 | IpAddressToBlock: 128 | StaticValue: 129 | Values: 130 | - '0.0.0.0/0' 131 | groupId: 132 | ResourceValue: 133 | Value: "RESOURCE_ID" 134 | ExecutionControls: 135 | SsmControls: 136 | ConcurrentExecutionRatePercentage: 10 137 | ErrorPercentage: 10 138 | Automatic: True 139 | MaximumAutomaticAttempts: 10 140 | RetryAttemptSeconds: 600 141 | -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/cft/buildspec-reinvent.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | - echo " --Python has some SSL issues in this version so we force an upgrade which doesn't fix everything; don't be alarmed by the warnings." 6 | build: 7 | commands: 8 | - echo "S3 Upload Beginning" 9 | - python -V 10 | - export ACCID=$(aws sts get-caller-identity --query 'Account' | tr -d '"') 11 | - aws s3 sync . s3://$STAGING_BUCKET/ --delete --exclude "*" --include "*.json" --include "*.yml" --include "*.yaml" 12 | - echo "S3 Upload Complete, updating cloudformation now..." 13 | - aws cloudformation create-stack-set --stack-set-name aws-pci-conformancepack-v1 --parameters "[{\"ParameterKey\":\"DeliveryS3Bucket\",\"ParameterValue\":\"replacewithyourdeliverybucket\"}]" --template-url "https://$STAGING_BUCKET.s3.amazonaws.com/ec2-lambda/aws-pci-conformancepack-v1.yml" --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND 14 | - aws cloudformation create-stack-instances --stack-set-name aws-pci-conformancepack-v1 --accounts --regions 15 | post_build: 16 | commands: 17 | - echo "Deploy complete" 18 | -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/cft/buildspec-update-reinvent.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | - echo "Python has some SSL issues in this version so we force an upgrade which doesn't fix everything; don't be alarmed by the warnings." 6 | build: 7 | commands: 8 | - echo "S3 Upload Beginning" 9 | - python -V 10 | - export ACCID=$(aws sts get-caller-identity --query 'Account' | tr -d '"') 11 | - aws s3 sync . s3://$STAGING_BUCKET/ --delete --exclude "*" --include "*.json" --include "*.yml" --include "*.yaml" 12 | - echo "S3 Upload Complete, updating cloudformation now..." 13 | - aws cloudformation update-stack-set --stack-set-name aws-pci-conformancepack-v1 --parameters "[{\"ParameterKey\":\"DeliveryS3Bucket\",\"ParameterValue\":\"replacewithyourdeliverybucket\"}]" --template-url "https://$STAGING_BUCKET.s3.amazonaws.com/ec2-lambda/aws-pci-conformancepack-v1.yml" --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND 14 | 15 | post_build: 16 | commands: 17 | - echo "Deploy complete" 18 | -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/cft/buildspec.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | - echo "Python has some SSL issues in this version so we force an upgrade which doesn't fix everything; don't be alarmed by the warnings." 6 | build: 7 | commands: 8 | - echo "S3 Upload Beginning" 9 | - python -V 10 | - export ACCID=$(aws sts get-caller-identity --query 'Account' | tr -d '"') 11 | - aws s3 sync . s3://$STAGING_BUCKET/ --delete --exclude "*" --include "*.json" --include "*.yml" --include "*.yaml" 12 | - echo "S3 Upload Complete, updating cloudformation now..." 13 | - aws configservice put-conformance-pack --conformance-pack-name="confpack-pci-1" --template-s3-uri="s3://s3-pciautohealconfpack--/ec2-lambda/aws-pci-conformancepack-v1-1.yml" --delivery-s3-bucket="config-bucket-" 14 | - aws configservice put-conformance-pack --conformance-pack-name="confpack-pci-2" --template-s3-uri="s3://s3-pciautohealconfpack--/cloudtrail-kms-codebuild/aws-pci-conformancepack-v1-2.yml" --delivery-s3-bucket="config-bucket-" 15 | - aws configservice put-conformance-pack --conformance-pack-name="confpack-pci-3" --template-s3-uri="s3://s3-pciautohealconfpack--/redshift-rds-iam/aws-pci-conformancepack-v1-3.yml" --delivery-s3-bucket="config-bucket-" 16 | post_build: 17 | commands: 18 | - echo "Deploy complete" -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/coverage/AWS PCI Conformance Packs Auto Healing Coverage.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-devsecops-conformancepack-pci/coverage/AWS PCI Conformance Packs Auto Healing Coverage.xlsx -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/images/arch-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-devsecops-conformancepack-pci/images/arch-diagram.png -------------------------------------------------------------------------------- /aws-devsecops-conformancepack-pci/images/ccoe-devsecopscompliance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-devsecops-conformancepack-pci/images/ccoe-devsecopscompliance.png -------------------------------------------------------------------------------- /aws-enable-config/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Enable Config and Config Rules across accounts or regions 5 | 6 | ## Option 1: Enable Config in an AWS Organization 7 | 8 | 1. In the CloudFormation console, choose StackSets. On the Create StackSets page, select the option to 'Use a sample template' and select the 'Enable AWS Config' template. Since you are using AWS Organizations use service managed permissions to deploy this template 9 | 10 | ## Option 2: Enable Config in multiple accounts or regions ( not using AWS Organizations) 11 | 12 | 1. Deploy Stackset pre-requisites to enable self service permissions - Launch the AWSCloudFormationStackSetAdministrationRole.yaml template in the account where the stackset will be provisioned. Launch the AWSCloudFormationStackSetExecutionRole.yaml in each of the accounts where stack instances based on the stackset will be provisioned 13 | 14 | 2. In the CloudFormation console of the account where the AWSCloudFormationStackSetAdministrationRole.yaml was provisioned , choose StackSets. On the Create StackSets page, select the option to 'Use a sample template' and select the 'Enable AWS Config' template. Select 'self service permissions' and provide the names of the AWSCloudFormationStackSetAdministration role and AWSCloudFormationStackSetExecution role. 15 | 16 | 17 | # Enable Managed Config Rules 18 | 19 | ## Option 1: Enable Config Rule in an AWS Organization - Sample 20 | 21 | 1. Launch the sample 'OrgEnableConfigRule.yml' template from the management account of your AWS Organization. Provide the AWS Config Managed Rule identifier as a parameter. Modify this snippet for deploying other Config managed rules 22 | 23 | ## Option 2: Enable Config Rule in multiple accounts or regions (not using AWS Organizations) - Sample 24 | 25 | 1. Deploy Stackset pre-requisites to enable self service permissions - Launch the AWSCloudFormationStackSetAdministrationRole.yaml template in the account where the stackset will be provisioned. Launch the AWSCloudFormationStackSetExecutionRole.yaml in each of the accounts where stack instances based on the stackset will be provisioned 26 | 27 | 2. In the CloudFormation console of the account where the AWSCloudFormationStackSetAdministrationRole.yaml was provisioned , choose StackSets. On the Create StackSets page, select the option to 'Use a sample template' and select the 'cloudtrail-enabled' template. Select 'self service permissions' and provide the names of the AWSCloudFormationStackSetAdministration role and AWSCloudFormationStackSetExecution role. -------------------------------------------------------------------------------- /aws-enable-config/cft/AWSCloudFormationStackSetAdministrationRole.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Configure the AWSCloudFormationStackSetAdministrationRole to enable use of AWS CloudFormation StackSets. (qs-1t0eilb5g) 3 | 4 | Resources: 5 | AdministrationRole: 6 | Type: AWS::IAM::Role 7 | Properties: 8 | RoleName: AWSCloudFormationStackSetAdministrationRole 9 | AssumeRolePolicyDocument: 10 | Version: 2012-10-17 11 | Statement: 12 | - Effect: Allow 13 | Principal: 14 | Service: cloudformation.amazonaws.com 15 | Action: 16 | - sts:AssumeRole 17 | Path: / 18 | Policies: 19 | - PolicyName: AssumeRole-AWSCloudFormationStackSetExecutionRole 20 | PolicyDocument: 21 | Version: 2012-10-17 22 | Statement: 23 | - Effect: Allow 24 | Action: 25 | - sts:AssumeRole 26 | Resource: 27 | - "arn:*:iam::*:role/AWSCloudFormationStackSetExecutionRole" 28 | -------------------------------------------------------------------------------- /aws-enable-config/cft/AWSCloudFormationStackSetExecutionRole.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Configure the AWSCloudFormationStackSetExecutionRole to enable use of your account as a target account in AWS CloudFormation StackSets (qs-1t0eilb5g). 3 | 4 | Parameters: 5 | AdministratorAccountId: 6 | Type: String 7 | Description: AWS Account Id of the administrator account (the account in which StackSets will be created). 8 | MaxLength: 12 9 | MinLength: 12 10 | 11 | Resources: 12 | ExecutionRole: 13 | Type: AWS::IAM::Role 14 | Properties: 15 | RoleName: AWSCloudFormationStackSetExecutionRole 16 | AssumeRolePolicyDocument: 17 | Version: 2012-10-17 18 | Statement: 19 | - Effect: Allow 20 | Principal: 21 | AWS: 22 | - !Ref AdministratorAccountId 23 | Action: 24 | - sts:AssumeRole 25 | Path: / 26 | ManagedPolicyArns: 27 | - !Sub arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess 28 | -------------------------------------------------------------------------------- /aws-enable-config/cft/EnableAWSConfig.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Enable AWS Config (qs-1t0eilb5g) 3 | 4 | Metadata: 5 | AWS::CloudFormation::Interface: 6 | ParameterGroups: 7 | - Label: 8 | default: Recorder Configuration 9 | Parameters: 10 | - AllSupported 11 | - IncludeGlobalResourceTypes 12 | - ResourceTypes 13 | - Label: 14 | default: Delivery Channel Configuration 15 | Parameters: 16 | - DeliveryChannelName 17 | - Frequency 18 | - Label: 19 | default: Delivery Notifications 20 | Parameters: 21 | - TopicArn 22 | - NotificationEmail 23 | ParameterLabels: 24 | AllSupported: 25 | default: Support all resource types 26 | IncludeGlobalResourceTypes: 27 | default: Include global resource types 28 | ResourceTypes: 29 | default: List of resource types if not all supported 30 | DeliveryChannelName: 31 | default: Configuration delivery channel name 32 | Frequency: 33 | default: Snapshot delivery frequency 34 | TopicArn: 35 | default: SNS topic name 36 | NotificationEmail: 37 | default: Notification Email (optional) 38 | 39 | Parameters: 40 | AllSupported: 41 | Type: String 42 | Default: True 43 | Description: Indicates whether to record all supported resource types. 44 | AllowedValues: 45 | - True 46 | - False 47 | 48 | IncludeGlobalResourceTypes: 49 | Type: String 50 | Default: True 51 | Description: Indicates whether AWS Config records all supported global resource types. 52 | AllowedValues: 53 | - True 54 | - False 55 | 56 | ResourceTypes: 57 | Type: List 58 | Description: A list of valid AWS resource types to include in this recording group, such as AWS::EC2::Instance or AWS::CloudTrail::Trail. 59 | Default: 60 | 61 | DeliveryChannelName: 62 | Type: String 63 | Default: 64 | Description: The name of the delivery channel. 65 | 66 | Frequency: 67 | Type: String 68 | Default: 24hours 69 | Description: The frequency with which AWS Config delivers configuration snapshots. 70 | AllowedValues: 71 | - 1hour 72 | - 3hours 73 | - 6hours 74 | - 12hours 75 | - 24hours 76 | 77 | TopicArn: 78 | Type: String 79 | Default: 80 | Description: The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (Amazon SNS) topic that AWS Config delivers notifications to. 81 | 82 | NotificationEmail: 83 | Type: String 84 | Default: 85 | Description: Email address for AWS Config notifications (for new topics). 86 | 87 | Conditions: 88 | IsAllSupported: !Equals 89 | - !Ref AllSupported 90 | - True 91 | IsGeneratedDeliveryChannelName: !Equals 92 | - !Ref DeliveryChannelName 93 | - 94 | CreateTopic: !Equals 95 | - !Ref TopicArn 96 | - 97 | CreateSubscription: !And 98 | - !Condition CreateTopic 99 | - !Not 100 | - !Equals 101 | - !Ref NotificationEmail 102 | - 103 | 104 | Mappings: 105 | Settings: 106 | FrequencyMap: 107 | 1hour : One_Hour 108 | 3hours : Three_Hours 109 | 6hours : Six_Hours 110 | 12hours : Twelve_Hours 111 | 24hours : TwentyFour_Hours 112 | 113 | Resources: 114 | 115 | ConfigBucket: 116 | DeletionPolicy: Retain 117 | Type: AWS::S3::Bucket 118 | Properties: 119 | BucketName: !Sub "s3-configbucket-${AWS::AccountId}-${AWS::Region}" 120 | BucketEncryption: 121 | ServerSideEncryptionConfiguration: 122 | - ServerSideEncryptionByDefault: 123 | SSEAlgorithm: AES256 124 | 125 | 126 | ConfigBucketPolicy: 127 | Type: AWS::S3::BucketPolicy 128 | Properties: 129 | Bucket: !Ref ConfigBucket 130 | PolicyDocument: 131 | Version: 2012-10-17 132 | Statement: 133 | - Sid: AWSConfigBucketPermissionsCheck 134 | Effect: Allow 135 | Principal: 136 | Service: 137 | - config.amazonaws.com 138 | Action: s3:GetBucketAcl 139 | Resource: 140 | - !Sub "arn:${AWS::Partition}:s3:::${ConfigBucket}" 141 | - Sid: DisallowHTTP 142 | Effect: Deny 143 | Principal: '*' 144 | Action: 's3:*' 145 | Resource: 146 | - !Sub "arn:aws:s3:::${ConfigBucket}" 147 | Condition: 148 | Bool: 149 | 'aws:SecureTransport': false 150 | - Sid: AWSConfigBucketDelivery 151 | Effect: Allow 152 | Principal: 153 | Service: 154 | - config.amazonaws.com 155 | Action: s3:PutObject 156 | Resource: 157 | - !Sub "arn:${AWS::Partition}:s3:::${ConfigBucket}/AWSLogs/${AWS::AccountId}/*" 158 | 159 | ConfigTopic: 160 | Condition: CreateTopic 161 | Type: AWS::SNS::Topic 162 | Properties: 163 | TopicName: !Sub "config-topic-${AWS::AccountId}" 164 | DisplayName: AWS Config Notification Topic 165 | 166 | ConfigTopicPolicy: 167 | Condition: CreateTopic 168 | Type: AWS::SNS::TopicPolicy 169 | Properties: 170 | Topics: 171 | - !Ref ConfigTopic 172 | PolicyDocument: 173 | Statement: 174 | - Sid: AWSConfigSNSPolicy 175 | Action: 176 | - sns:Publish 177 | Effect: Allow 178 | Resource: !Ref ConfigTopic 179 | Principal: 180 | Service: 181 | - config.amazonaws.com 182 | 183 | EmailNotification: 184 | Condition: CreateSubscription 185 | Type: AWS::SNS::Subscription 186 | Properties: 187 | Endpoint: !Ref NotificationEmail 188 | Protocol: email 189 | TopicArn: !Ref ConfigTopic 190 | 191 | ConfigRecorderRole: 192 | Type: AWS::IAM::Role 193 | Properties: 194 | AssumeRolePolicyDocument: 195 | Version: 2012-10-17 196 | Statement: 197 | - Effect: Allow 198 | Principal: 199 | Service: 200 | - config.amazonaws.com 201 | Action: 202 | - sts:AssumeRole 203 | Path: / 204 | ManagedPolicyArns: 205 | - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWS_ConfigRole" 206 | 207 | ConfigRecorder: 208 | Type: AWS::Config::ConfigurationRecorder 209 | DependsOn: 210 | - ConfigBucketPolicy 211 | Properties: 212 | RoleARN: !GetAtt ConfigRecorderRole.Arn 213 | RecordingGroup: 214 | AllSupported: !Ref AllSupported 215 | IncludeGlobalResourceTypes: !Ref IncludeGlobalResourceTypes 216 | ResourceTypes: !If 217 | - IsAllSupported 218 | - !Ref AWS::NoValue 219 | - !Ref ResourceTypes 220 | 221 | ConfigDeliveryChannel: 222 | Type: AWS::Config::DeliveryChannel 223 | DependsOn: 224 | - ConfigBucketPolicy 225 | Properties: 226 | Name: !If 227 | - IsGeneratedDeliveryChannelName 228 | - !Ref AWS::NoValue 229 | - !Ref DeliveryChannelName 230 | ConfigSnapshotDeliveryProperties: 231 | DeliveryFrequency: !FindInMap 232 | - Settings 233 | - FrequencyMap 234 | - !Ref Frequency 235 | S3BucketName: !Ref ConfigBucket 236 | SnsTopicARN: !If 237 | - CreateTopic 238 | - !Ref ConfigTopic 239 | - !Ref TopicArn 240 | -------------------------------------------------------------------------------- /aws-enable-config/cft/OrgEnableAWSConfigRule.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Enable AWS Config Managed Rule (qs-1t0eilb5g) 3 | 4 | Parameters: 5 | OrganizationConfigRuleName: 6 | Type: String 7 | Default: 'EnableCloudTrail' 8 | Description: Config Rule Name for CLOUD_TRAIL_ENABLED rule identifier 9 | 10 | 11 | Resources: 12 | EnableOrganizationConfigRule: 13 | Type: "AWS::Config::OrganizationConfigRule" 14 | Properties: 15 | OrganizationConfigRuleName: !Ref OrganizationConfigRuleName 16 | OrganizationManagedRuleMetadata: 17 | RuleIdentifier: "CLOUD_TRAIL_ENABLED" 18 | Description: "Cloudtrail enabled rule" 19 | 20 | 21 | -------------------------------------------------------------------------------- /aws-enable-config/images/config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-enable-config/images/config.png -------------------------------------------------------------------------------- /aws-org-conformancepack/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Deploy custom AWS Config Conformance Packs in an AWS Organization 5 | 6 | 7 | ## 0 - Prerequsites 8 | 1. Ensure AWS Config is enabled in each account 9 | 2. Ensure an IAM role (service linked role) is provisioned in each account 10 | 3. Ensure that there is s3 bucket that allows read/write from the IAM role in each account 11 | 4. Recommended – Register delegated administrator account 12 | 13 | 14 | ## 1 - Deploy custom Config Conformance Pack 15 | 16 | 1. Launch the sample 'OrgEnableConformancePack.yml' template from the management account of your AWS Organization. The template takes the 'TemplateS3Uri' as a parameter which is the S3 template URI that hosts the conformance pack template. You can upload the sample 'org-confpack-pci' conformance pack template to S3 and test an organizational deployment of that conformance pack. Upload other conformance pack templates to S3 and use this template as a sample to deploy organization conformance packs. 17 | 18 | 19 | ## 2- Deploy custom Config Conformance Pack with remediations in an AWS Organization 20 | 21 | 1. Deploy Stackset pre-requisites to enable self service permissions - Launch the AWSCloudFormationStackSetAdministrationRole.yaml template in the account where the stackset will be provisioned. Launch the AWSCloudFormationStackSetExecutionRole.yaml in each of the accounts where stack instances based on the stackset will be provisioned 22 | 23 | 2. In the CloudFormation console of the account where the AWSCloudFormationStackSetAdministrationRole.yaml was provisioned , choose StackSets. On the Create StackSets page, select the option to 'Upload a template file' and select the 'org-confpack-pci' sample conformance pack template. Select 'self service permissions' and provide the names of the AWSCloudFormationStackSetAdministration rol sample and AWSCloudFormationStackSetExecution role. Modify this snippet for deploying other conformance Pack templates. -------------------------------------------------------------------------------- /aws-org-conformancepack/cft/AccountEnableConformancePack.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: This template automatically deploy the AWS Config Conformance Pack for Operational Best Practices for AWS Identity And Access Management. Please note resource charges for S3 buckets, Config and Conformance pack will apply. (qs-1t0eilb5g) 3 | Parameters: 4 | ConformancePackDeliveryBucket: 5 | Type: String 6 | Description: AWS Config stores intermediate files while processing conformance pack template. Please enter thename of the bucket that has been configured already for conformance pack to deliver to deliver findings. 7 | MaxAgeAccessKeyRotated: 8 | Type: String 9 | Description: This is a parameter for the conformance pack. Enter the IAM Access Key Maximum number of days without rotation. Default 90 10 | Default: '90' 11 | BlackListedIAMPolicyARN: 12 | Type: String 13 | Default: 'arn:aws:iam::aws:policy/PowerUserAccess' 14 | Description: >- 15 | This is a parameter for the conformance pack. Enter a Comma-separated list of IAM policy ARNs that should not be attached to any 16 | IAM entity. We provide as the PowerUserAccess for sample purposes only. Feel free to enter asnother policy ARN 17 | IAMUserUnusedCredentialAge: 18 | Type: String 19 | Description: >- 20 | This is a parameter for the conformance pack. Maximum number of days a credential cannot be used. The default value is 21 | 90 days. 22 | Default: '90' 23 | Resources: 24 | ConformancePack: 25 | Type: 'AWS::Config::ConformancePack' 26 | Properties: 27 | ConformancePackName: IAMBestPractices 28 | ConformancePackInputParameters: 29 | - 30 | ParameterName: AccessKeysRotatedParameterMaxAccessKeyAge 31 | ParameterValue: !Ref MaxAgeAccessKeyRotated 32 | - 33 | ParameterName: IAMPolicyBlacklistedCheckParameterPolicyArns 34 | ParameterValue: !Ref BlackListedIAMPolicyARN 35 | - 36 | ParameterName: IAMUserUnusedCredentialsCheckParameterMaxCredentialUsageAge 37 | ParameterValue: !Ref IAMUserUnusedCredentialAge 38 | DeliveryS3Bucket: !Ref ConformancePackDeliveryBucket 39 | TemplateBody: |- 40 | Parameters: 41 | AccessKeysRotatedParameterMaxAccessKeyAge: 42 | Description: Maximum number of days without rotation. Default 90. 43 | Type: String 44 | IAMPolicyBlacklistedCheckParameterPolicyArns: 45 | Description: Comma-separated list of IAM policy ARNs that should not be attached to any IAM entity. 46 | Type: String 47 | IAMUserUnusedCredentialsCheckParameterMaxCredentialUsageAge: 48 | Description: Maximum number of days a credential cannot be used. The default value 49 | is 90 days. 50 | Type: String 51 | Resources: 52 | AccessKeysRotated: 53 | Properties: 54 | ConfigRuleName: AccessKeysRotated 55 | Description: Checks whether the active access keys are rotated within the number 56 | of days specified in maxAccessKeyAge. The rule is non-compliant if the access 57 | keys have not been rotated for more than maxAccessKeyAge number of days. 58 | InputParameters: 59 | maxAccessKeyAge: 60 | Ref: AccessKeysRotatedParameterMaxAccessKeyAge 61 | Source: 62 | Owner: AWS 63 | SourceIdentifier: ACCESS_KEYS_ROTATED 64 | Type: AWS::Config::ConfigRule 65 | IAMGroupHasUsersCheck: 66 | Properties: 67 | ConfigRuleName: IAMGroupHasUsersCheck 68 | Description: Checks whether IAM groups have at least one IAM user. 69 | Source: 70 | Owner: AWS 71 | SourceIdentifier: IAM_GROUP_HAS_USERS_CHECK 72 | Type: AWS::Config::ConfigRule 73 | IAMPasswordPolicy: 74 | Properties: 75 | ConfigRuleName: IAMPasswordPolicy 76 | Description: Checks whether the account password policy for IAM users meets 77 | the specified requirements. 78 | Source: 79 | Owner: AWS 80 | SourceIdentifier: IAM_PASSWORD_POLICY 81 | Type: AWS::Config::ConfigRule 82 | IAMPolicyBlacklistedCheck: 83 | Properties: 84 | ConfigRuleName: IAMPolicyBlacklistedCheck 85 | Description: Checks that none of your IAM users, groups, or roles (excluding 86 | exceptionList) have the specified policies attached. 87 | InputParameters: 88 | policyArns: 89 | Ref: IAMPolicyBlacklistedCheckParameterPolicyArns 90 | Source: 91 | Owner: AWS 92 | SourceIdentifier: IAM_POLICY_BLACKLISTED_CHECK 93 | Type: AWS::Config::ConfigRule 94 | IAMPolicyNoStatementsWithAdminAccess: 95 | Properties: 96 | ConfigRuleName: IAMPolicyNoStatementsWithAdminAccess 97 | Source: 98 | Owner: AWS 99 | SourceIdentifier: IAM_POLICY_NO_STATEMENTS_WITH_ADMIN_ACCESS 100 | Type: AWS::Config::ConfigRule 101 | IAMRootAccessKeyCheck: 102 | Properties: 103 | ConfigRuleName: IAMRootAccessKeyCheck 104 | Description: Checks whether the root user access key is available. The rule 105 | is compliant if the user access key does not exist. 106 | Source: 107 | Owner: AWS 108 | SourceIdentifier: IAM_ROOT_ACCESS_KEY_CHECK 109 | Type: AWS::Config::ConfigRule 110 | IAMUserGroupMembershipCheck: 111 | Properties: 112 | ConfigRuleName: IAMUserGroupMembershipCheck 113 | Description: Checks whether IAM users are members of at least one IAM group. 114 | Source: 115 | Owner: AWS 116 | SourceIdentifier: IAM_USER_GROUP_MEMBERSHIP_CHECK 117 | Type: AWS::Config::ConfigRule 118 | IAMUserMFAEnabled: 119 | Properties: 120 | ConfigRuleName: IAMUserMFAEnabled 121 | Description: Checks whether the AWS Identity and Access Management users have 122 | multi-factor authentication (MFA) enabled. 123 | Source: 124 | Owner: AWS 125 | SourceIdentifier: IAM_USER_MFA_ENABLED 126 | Type: AWS::Config::ConfigRule 127 | IAMUserNoPoliciesCheck: 128 | Properties: 129 | ConfigRuleName: IAMUserNoPoliciesCheck 130 | Description: Checks that none of your IAM users have policies attached. IAM 131 | users must inherit permissions from IAM groups or roles. 132 | Source: 133 | Owner: AWS 134 | SourceIdentifier: IAM_USER_NO_POLICIES_CHECK 135 | Type: AWS::Config::ConfigRule 136 | IAMUserUnusedCredentialsCheck: 137 | Properties: 138 | ConfigRuleName: IAMUserUnusedCredentialsCheck 139 | Description: Checks whether your AWS Identity and Access Management (IAM) users 140 | have passwords or active access keys that have not been used within the specified 141 | number of days you provided. 142 | InputParameters: 143 | maxCredentialUsageAge: 144 | Ref: IAMUserUnusedCredentialsCheckParameterMaxCredentialUsageAge 145 | Source: 146 | Owner: AWS 147 | SourceIdentifier: IAM_USER_UNUSED_CREDENTIALS_CHECK 148 | Type: AWS::Config::ConfigRule 149 | MFAEnabledForIAMConsoleAccess: 150 | Properties: 151 | ConfigRuleName: MFAEnabledForIAMConsoleAccess 152 | Description: Checks whether AWS Multi-Factor Authentication (MFA) is enabled 153 | for all AWS Identity and Access Management (IAM) users that use a console 154 | password. The rule is compliant if MFA is enabled. 155 | Source: 156 | Owner: AWS 157 | SourceIdentifier: MFA_ENABLED_FOR_IAM_CONSOLE_ACCESS 158 | Type: AWS::Config::ConfigRule 159 | RootAccountHardwareMFAEnabled: 160 | Properties: 161 | ConfigRuleName: RootAccountHardwareMFAEnabled 162 | Description: Checks whether your AWS account is enabled to use a multi-factor 163 | authentication (MFA) hardware device to sign in with root credentials. 164 | Source: 165 | Owner: AWS 166 | SourceIdentifier: ROOT_ACCOUNT_HARDWARE_MFA_ENABLED 167 | Type: AWS::Config::ConfigRule 168 | RootAccountMFAEnabled: 169 | Properties: 170 | ConfigRuleName: RootAccountMFAEnabled 171 | Description: Checks whether the root user of your AWS account requires multi-factor 172 | authentication for console sign-in. 173 | Source: 174 | Owner: AWS 175 | SourceIdentifier: ROOT_ACCOUNT_MFA_ENABLED 176 | Type: AWS::Config::ConfigRule -------------------------------------------------------------------------------- /aws-org-conformancepack/cft/OrgEnableConformancePack.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Deploy AWS Config Conformance Pack in an AWS Organization (qs-1t0eilb5g) 3 | 4 | Parameters: 5 | 6 | OrganizationConformancePackName: 7 | Type: String 8 | Default: 'PCIDSSConformancePack' 9 | Description: Name of the Conformance Pack to be deployed in an AWS Organization 10 | 11 | TemplateS3Uri: 12 | Type: String 13 | Default: 's3://bucketname/prefix' 14 | Description: s3 template uri that hosts the conformance pack template 15 | 16 | 17 | Resources: 18 | EnableOrganizationConfigRule: 19 | Type: AWS::Config::OrganizationConformancePack 20 | Properties: 21 | OrganizationConformancePackName: !Ref OrganizationConformancePackName 22 | TemplateS3Uri: !Ref TemplateS3Uri 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /aws-org-custom-conformancepacks/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Automate Cloud Foundations for Compliance in AWS 5 | 6 | 7 | 8 | ## Overview 9 | 10 | 1. Automated deployment of a custom AWS Config Conformance Pack in an AWS Organization. 11 | 2. Automated deployment of AWS Systems Manager remediation runbooks in an AWS Organization. 12 | 3. Add code for SSM remediations to a custom AWS Config Conformance Pack 13 | 4. Automated deployment of a custom AWS Config Conformance Pack with remediations in an AWS Organization. 14 | 15 | Demonstrates deployment of a custom Config conformance pack with remediations for these PCI controls: 16 | 17 | ``` 18 | * [PCI.AutoScaling.1] Auto scaling groups associated with a load balancer should use health checks 19 | * [PCI.CloudTrail.3] CloudTrail log file validation should be enabled 20 | * [PCI.CloudTrail.4] CloudTrail trails should be integrated with CloudWatch Logs 21 | * [PCI.CodeBuild.2] CodeBuild project environment variables should not contain clear text credentials 22 | * [PCI.EC2.2] VPC default security group should prohibit inbound and outbound traffic 23 | * [PCI.EC2.3] Unused EC2 security groups should be removed 24 | * [PCI.EC2.4] Unused EC2 EIPs should be removed 25 | * [PCI EC2.5] Security groups should not allow ingress from 0.0.0.0/0 to port 22 26 | * [PCI.IAM.3] IAM policies should not allow full * administrative privileges 27 | * [PCI.KMS.1] Customer master key (CMK) rotation should be enabled 28 | * [PCI.Lambda.1] Lambda functions should prohibit public access 29 | * [PCI.RDS.1] RDS snapshots should prohibit public access 30 | * [PCI.RDS.2] RDS DB Instances should prohibit public access 31 | * [PCI.Redshift.1] Amazon Redshift clusters should prohibit public access 32 | * [PCI.S3.1] S3 buckets should prohibit public write access 33 | * [PCI.S3.2] S3 buckets should prohibit public read access 34 | ``` 35 | 36 | 37 | ## 0 - Prerequsites 38 | 1. Complete the setup in [aws-org-enable-cca](https://github.com/aws-samples/aws-cloud-compliance-assurance/tree/main/aws-org-enable-cca) 39 | 2. From your **management account**, launch the [**aws-pci-confpack-ssmautomation-v1.yml**](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-org-custom-conformancepacks/cft/aws-pci-confpack-ssmautomation-v1.yml) as a CloudFormation stackset. [Use service-managed permissions to deploy this template automatically throughout your AWS Organization using CloudFormation stacksets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-getting-started-create.html#stacksets-orgs-associate-stackset-with-org). 40 | 41 | 42 | ## 1 - Deploy custom Config Conformance Pack in an AWS Organization 43 | 44 | 1. In your **delegated administrator** account, create an S3 bucket. Upload the [**aws-pci-conformancepack-v1.yml**](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-org-custom-conformancepacks/cft/aws-pci-conformancepack-v1.yml) custom conformance pack template that you want to deploy in your AWS Organization. You will use the S3 URI that contains this template as the TemplateS3Uri parameter in the next step. 45 | 2. Launch the [**aws-pci-customconfpack-org.yml**](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-org-custom-conformancepacks/cft/aws-pci-custom-confpack-org.yml) template from your **delegated administrator** account. This template automates org wide deployment of custom conformance packs. Provide the following parameters: 46 | - **DeliveryS3Bucket**: The name of the Amazon S3 bucket where AWS Config stores artifacts for org wide deployment of conformance pack templates. Obtain this value from the Org Conformance Pack pre-requisites that you completed. 47 | - **OrganizationConformancePackName**: Name of the custom config conformance pack 48 | - **TemplateS3Uri**: S3 URI that points to the location in S3 of the custom conformance pack template that you want to deploy in your AWS Organization. 49 | 50 | ## 2- Deploy custom Config Conformance Pack with remediations in an AWS Organization 51 | 52 | 1. Replace the **accountID** used for all the **AutomationAssumeRole** parameters within the [**aws-pci-conformancepack-remediations-v1.yml**](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-org-custom-conformancepacks/cft/aws-pci-conformancepack-remediations-v1.yml) custom Config Conformance Pack with SSM remediations template with the AWS AccountID of your **delegated administrator** account. 53 | 2. Upload the modified [**aws-pci-conformancepack-remediations-v1.yml**](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-org-custom-conformancepacks/cft/aws-pci-conformancepack-remediations-v1.yml) custom Config Conformance Pack with SSM remediations template to an S3 bucket in your **delegated administrator** account. You will use the S3 URI that contains this template as the TemplateS3Uri parameter in the next step. 54 | 3. Launch the [**aws-pci-customconfpack-org.yml**](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-org-custom-conformancepacks/cft/aws-pci-custom-confpack-org.yml) template from your **delegated administrator** account. This template automates org wide deployment of custom conformance packs. Provide the following parameters: 55 | - **DeliveryS3Bucket**: The name of the Amazon S3 bucket where AWS Config stores artifacts for org wide deployment of conformance pack templates. Obtain this value from the Org Conformance Pack pre-requisites that you completed. 56 | - **OrganizationConformancePackName**: Name of the custom config conformance pack with remediations 57 | - **TemplateS3Uri**: S3 URI that points to the location in S3 of the custom conformance pack template with remediations that you want to deploy in your AWS Organization. 58 | 59 | 60 | -------------------------------------------------------------------------------- /aws-org-custom-conformancepacks/cft/aws-pci-custom-confpack-org.yml: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 3 | # Provisions Org Custom Conformance Packs 4 | # 5 | # @kmmahaj 6 | # 7 | # License: 8 | # This code is made available under the MIT-0 license. See the LICENSE file. 9 | ################################################################################ 10 | AWSTemplateFormatVersion: 2010-09-09 11 | Description: Provisions Org Custom Conformance Packs(qs-1t0eilb5g) 12 | 13 | Parameters: 14 | 15 | DeliveryS3Bucket: 16 | Description: The name of the Amazon S3 bucket where AWS Config stores conformance pack templates. 17 | Type: String 18 | Default: 'awsconfigconforms-orgbucket' 19 | 20 | OrganizationConformancePackName: 21 | Description: Name of the custom config conformance pack 22 | Type: String 23 | Default: 'aws-pcicustomconfpack-remediations-org' 24 | 25 | TemplateS3Uri: 26 | Description: Location of S3 file containing the conformance pack template body. Points to the conformance pack template 27 | Type: String 28 | Default: 's3://s3-pci-confpack-org/aws-pci-conformancepack-remediations-v1.yml' 29 | 30 | Resources: 31 | 32 | OrganizationConformancePack: 33 | Type: 'AWS::Config::OrganizationConformancePack' 34 | Properties: 35 | OrganizationConformancePackName: !Ref OrganizationConformancePackName 36 | DeliveryS3Bucket: !Ref DeliveryS3Bucket 37 | ExcludedAccounts: 38 | - "798653331051" 39 | - "652691327122" 40 | - "227214716926" 41 | - "018299706242" 42 | - "525354019754" 43 | - "602116679243" 44 | - "187355837323" 45 | - "341476298946" 46 | - "221809298128" 47 | - "388407216922" 48 | TemplateS3Uri: !Ref TemplateS3Uri 49 | -------------------------------------------------------------------------------- /aws-org-custom-conformancepacks/cft/s3bucketpolicy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Principal": "*", 7 | "Action": [ 8 | "s3:GetObject", 9 | "s3:PutObject", 10 | "s3:DeleteObject" 11 | ], 12 | "Resource": "arn:aws:s3:::awsconfigconforms-orgbucket/*", 13 | "Condition": { 14 | "StringEquals": { 15 | "aws:PrincipalOrgID": "o-s9coreqj0c" 16 | } 17 | } 18 | }, 19 | { 20 | "Effect": "Allow", 21 | "Principal": "*", 22 | "Action": [ 23 | "s3:GetBucketAcl", 24 | "s3:ListBucket", 25 | "s3:GetBucketPolicy" 26 | ], 27 | "Resource": "arn:aws:s3:::awsconfigconforms-orgbucket", 28 | "Condition": { 29 | "StringEquals": { 30 | "aws:PrincipalOrgID": "o-s9coreqj0c" 31 | } 32 | } 33 | } 34 | ] 35 | } -------------------------------------------------------------------------------- /aws-org-enable-cca/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Setup configuration compliance in an AWS Organization 5 | 6 | ## Overview 7 | 8 | Demonstrates steps required to operationalize configuration compliance in AWS across an AWS Organization 9 | 10 | 11 | ## Step 1 - Enable Config in an AWS Organization 12 | 13 | **Option 1 - Use CloudFormation Stacksets** - In the CloudFormation console, choose StackSets. On the Create StackSets page, select the option to 'Use a sample template' and select the 'Enable AWS Config' template. Since you are using AWS Organizations [use service-managed permissions to deploy this template as a stackset](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-getting-started-create.html#stacksets-orgs-associate-stackset-with-org) 14 | 15 | **Option 2 - Use Systems Manager Quick Setup** - With [Quick Setup](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-quick-setup.html), a capability of AWS Systems Manager, you can quickly create a configuration recorder powered by AWS Config across your organization. Follow the [steps outlined in SSM Quick Setup](https://docs.aws.amazon.com/systems-manager/latest/userguide/quick-setup-config.html) to set up AWS Config recording with AWS Systems Manager Quick Setup in an AWS Organization 16 | 17 | ## Step 2 - Register a delegated administrator account for AWS Config 18 | 19 | From the **management account** of your AWS Organization, run the **register-delegated-administrator** command. In the following AWS CLI command, replace *delegated account id* with the delegated administrator account ID: 20 | 21 | ``` 22 | $ aws register-delegated-administrator --service-principal config.amazonaws.com\ 23 | --account-id [delegated account id] 24 | ``` 25 | 26 | ## Step 3 - Setup S3 Delivery bucket in the delegated administrator account for Conformance Pack artifacts 27 | 28 | For AWS Config to be able to store conformance pack artifacts, you will need to provide an Amazon S3 bucket in the **delegated administrator** account. This bucket name must start with the prefix **“awsconfigconforms”**. Each account in the organization must have access to this bucket. 29 | 30 | AWS Config recommends having limited permissions to the Amazon S3 bucket policy. To limit access, you can use following policy which uses **PrincipalOrgID** and **PrincipalArn** conditions in the Amazon S3 policy. This allows only accounts in an organization to have access to the bucket. You can find your organization id from the AWS Organizations console under the Settings tab. 31 | 32 | ``` 33 | { 34 | "Version": "2012-10-17", 35 | "Statement": [ 36 | { 37 | "Sid": "AllowGetPutObject", 38 | "Effect": "Allow", 39 | "Principal": "*", 40 | "Action": [ 41 | "s3:GetObject", 42 | "s3:PutObject" 43 | ], 44 | "Resource": "arn:aws:s3:::awsconfigconforms/*", 45 | "Condition": { 46 | "StringEquals": { 47 | "aws:PrincipalOrgID": "customer_org_id" 48 | }, 49 | "ArnLike": { 50 | "aws:PrincipalArn": "arn:aws:iam::*:role/aws-service-role/config-conforms.amazonaws.com/AWSServiceRoleForConfigConforms" 51 | } 52 | } 53 | }, 54 | { 55 | "Sid": "AllowGetBucketAcl", 56 | "Effect": "Allow", 57 | "Principal": "*", 58 | "Action": "s3:GetBucketAcl", 59 | "Resource": "arn:aws:s3:::awsconfigconforms", 60 | "Condition": { 61 | "StringEquals": { 62 | "aws:PrincipalOrgID": "customer_org_id" 63 | }, 64 | "ArnLike": { 65 | "aws:PrincipalArn": "arn:aws:iam::*:role/aws-service-role/config-conforms.amazonaws.com/AWSServiceRoleForConfigConforms" 66 | } 67 | } 68 | } 69 | ] 70 | } 71 | 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /aws-remediate-cis-securityhub/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Automated Remediations for CIS Benchmarks using AWS Security Hub 5 | 6 | The solution implemented here leverages the AWS Security Hub service and provides customers with an AWS native implementation for automated remediations for these CIS violations detected by AWS Security Hub. 7 | 8 | 9 | ## How it Works 10 | 11 | This implementation is based on the following solution approach: 12 | 13 | 1. Leverages AWS Security Hub directly to provide continuous detection of CIS findings 14 | 2. Provides AWS Systems Manager Automation Documents for automated remediation for AWS Security Hub findings. All documents are automatically provisioned via an AWS CloudFormation template. 15 | 3. Provides integration of AWS Security Hub Custom Actions with AWS Systems Manager Automation Documents to provide real time remediations of AWS Security Hub FSBP findings as follows: 16 | * Leverages the ability of AWS Security Hub to send findings associated with custom actions to CloudWatch Events as Security Hub Findings - Custom Action events. 17 | * The CloudWatch Events Rule invokes the corresponding Lambda Function as the Target for the source Security Hub Custom Action event 18 | * The Lambda function processes the finding using the standard findings format provided by Security Hub - AWS Security Finding Format (ASFF) and invokes the corresponding AWS Systems Manager Automation Document with the input from the ASFF finding 19 | 20 | 21 | ## Solution Design 22 | 23 | ![](images/arch-diagram.png) 24 | 25 | ## How To Install 26 | 27 | 1. **Template 1 of 3:** aws-aws-cis-cloudwatchlogmetricfilters.yml 28 | * Provisions CloudWatch Logs Metric Filters. Enter email address as input. Simply install on the CloudFormation console (or CLI). Installs in approx 1-2 mins. 29 | 30 | 2. **Template 2 of 3:** aws-cis-systemsmanagerautomations.yml 31 | * Provisions AWS Systems Manager automation documents. These documents are used to provide automated remediations within the provisioned AWS Security Hub Action. 32 | * Provisions with fully built-in pre-reqs. No input parameters required. Simply install on the CloudFormation console (or CLI). Installs in approx 3-4 mins. 33 | 34 | 2. **Template 3 of 3:** aws-cis-securityhubactions.yml 35 | * Provisions AWS CloudWatch Evemts and AWS Security Hub Custom Actions. No input parameters. Simply install on the CloudFormation console (or CLI). Installs in approx 3-4 mins. 36 | * Leverages the output from the previous template specifically the AWS Systems Manager Automation documents 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /aws-remediate-cis-securityhub/cft/aws-cis-securityhubactions.yml: -------------------------------------------------------------------------------- 1 | 2 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 3 | # CloudFormation Template 2 of 3 - Real Time Automated Remediation for CIS AWS Foundations Benchmark 4 | # 5 | # Pre-req : Uses the AWS SSM Automation CloudFormation Template. 6 | # This template integrates AWS Security Hub custom actions with Custom AWS SSM Automation Remediation Documents 7 | # 8 | # @author Kanishk Mahajan 9 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 10 | AWSTemplateFormatVersion: 2010-09-09 11 | Description: CloudFormation Template 2 of 3 - Real Time Automated Remediation for CIS AWS Foundations Benchmark. (qs-1t0eilb5g) 12 | 13 | Resources: 14 | 15 | CreateSecurityHubCustomActionTargetLambda: 16 | Type: AWS::Lambda::Function 17 | Properties: 18 | FunctionName: CreateSecurityHubCustomActionTargetLambda 19 | Description: Custom resource to create an action target in Security Hub 20 | Handler: index.lambda_handler 21 | MemorySize: 256 22 | Role: !GetAtt CreateSecurityHubCustomActionTargetLambdaRole.Arn 23 | Runtime: python3.7 24 | Timeout: 60 25 | Code: 26 | ZipFile: | 27 | import boto3 28 | import cfnresponse 29 | import os 30 | def lambda_handler(event, context): 31 | try: 32 | properties = event['ResourceProperties'] 33 | region = os.environ['AWS_REGION'] 34 | client = boto3.client('securityhub', region_name=region) 35 | responseData = {} 36 | if event['RequestType'] == 'Create': 37 | response = client.create_action_target( 38 | Name=properties['Name'], 39 | Description=properties['Description'], 40 | Id=properties['Id'] 41 | ) 42 | responseData['Arn'] = response['ActionTargetArn'] 43 | elif event['RequestType'] == 'Delete': 44 | account_id = context.invoked_function_arn.split(":")[4] 45 | client.delete_action_target( 46 | ActionTargetArn=f"arn:aws:securityhub:{region}:{account_id}:action/custom/{properties['Id']}" 47 | ) 48 | cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData) 49 | except Exception as e: 50 | print(e) 51 | cfnresponse.send(event, context, cfnresponse.FAILED, {}) 52 | CreateSecurityHubCustomActionTargetLambdaRole: 53 | Type: AWS::IAM::Role 54 | Properties: 55 | AssumeRolePolicyDocument: 56 | Version: 2012-10-17 57 | Statement: 58 | - Effect: Allow 59 | Principal: { Service: lambda.amazonaws.com } 60 | Action: 61 | - sts:AssumeRole 62 | Path: / 63 | ManagedPolicyArns: 64 | - !Sub "arn:${AWS::Partition}:iam::aws:policy/AWSSecurityHubFullAccess" 65 | - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" 66 | 67 | 68 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 69 | # CIS AWS Foundations Benchmark - 2.9 – Ensure VPC flow logging is enabled in all VPCs 70 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 71 | 72 | VPCFlowLogsEnabledRule: 73 | Type: AWS::Events::Rule 74 | Properties: 75 | Name: VPCFlowLogsEnabledRule 76 | Description: "CIS AWS Foundations Benchmark - 2.9 – Ensure VPC flow logging is enabled in all VPCs" 77 | EventPattern: 78 | source: 79 | - aws.securityhub 80 | detail-type: 81 | - Security Hub Findings - Custom Action 82 | resources: 83 | - !GetAtt VPCFlowLogsEnabledActionTarget.Arn 84 | State: "ENABLED" 85 | Targets: 86 | - 87 | Arn: 88 | Fn::GetAtt: 89 | - "VPCFlowLogsEnabledLambda" 90 | - "Arn" 91 | Id: "EnableVPCFlowLogs" 92 | 93 | VPCFlowLogsEnabledActionTarget: 94 | Type: Custom::ActionTarget 95 | Version: 1.0 96 | Properties: 97 | ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn 98 | Name: EnableVPCFlowLogs 99 | Description: CIS29 Event from Security Hub 100 | Id: EnableVPCFlowLogs 101 | 102 | VPCFlowLogsEnabledPermission: 103 | Type: AWS::Lambda::Permission 104 | Properties: 105 | FunctionName: 106 | Ref: "VPCFlowLogsEnabledLambda" 107 | Action: "lambda:InvokeFunction" 108 | Principal: "events.amazonaws.com" 109 | SourceArn: 110 | Fn::GetAtt: 111 | - "VPCFlowLogsEnabledRule" 112 | - "Arn" 113 | 114 | VPCFlowLogsEnabledLambda: 115 | Type: AWS::Lambda::Function 116 | DependsOn: VPCFlowLogsEnabledLambdaRole 117 | Properties: 118 | FunctionName: VPCFlowLogsEnabledLambda 119 | Description: CIS 2.9 Remediation using Custom SSM Document 120 | Handler: index.lambda_handler 121 | MemorySize: 256 122 | Role: !GetAtt VPCFlowLogsEnabledLambdaRole.Arn 123 | Runtime: python3.7 124 | Timeout: 60 125 | Environment: 126 | Variables: 127 | CloudWatchLogGroupArn : !ImportValue FlowLogsCloudWatchLogGroupArn 128 | CloudWatchLogGroupName : !ImportValue FlowLogsCloudWatchLogs 129 | FlowLogRoleArn : !ImportValue FlowLogsRoleArn 130 | Code: 131 | ZipFile: | 132 | import boto3 133 | import json 134 | import os 135 | def lambda_handler(event, context): 136 | 137 | VpcArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) 138 | VpcId_1 = VpcArn.split(':')[-1] 139 | VpcId = VpcId_1.replace("vpc/","") 140 | Id = str(event['detail']['findings'][0]['Id']) 141 | CloudWatchLogGroupArn = os.environ['CloudWatchLogGroupArn'] 142 | CloudWatchLogGroupName = os.environ['CloudWatchLogGroupName'] 143 | FlowLogRoleArn = os.environ['FlowLogRoleArn'] 144 | ssm = boto3.client('ssm') 145 | try: 146 | response = ssm.start_automation_execution( 147 | DocumentName='Custom-EnableVPCFlowLogsCF', 148 | DocumentVersion='1', # default 149 | Parameters={ 150 | 'FlowLogRoleArn': [ FlowLogRoleArn ], 151 | 'CloudWatchLogGroupArn': [ CloudWatchLogGroupArn ], 152 | 'CloudWatchLogGroupName': [ CloudWatchLogGroupName ], 153 | 'VpcId': [ VpcId ] 154 | } 155 | ) 156 | 157 | except Exception as e: 158 | print(e) 159 | print("SSM automation execution error") 160 | raise 161 | 162 | VPCFlowLogsEnabledLambdaRole: 163 | Type: AWS::IAM::Role 164 | Properties: 165 | AssumeRolePolicyDocument: 166 | Version: 2012-10-17 167 | Statement: 168 | - Effect: Allow 169 | Principal: { Service: lambda.amazonaws.com } 170 | Action: 171 | - sts:AssumeRole 172 | Path: / 173 | ManagedPolicyArns: 174 | - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" 175 | - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonSSMAutomationRole" -------------------------------------------------------------------------------- /aws-remediate-cis-securityhub/images/arch-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-remediate-cis-securityhub/images/arch-diagram.png -------------------------------------------------------------------------------- /aws-servicecatalog-prescriptivecompliance/README-old.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Prescriptive Compliance with Service Catalog and Config 5 | 6 | Standardize the provisioning and set up of configuration compliance using AWS Service Catalog and AWS Config Rules with custom Config Remediations 7 | 8 | 9 | ## Install 10 | 11 | 1. Launch the sample 'aws-servicecatalog-prescriptivecompliance.yml' template from any account in your organization where Config is already enabled. 12 | 2. Provisions a AWS Service Catalog Portfolio with an AWS Config Remediations Product. 13 | - The AWS Config Remediations Product provides automated detection with AWS Config and automated remediations with custom AWS Systems Manager documents 14 | - Provisions all pre-reqs for AWS Systems Manager Remediations 15 | - Provisions Custom AWS Systems Manager Automation Documents to provide Automated Remediations for AWS Config 16 | - For demo purposes (for GameDay, Reinforce etc) the template provisions misconfigured resources to trigger an attack and then also provisions on demand evaluations for AWS Config to detect and then remediate the attack with provisioned custom SSM remediations 17 | - Creates a launch constraint for a "Team Member' Role. In your AWS account, create a Team Member IAM role and add an IAM user to that role to demonstrate end user access to the catalog. Ignore this step if the AWS account is provisioned by Event Engine 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /aws-servicecatalog-prescriptivecompliance/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Prescriptive Compliance with Service Catalog and Config. Use a CCOE approach to standardize compliance 5 | 6 | This solution demonstrates the combined use of DevOps automation and Infrastructure as Code (IaC) via AWS CodePipeline, AWS Service Catalog and AWS CloudFormation to enable CCOE (Cloud Center of Excellence) AWS administrators and infrastructure engineers to automate the management and deployment of Service Catalog Portfolios that contain Service Catalog Products containing AWS Config rules and integrated AWS Systems Manager (SSM) remediation runbooks 7 | 8 | We will deploy this solution in a multi account organization. Our organization deployed via AWS Organizations comprises of a Shared Services account which is where CCOE (Cloud Center of Excellence) administrators can deploy shared service and can add/remove/update compliance rules. These updates flow through a devops based AWS CodePipeline deployment to the managed accounts and result in updated compliance related Service Catalog Portfolios in the managed accounts. The entire solution is setup in 1 step with Infrastructure as Code (IaC) automation using AWS CloudFormation. 9 | 10 | 11 | ## Personas 12 | 13 | 1. CCOE AWS administrator 14 | 1. The CCOE administrator performs initial setup from the shared services account. After setup, the DevOps infrastructure (AWS CodePipeline) is provisioned in the shared services account, and an AWS Service Catalog Portfolio with Config rules and integrated remediation runbooks is provisioned in the managed accounts. 15 | 2. The CCOE administrator also performs code updates from the local Git repository. The administrator checks in updated Config rules and remediation runbook templates and (optionally) an updated buildspec.yaml file. The updated code flows via AWS CodePipeline in the AWS shared services account and updates the AWS Service Catalog Portfolio in the managed accounts. 16 | 17 | 2. End user / AWS administrator in the managed accounts 18 | The end user launches the Config rules and integrated remediation runbooks from the AWS Service Catalog console in the managed account. 19 | 20 | ## What is implemented 21 | 22 | The following AWS CloudFormation templates have been implemented for this solution - 23 | 1. aws-servicecatalog-codepipeline.yaml – Sets up the AWS CodePipeline automation in the Shared Services account that distributes service catalog portfolios to the managed accounts 24 | 2. aws-servicecatalog-prescriptivecompliance.yml – Sets up the AWS Service Catalog Portfolio that consists of Service Catalog Products comprised of Config rules with remediation runbooks 25 | 26 | 27 | ## Architecture 28 | 29 | ![](images/ccoe-prescriptivecompliance.png) 30 | 31 | 32 | ## Pre-requisites 33 | 34 | 1. As a CCOE AWS administrator signed in to the AWS shared services account, set up the following resources. 35 | Enable AWS Config in the shared service account and all your managed accounts in the organization. [Perform step 1 from the Automate configuration compliance at scale blog post](https://aws.amazon.com/blogs/mt/automate-configuration-compliance-at-scale-in-aws/) to use Systems Manager quick setup to do that with just a few clicks from your console. 36 | 2. Integrate AWS Cloud9 local Git repository with AWS CodeCommit remote Git repository 37 | 1. Use the aws-servicecatalog-configremediations-v1.yml AWS CloudFormation template that contains AWS Config Managed rules with integrated AWS Systems Manager remediation runbooks for common cloud configuration compliance violations. You can get the AWS CloudFormation template that provides a full coverage of PCI rules with SSM remediation runbooks from this [PCI and FSBP Config Rules with built-in SSM remediations](https://github.com/aws-samples/aws-config-pci-fsbp-ssmremediations) repository 38 | 2. Create an AWS CodeCommit Git repository in the shared services account and integrate it with your local Git repository. Using AWS Cloud9 is one of the easiest ways in AWS to set up a local Git repository and integrate with CodeCommit as the remote Git repository. 39 | 3. Download these files from this solution’s GitHub repo and upload them to your Cloud9 local Git repository.The local Cloud9 Git repository contains the following files in this structure. 40 | 1. Compliance product templates: 41 | 1. aws-servicecatalog-configremediations-v1.yml in a *compliance* folder 42 | 2. aws-servicecatalog-prescriptivecompliance.yml in the root folder 43 | 2. buildspec.yml in the root folder 44 | 3. buildspec-update.yml in the root folder 45 | 4. Create an S3 staging bucket using this naming convention: s3-configremediations-*accountid*-*region*. Create a folder called *compliance* in your S3 bucket. The folder names here need to match the folder names in your local Git repository. You can create these folders with any names as long as those are the same names used while creating your local Git repository there. 46 | 5. In the following files that are available for download from the solution, substitute the *accountid* parameter with the AWS Account ID of the shared services account. Substitute the *region* parameter with the AWS region of your shared services account. Substitute the *managedaccount* and *managedregion* parameters with comma separated AWS Account IDs and comma separated AWS regions respectively of the managed accounts where the solution will be deployed. 47 | 1. buildspec.yml 48 | 2. buildspec-updates.yml 49 | 50 | 51 | ## How to Install 52 | 53 | The initial set up is done in 1 step by the CCOE (Cloud Center of Excellence) AWS Administrator from the shared services account. 54 | 55 | 1. Launch the aws-servicecatalog-codepipeline.yml template. The template takes the following parameters and you can accept all defaults. 56 | 1. RepositoryName: CodeCommit repository for the Config remediation CloudFormation templates 57 | 2. BranchName: Branch in the CodeCommit repository for the Config Remediation CloudFormation templates 58 | 3. S3StagingBucketPrefix: Prefix for the S3 Staging Bucket that stages the code copied from code commit. In our case this is s3-configremediations-*accountid*-*region* 59 | 60 | 61 | ## Validate compliance 62 | 63 | Test and validate the standardized compliance posture that CCOE teams can enforce across managed accounts using AWS Service Catalog 64 | 65 | **Step 1: Launch the Service Catalog Product** 66 | 1. Log in to the IAM console of the AWS managed account as an administrator and create an IAM user that is a member of the EnduserGroup and logout of the managed account. 67 | 2. Navigate to the AWS Service Catalog console of the managed account as the IAM end user that was created and navigate to the left sidebar and choose Products. 68 | 1. Select the *AWS ConfigRemediations Compliance Product* product, accept the defaults and select *Launch Product*. The Service Catalog product screen will auto refresh until the product has been launched. Select *Provisioned Products* from the left sidebar to validate that the product has been launched and the status shows available. 69 | 70 | **Step 2: Review provisioned Config rules with attached remediation runbooks** 71 | 1. Navigate to the AWS Config Console of the managed account. You will see that several AWS Config rules - specifically ‘cloud-trail-log-file-validation-enabled’, ‘ReleaseElasticIP’, ‘cloud_trail_cloud_watch_logs_enabled’, ‘cmk-backing-key-rotation-enabled’ and ‘cis-iam-password-policy’- with associated remediation runbooks have been provisioned for you based on the launch of the Service Catalog product. 72 | 1. These Config rules with associated remediations will provide continuous compliance for your AWS environment based on the evaluation of these provisioned rules. 73 | 74 | **Step 3: Verify automated ‘attack’ and validate compliance** 75 | 1. The solution provides built-in automation that launches a *compliance attack* by simulating misconfiguration of AWS resources. Log in as an administrator in the managed account: 76 | 1. Check that an AWS CloudTrail called ‘ReinforceTrail’ has been provisioned without log file validation and CloudWatch Logs monitoring enabled. Check that an AWS KMS Customer Master Key with description ‘Test Key Rotation’ has key rotation disabled and that there’s an Elastic IP with an unassociated EC2 instance. 77 | 2. Navigate to the AWS Systems Manager console and select Automation in the left panel and then select Executions. Since we have launched the Service Catalog Product in the managed account, our standardized compliance posture triggers AWS Config Remediations that leverage our integrated and custom AWS Systems Manager remediation runbooks. You can monitor the Execution status in the Systems Manager Automation console for each of the automations and verify their successful automation status. 78 | 3. Finally validate the compliance posture of the managed account by validating that each of the misconfigured resources are now in the desired state. Check that the AWS CloudTrail called ‘ReinforceTrail’ has been both log file validation and CloudWatch Logs monitoring enabled. Check that an AWS KMS Customer Master Key with description ‘Test Key Rotation’ has key rotation enabled and that the unassociated Elastic IP has been removed. 79 | -------------------------------------------------------------------------------- /aws-servicecatalog-prescriptivecompliance/cft/buildspec-update.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | - echo "Python has some SSL issues in this version so we force an upgrade which doesn't fix everything; don't be alarmed by the warnings." 6 | build: 7 | commands: 8 | - echo "S3 Upload Beginning" 9 | - python -V 10 | - export ACCID=$(aws sts get-caller-identity --query 'Account' | tr -d '"') 11 | - aws s3 sync . s3://$STAGING_BUCKET/ --delete --exclude "*" --include "*.json" --include "*.yml" --include "*.yaml" 12 | - echo "S3 Upload Complete, updating cloudformation now..." 13 | - aws cloudformation update-stack-set --stack-set-name aws-servicecatalog-prescriptivecompliance --parameters "[{\"ParameterKey\":\"S3StagingBucketURL\",\"ParameterValue\":\"https://s3-configremediations--.s3.amazonaws.com/\"}]" --template-url "https://$STAGING_BUCKET.s3.amazonaws.com/aws-servicecatalog-prescriptivecompliance.yml" --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND 14 | 15 | post_build: 16 | commands: 17 | - echo "Deploy complete" 18 | -------------------------------------------------------------------------------- /aws-servicecatalog-prescriptivecompliance/cft/buildspec.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | - echo " --Python has some SSL issues in this version so we force an upgrade which doesn't fix everything; don't be alarmed by the warnings." 6 | build: 7 | commands: 8 | - echo "S3 Upload Beginning" 9 | - python -V 10 | - export ACCID=$(aws sts get-caller-identity --query 'Account' | tr -d '"') 11 | - aws s3 sync . s3://$STAGING_BUCKET/ --delete --exclude "*" --include "*.json" --include "*.yml" --include "*.yaml" 12 | - echo "S3 Upload Complete, updating cloudformation now..." 13 | - aws cloudformation create-stack-set --stack-set-name aws-servicecatalog-prescriptivecompliance --parameters "[{\"ParameterKey\":\"S3StagingBucketURL\",\"ParameterValue\":\"https://s3-configremediations--.s3.amazonaws.com/\"}]" --template-url "https://$STAGING_BUCKET.s3.amazonaws.com/aws-servicecatalog-prescriptivecompliance.yml" --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND 14 | - aws cloudformation create-stack-instances --stack-set-name aws-servicecatalog-prescriptivecompliance --accounts --regions 15 | post_build: 16 | commands: 17 | - echo "Deploy complete" 18 | -------------------------------------------------------------------------------- /aws-servicecatalog-prescriptivecompliance/images/ccoe-prescriptivecompliance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-servicecatalog-prescriptivecompliance/images/ccoe-prescriptivecompliance.png -------------------------------------------------------------------------------- /aws-systemsmanager-automations/migrations/cft/domain-join-automation-role.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Parameters: 3 | DomainJoinAutomationEC2Role: 4 | Type: String 5 | Description: Role Name for EC2 Domain Join Automation that will be created using this template 6 | Default: EC2DomainJoinAutomation 7 | Resources: 8 | DomainJoinAutomationRole: 9 | Type: 'AWS::IAM::Role' 10 | Properties: 11 | RoleName: !Ref DomainJoinAutomationEC2Role 12 | AssumeRolePolicyDocument: 13 | Statement: 14 | - Action: sts:AssumeRole 15 | Effect: Allow 16 | Principal: 17 | Service: 18 | - ec2.amazonaws.com 19 | Version: "2012-10-17" 20 | ManagedPolicyArns: 21 | - !Sub arn:${AWS::Partition}:iam::aws:policy/AmazonSSMManagedInstanceCore 22 | Path: / 23 | Policies: 24 | - PolicyName: ssm-param-kms-policy 25 | PolicyDocument: 26 | Version: 2012-10-17 27 | Statement: 28 | - Effect: Allow 29 | Action: 30 | - 'kms:Decrypt' 31 | Resource: 32 | - !ImportValue AD-Creds-KMS-Key-Arn 33 | - Effect: Allow 34 | Action: 35 | - 'ssm:GetParameter*' 36 | Resource: 37 | - !ImportValue AD-Username-SSM-Param-Arn 38 | - !ImportValue AD-Password-SSM-Param-Arn 39 | 40 | InstanceProfile: 41 | Type: AWS::IAM::InstanceProfile 42 | Properties: 43 | InstanceProfileName: !Ref DomainJoinAutomationEC2Role 44 | Path: / 45 | Roles: 46 | - Ref: DomainJoinAutomationRole 47 | -------------------------------------------------------------------------------- /aws-systemsmanager-automations/migrations/cft/domainJoin_RunDocument_yaml.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: SSM Document for Domain Join Automation 3 | Parameters: 4 | DomainJoinSSMDocumentName: 5 | Type: String 6 | Description: Name for the Domain Join SSM Run Document created by this stack 7 | Default: DomainJoinAutomation 8 | Resources: 9 | MySSMDocument: 10 | Type: 'AWS::SSM::Document' 11 | Properties: 12 | Content: 13 | schemaVersion: '2.2' 14 | description: This document will be used for domain join of EC2 instances. 15 | parameters: 16 | DomainName: 17 | type: String 18 | description: (Required) FQDN of AD 19 | default: corp.example.com 20 | DomainJoinUserName: 21 | type: String 22 | description: (Required) Domain Username SSM Parameter 23 | default: domainAdmin 24 | DomainJoinPassword: 25 | type: String 26 | description: (Required) Domain User password SSM Parameter 27 | default: domainPassword 28 | mainSteps: 29 | - precondition: 30 | StringEquals: 31 | - platformType 32 | - Windows 33 | action: aws:runPowerShellScript 34 | name: DomainJoinWindows 35 | inputs: 36 | timeoutSeconds: 7200 37 | runCommand: 38 | - "Import-Module -name AWSPowerShell" 39 | - "$DomainJoined = ''" 40 | - "##### Get Current Computer info #####" 41 | - "$ComputerInfo = get-computerinfo" 42 | - "$CurrentDomain = $ComputerInfo.csdomain" 43 | - "##### Check if Computer is not joined to Domain #####" 44 | - "IF ($CurrentDomain -eq 'WORKGROUP'){" 45 | - "$DomainJoined = '$False'}" 46 | - "Else {" 47 | - "$DomainJoined = '$True'" 48 | - "echo \"Instance is joined to the domain\"" 49 | - "exit 0" 50 | - "}" 51 | - "##### Domain Join Credentials #####" 52 | - "$DomainAccount = (Get-SSMParameter -Name {{DomainJoinUserName}} -WithDecryption $True).Value" 53 | - "$UserAccount = \"{{DomainName}}\\$DomainAccount\"" 54 | - "$Password = (Get-SSMParameter -Name {{DomainJoinPassword}} -WithDecryption $True).Value | ConvertTo-SecureString -asPlainText -Force" 55 | - "##### Create credential object #####" 56 | - "$credential = New-Object System.Management.Automation.PSCredential($UserAccount,$Password)" 57 | - "##### Join Domain#####" 58 | - "IF ($DomainJoined -eq '$False'){" 59 | - "Add-Computer -DomainName {{DomainName}} -Credential $credential -Verbose" 60 | - "$DomainJoined = '$True'" 61 | - "#Restart-Computer -Force" 62 | - "exit 3010" 63 | - "}" 64 | - "##### Exit Gracefully after setting Domain Joined to True #####" 65 | - "IF ($DomainJoined -eq '$True')" 66 | - "{" 67 | - "echo \"Run document execution completed successfully\"" 68 | - "exit 0" 69 | - "}" 70 | - precondition: 71 | StringEquals: 72 | - platformType 73 | - Linux 74 | action: aws:runShellScript 75 | name: DomainJoinLinux 76 | inputs: 77 | timeoutSeconds: 7200 78 | runCommand: 79 | - "if [ -f /tmp/ad_join_reboot ]; then" 80 | - "echo \"Document executed successfully\"" 81 | - "rm -f /tmp/ad_join_reboot" 82 | - "exit 0" 83 | - "fi" 84 | - " " 85 | - "sudo yum -y update" 86 | - "sudo yum -y install sssd realmd krb5-workstation samba-common-tools" 87 | - "sudo yum -y install oddjob oddjob-mkhomedir sssd adcli" 88 | - "domainJoinPassword=$(aws ssm get-parameter --name {{DomainJoinPassword}} --with-decryption --query \"Parameter.Value\" --output text)" 89 | - "domainJoinUsername=$(aws ssm get-parameter --name {{DomainJoinUserName}} --with-decryption --query \"Parameter.Value\" --output text)" 90 | - "## test if already joined to {{DomainName}} realm ##" 91 | - "if [[ $(realm list | grep {{DomainName}}) ]] ; then" 92 | - "echo \"{{DomainName}} realm configured\"" 93 | - "exit 0" 94 | - "fi" 95 | - " " 96 | - "#### Join Domain ####" 97 | - "echo ${domainJoinPassword} | sudo realm join -U ${domainJoinUsername} {{DomainName}} -v" 98 | - "if [ $? -ne 0 ]; then" 99 | - "echo \"Unable to join domain.Exiting..\"" 100 | - "exit 1" 101 | - "fi" 102 | - " " 103 | - "#### Update sshd_config ####" 104 | - "/usr/bin/sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config" 105 | - " " 106 | - "touch /tmp/ad_join_reboot" 107 | - "exit 194" 108 | DocumentType: Command 109 | Name: !Ref DomainJoinSSMDocumentName 110 | -------------------------------------------------------------------------------- /aws-systemsmanager-automations/migrations/cft/ssm-parameters.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Parameters: 3 | DomainJoinUserName: 4 | Type: String 5 | NoEcho: true 6 | Description: Value for Username SSM Parameter 7 | DomainJoinPassword: 8 | Type: String 9 | NoEcho: true 10 | Description: Value for Domain User password SSM Parameter 11 | 12 | Resources: 13 | DomainUsernameParam: 14 | Type: 'Custom::SSMParameter' 15 | Properties: 16 | ServiceToken: !GetAtt 'LambdaFunction.Arn' 17 | Name: domainAdmin 18 | Description: SSM Parameter for AD Username 19 | Type: SecureString 20 | Value: !Ref DomainJoinUserName 21 | KeyId: !Ref KMSKey 22 | DomainPasswordParam: 23 | Type: 'Custom::SSMParameter' 24 | Properties: 25 | ServiceToken: !GetAtt 'LambdaFunction.Arn' 26 | Name: domainPassword 27 | Description: SSM Parameter for AD Password 28 | Type: SecureString 29 | Value: !Ref DomainJoinPassword 30 | KeyId: !Ref KMSKey 31 | LambdaFunction: 32 | Type: AWS::Lambda::Function 33 | Properties: 34 | Handler: index.handler 35 | Role: !GetAtt LambdaExecutionRole.Arn 36 | Runtime: nodejs16.x 37 | Timeout: 60 38 | Code: 39 | ZipFile: > 40 | var response = require('cfn-response'); 41 | var aws = require('aws-sdk'); 42 | exports.handler = function(event, context) { 43 | console.log(event); 44 | 45 | var ssm = new aws.SSM(); 46 | var props = event.ResourceProperties; 47 | var splitStackArn = event.StackId.split(':'); 48 | var region = splitStackArn[3]; 49 | var accountId = splitStackArn[4]; 50 | var paramName = props.Name; 51 | var stackName = splitStackArn[5].split("/")[1]; 52 | var paramArn = "arn:aws:ssm:" + region + ":" + accountId + ":parameter/" + paramName; 53 | var cb = function(err, resp) { 54 | var cfnRespData = { Arn: paramArn, Name: paramName }; 55 | if (err) { 56 | console.log(err); 57 | response.send(event, context, response.FAILED, cfnRespData, paramArn); 58 | } else { 59 | console.log(resp); 60 | response.send(event, context, response.SUCCESS, cfnRespData, paramArn); 61 | } 62 | }; 63 | if (event.RequestType == "Create") { 64 | var params = { 65 | Name: props.Name, 66 | Type: props.Type, 67 | Description: props.Description, 68 | Value: props.Value, 69 | KeyId: props.KeyId, 70 | Overwrite: false 71 | }; 72 | if (props.Description) params.Description = props.Description; 73 | if (props.KeyId) params.KeyId = props.KeyId; 74 | 75 | ssm.putParameter(params, cb); 76 | } else if (event.RequestType == "Update") { 77 | var params = { 78 | Name: props.Name, 79 | Type: props.Type, 80 | Description: props.Description, 81 | Value: props.Value, 82 | KeyId: props.KeyId, 83 | Overwrite: true 84 | }; 85 | if (props.Description) params.Description = props.Description; 86 | if (props.KeyId) params.KeyId = props.KeyId; 87 | ssm.putParameter(params, cb); 88 | } else if (event.RequestType == "Delete") { 89 | ssm.deleteParameter({ Name: paramName }, cb); 90 | } 91 | }; 92 | Metadata: 93 | cfn_nag: 94 | rules_to_suppress: 95 | - id: W89 96 | reason: This is a custom resource Lambda function 97 | - id: W92 98 | reason: This is a custom resource Lambda function 99 | LambdaExecutionRole: 100 | Type: 'AWS::IAM::Role' 101 | Properties: 102 | AssumeRolePolicyDocument: 103 | Version: 2012-10-17 104 | Statement: 105 | - Effect: Allow 106 | Principal: 107 | Service: lambda.amazonaws.com 108 | Action: 'sts:AssumeRole' 109 | ManagedPolicyArns: 110 | - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole' 111 | Policies: 112 | - PolicyName: SSMParameterLambdaPolicy 113 | PolicyDocument: 114 | Version: 2012-10-17 115 | Statement: 116 | - Effect: Allow 117 | Action: 118 | - 'ssm:PutParameter' 119 | - 'ssm:DeleteParameter' 120 | Resource: !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/domain*' 121 | - PolicyName: KMSKeyAccessPolicy 122 | PolicyDocument: 123 | Version: 2012-10-17 124 | Statement: 125 | - Effect: Allow 126 | Action: 127 | - 'kms:Encrypt' 128 | - 'kms:Decrypt' 129 | - 'kms:ReEncrypt*' 130 | - 'kms:GenerateDataKey*' 131 | - 'kms:DescribeKey' 132 | Resource: !GetAtt KMSKey.Arn 133 | KMSKey: 134 | Type: 'AWS::KMS::Key' 135 | Properties: 136 | EnableKeyRotation: true 137 | Description: KMS Key for SSM Parameter Encryption 138 | KeyPolicy: 139 | Version: 2012-10-17 140 | Id: key-default-1 141 | Statement: 142 | - Sid: Enable IAM User Permissions 143 | Effect: Allow 144 | Principal: 145 | AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root' 146 | Action: 'kms:*' 147 | Resource: '*' 148 | - Sid: Allow administration of the key 149 | Effect: Allow 150 | Principal: 151 | AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root' 152 | Action: 153 | - 'kms:Create*' 154 | - 'kms:Describe*' 155 | - 'kms:Enable*' 156 | - 'kms:List*' 157 | - 'kms:Put*' 158 | - 'kms:Update*' 159 | - 'kms:Revoke*' 160 | - 'kms:Disable*' 161 | - 'kms:Get*' 162 | - 'kms:Delete*' 163 | - 'kms:TagResource' 164 | - 'kms:UntagResource' 165 | - 'kms:ScheduleKeyDeletion' 166 | - 'kms:CancelKeyDeletion' 167 | Resource: '*' 168 | - Sid: Allow use of the key 169 | Effect: Allow 170 | Principal: 171 | AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root' 172 | Action: 173 | - 'kms:Encrypt' 174 | - 'kms:Decrypt' 175 | - 'kms:ReEncrypt*' 176 | - 'kms:GenerateDataKey*' 177 | - 'kms:DescribeKey' 178 | Resource: '*' 179 | Aliases: 180 | Type: 'AWS::KMS::Alias' 181 | Properties: 182 | AliasName: alias/domain-creds-kms-key 183 | TargetKeyId: !Ref KMSKey 184 | 185 | Outputs: 186 | DomainCredsKmsKeyId: 187 | Description: Arn of the KMS key used for encrypting AD creds parameters 188 | Value: !GetAtt KMSKey.Arn 189 | Export: 190 | Name: 'AD-Creds-KMS-Key-Arn' 191 | DomainUserNameParamArn: 192 | Description: Arn of SSM Parameter which stores the Username used for domain join 193 | Value: !Ref DomainUsernameParam 194 | Export: 195 | Name: 'AD-Username-SSM-Param-Arn' 196 | DomainPasswordParamArn: 197 | Description: Arn of SSM Parameter which stores the Password used for domain join 198 | Value: !Ref DomainPasswordParam 199 | Export: 200 | Name: 'AD-Password-SSM-Param-Arn' 201 | DomainUserNameParamName: 202 | Description: Name of SSM Parameter which stores the Username used for domain join 203 | Value: 'domainAdmin' 204 | Export: 205 | Name: 'AD-Username-SSM-Param-Name' 206 | DomainPasswordParamName: 207 | Description: Name of SSM Parameter which stores the Password used for domain join 208 | Value: 'domainPassword' 209 | Export: 210 | Name: 'AD-Password-SSM-Param-Name' 211 | 212 | -------------------------------------------------------------------------------- /aws-systemsmanager-automations/patching/aws-ssm-patchmanager-v1.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | 3 | Description: 'AWS-RunPatchBaseline' 4 | 5 | # --------------------------------------------------------------------------------------------------------- 6 | # CloudFormation Template 1 of 2 - Patch Manager association 7 | # 8 | # 9 | # @kmmahaj 10 | ## 11 | ## License: 12 | ## This code is made available under the MIT-0 license. See the LICENSE file. 13 | # ------------------------------------------------------------............................................... 14 | 15 | Outputs: 16 | StackArn: 17 | Value: 18 | Ref: AWS::StackId 19 | Conditions: 20 | ShouldEnablePatching: 21 | Fn::Equals: 22 | - Ref: EnableWeeklyPatching 23 | - 'True' 24 | PatchWeekly: 25 | Type: AWS::SSM::Association 26 | Properties: 27 | Name: AWS-RunPatchBaseline 28 | ScheduleExpression: rate(7 days) 29 | AssociationName: 30 | Fn::Sub: "${AWS::AccountId}-PatchWeekly" 31 | Parameters: 32 | Operation: 33 | - Install 34 | - Scan 35 | Targets: 36 | - Values: 37 | - "*" 38 | Key: InstanceIds 39 | Parameters: 40 | EnableWeeklyPatching: 41 | Default: 'True' 42 | Type: String 43 | Description: True or False 44 | AllowedValues: 45 | - 'True' 46 | - 'False' 47 | -------------------------------------------------------------------------------- /aws-systemsmanager-changemanager/README.md: -------------------------------------------------------------------------------- 1 |

2 |

3 | 4 | # Automate change management in AWS with AWS Systems Manager Change Manager 5 | 6 | Template 1 first provisions AWS Systems Manager Automation Documents as well as all the required pre-reqs. Template 2 then leverages the Systems Manager Automation documents within AWS Config Remediation Rules to incorporate change management in a remediation action via Systems Manager automation 7 | 8 | 9 | 10 | ## Solution architecture 11 | 12 | ![](images/arch-changemanager.png) 13 | 14 | 15 | ## How To Install 16 | 17 | 1. **Template 1 of 2:** [aws-changemanager-ssmautomation.yml](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-systemsmanager-changemanager/cft/aws-changemanager-configremediation.yaml) 18 | * Provisions AWS Systems Manager automation documents. These documents are used to provide automated remediations within the provisioned AWS Config Rule. 19 | * Provisions with fully built-in pre-reqs. No input parameters required. Simply install on the CloudFormation console (or CLI). Installs in approx 1-2 mins. 20 | 21 | 2. **Template 2 of 2:** [aws-changemanager-configremediation.yml](https://github.com/aws-samples/aws-cloud-compliance-assurance/blob/main/aws-systemsmanager-changemanager/cft/aws-changemanager-configremediation.yaml) 22 | * Provisions AWS Config Managed Rules and attaches the custom AWS Systems Manager automation documents as AWS Config Remediations to the AWS Config Managed Rule. No input parameters. Simply install on the CloudFormation console (or CLI). Installs in approx 1-2 mins. 23 | * Leverages the output from the previous template specifically the AWS Systems Manager Automation documents 24 | 25 | 26 | -------------------------------------------------------------------------------- /aws-systemsmanager-changemanager/cft/aws-changemanager-configremediation.yaml: -------------------------------------------------------------------------------- 1 | 2 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 3 | # CloudFormation Template 2 of 2- 4 | # 5 | # Provisions 6 | # 1/ Config rule and 7 | # 2/ Config remediation using Change Manager based SSM automation 8 | # 9 | # 10 | # @kmmahaj 11 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 12 | 13 | 14 | Resources: 15 | 16 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 17 | # CIS AWS Foundations Benchmark - 2.9 – Ensure VPC flow logging is enabled in all VPCs 18 | # 19 | # The 1st half AWS::Config::ConfigRule provides detection with SourceIdentifier - AWS Managed Config Rule 20 | # The 2nd half AWS::Config::RemediationConfiguration provides remediation with Change Manager 21 | # ------------------------------------------------------------------------------------------------------------------------------------------------------- 22 | 23 | VPCFlowLogsEnabled: 24 | Type: "AWS::Config::ConfigRule" 25 | Properties: 26 | ConfigRuleName: VPCFlowLogsEnabled 27 | Description: "Ensures VPC Flow Logs are Enabled" 28 | Source: 29 | Owner: AWS 30 | SourceIdentifier: VPC_FLOW_LOGS_ENABLED 31 | MaximumExecutionFrequency: One_Hour 32 | VPCFlowLogsEnabledRemediation: 33 | DependsOn: VPCFlowLogsEnabled 34 | Type: 'AWS::Config::RemediationConfiguration' 35 | Properties: 36 | ConfigRuleName: VPCFlowLogsEnabled 37 | TargetId: "Custom-EnableChangeManagerVPCFlowLogs" 38 | TargetType: "SSM_DOCUMENT" 39 | Parameters: 40 | AutomationAssumeRole: 41 | StaticValue: 42 | Values: 43 | - !ImportValue AutomationAssumeRoleArn 44 | CloudWatchLogGroupArn: 45 | StaticValue: 46 | Values: 47 | - !ImportValue FlowLogsCloudWatchLogGroupArn 48 | CloudWatchLogGroupName: 49 | StaticValue: 50 | Values: 51 | - !ImportValue FlowLogsCloudWatchLogs 52 | FlowLogRoleArn: 53 | StaticValue: 54 | Values: 55 | - !ImportValue FlowLogsRoleArn 56 | VpcId: 57 | ResourceValue: 58 | Value: "RESOURCE_ID" 59 | ExecutionControls: 60 | SsmControls: 61 | ConcurrentExecutionRatePercentage: 10 62 | ErrorPercentage: 10 63 | Automatic: True 64 | MaximumAutomaticAttempts: 5 65 | RetryAttemptSeconds: 60 66 | 67 | 68 | #------------------------------------------------------------------------------------------ 69 | # On Demand Config Evaluation Lambda for AWS Config Rules: 70 | # -- Provides a live demo experience to the user 71 | # -- Triggers Detection at 2 min intervals of misconfigured resources via AWS Config 72 | #------------------------------------------------------------------------------------------- 73 | 74 | OnDemandConfigEvalEventRule: 75 | Type: AWS::Events::Rule 76 | Properties: 77 | Name: OnDemandConfigEvalEventRule 78 | Description: "Trigger On Demand Evaluation of Config Rules for Game Day" 79 | State: "ENABLED" 80 | ScheduleExpression: "rate(2 minutes)" 81 | Targets: 82 | - 83 | Arn: 84 | Fn::GetAtt: 85 | - "OnDemandConfigEvalLambda" 86 | - "Arn" 87 | Id: "OnDemandConfigEval" 88 | 89 | PermissionForEventsToInvokeConfigLambda: 90 | Type: AWS::Lambda::Permission 91 | Properties: 92 | Action: lambda:InvokeFunction 93 | FunctionName: !GetAtt "OnDemandConfigEvalLambda.Arn" 94 | Principal: events.amazonaws.com 95 | SourceArn: !GetAtt "OnDemandConfigEvalEventRule.Arn" 96 | 97 | OnDemandConfigEvalLambda: 98 | Type: AWS::Lambda::Function 99 | Properties: 100 | Code: 101 | ZipFile: | 102 | import json 103 | import os 104 | import boto3 105 | import logging 106 | LOGGER = logging.getLogger() 107 | LOGGER.setLevel(logging.INFO) 108 | def lambda_handler(event, context): 109 | try: 110 | ruleName1 = os.environ['ruleName1'] 111 | client = boto3.client('config') 112 | response = client.start_config_rules_evaluation( 113 | ConfigRuleNames=[ 114 | ruleName1 115 | ] 116 | ) 117 | except Exception as e: 118 | print(e) 119 | print("AWS Config Evaluation execution error") 120 | raise 121 | Handler: index.lambda_handler 122 | MemorySize: 128 123 | Role: !GetAtt "OnDemandConfigEvalLambdaRole.Arn" 124 | Runtime: python3.7 125 | Timeout: 60 126 | Environment: 127 | Variables: 128 | ruleName1: 'VPCFlowLogsEnabled' 129 | 130 | 131 | # On Demand Config Eval Role 132 | OnDemandConfigEvalLambdaRole: 133 | Type: 'AWS::IAM::Role' 134 | Properties: 135 | RoleName: !Sub demo-OnDemandConfigEvalLambdaRole-${AWS::Region} 136 | AssumeRolePolicyDocument: 137 | Version: 2012-10-17 138 | Statement: 139 | - Effect: Allow 140 | Principal: 141 | Service: 142 | - lambda.amazonaws.com 143 | Action: 144 | - 'sts:AssumeRole' 145 | Path: / 146 | ManagedPolicyArns: 147 | - !Sub "arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess" 148 | -------------------------------------------------------------------------------- /aws-systemsmanager-changemanager/images/arch-changemanager.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-cloud-compliance-assurance/fb8251ab8536ad36a64bac8408b29f5e7ee33df1/aws-systemsmanager-changemanager/images/arch-changemanager.png --------------------------------------------------------------------------------