├── Images ├── Copy-JWT.png ├── JWT-Pasted.png ├── Config-Header.png ├── New-Execution.png └── SFN-Execution-Map.png ├── NOTICE ├── Workshop-Rules ├── 1-Introduction-to-Config-Rules │ ├── Images │ │ ├── Add-Rule.png │ │ ├── Add-Custom-Rule.png │ │ ├── Cloudformation.png │ │ ├── Rule-Parameters.png │ │ ├── Rule-Basic-Config.png │ │ └── Rule-Trigger-Config.png │ ├── compliant_test_event.json │ ├── rule.py │ ├── noncompliant_test_event.json │ └── README.md ├── 4-Overlapping-VPC-IP-Ranges │ ├── README.md │ ├── compliant-test-event.json │ ├── noncompliant-test-event.json │ └── rule.py ├── 5-S3-Bucket-Policy-Read-Access │ ├── README.md │ ├── rule.py │ ├── compliant-test-event.json │ └── noncompliant-test-event.json ├── 3-Private-VPC-No-IGW-Policy │ ├── compliant-test-event.json │ ├── noncompliant-test-event.json │ ├── README.md │ └── rule.py └── 2-S3-Version-Lifecyle-Policies │ ├── noncompliant_test_event.json │ ├── README.md │ ├── rule.py │ └── compliant_test_event.json ├── .github └── PULL_REQUEST_TEMPLATE.md ├── README.md └── LICENSE /Images/Copy-JWT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Images/Copy-JWT.png -------------------------------------------------------------------------------- /Images/JWT-Pasted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Images/JWT-Pasted.png -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | AWS Serverless Config Rules Workshop 2 | Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /Images/Config-Header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Images/Config-Header.png -------------------------------------------------------------------------------- /Images/New-Execution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Images/New-Execution.png -------------------------------------------------------------------------------- /Images/SFN-Execution-Map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Images/SFN-Execution-Map.png -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/Images/Add-Rule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Workshop-Rules/1-Introduction-to-Config-Rules/Images/Add-Rule.png -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/Images/Add-Custom-Rule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Workshop-Rules/1-Introduction-to-Config-Rules/Images/Add-Custom-Rule.png -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/Images/Cloudformation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Workshop-Rules/1-Introduction-to-Config-Rules/Images/Cloudformation.png -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/Images/Rule-Parameters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Workshop-Rules/1-Introduction-to-Config-Rules/Images/Rule-Parameters.png -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/Images/Rule-Basic-Config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Workshop-Rules/1-Introduction-to-Config-Rules/Images/Rule-Basic-Config.png -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/Images/Rule-Trigger-Config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-config-rules-workshop/HEAD/Workshop-Rules/1-Introduction-to-Config-Rules/Images/Rule-Trigger-Config.png -------------------------------------------------------------------------------- /Workshop-Rules/4-Overlapping-VPC-IP-Ranges/README.md: -------------------------------------------------------------------------------- 1 | # No VPC Overlap with On Premises Network 2 | Completion of this rule will require you to create a Lambda function and custom Config Rule using the yet-to-be complete code provided in [`rule.py`](./rule.py). The method and process of creating a new Lambda function and new custom Config Rule will mirror Module 1, with no additional permissions required. All that will differ are the code for the Lambda function, and the configuration of the Config Rule. 3 | 4 | ## The Purpose of This Rule 5 | One of the more foundational and rigid implementation decisions that you make while building applications on AWS is the CIDR block/IP range of a new VPC. Creating a VPC that has an overlapping IP range with an existing network could prevent future integration of the networks without using potentially complex Network Address Translation. **The purpose of this rule is to ensure that no VPCs have an overlapping IP range with existing on-premises networks.** There are two on premises networks that VPC IP ranges should not overlap with - 10.218.0.0/24, and 10.218.1.0/24. 6 | 7 | ### Hints for Completion 8 | 1. Remember to use the provided sample events to test your function rule. ...The test events may also provide a good reference for the evaluations your code should perform. 9 | 2. In order to leverage a Python library within your function code, make sure you import it first. 10 | 11 | Region| Launch 12 | ------|----- 13 | EU (Ireland) | [![Launch Module 4 in eu-west-1](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/cloudformation-launch-stack-button.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=ConfigRules-Module-4-No-Overlapping-IP-Ranges&templateURL=https://s3.amazonaws.com/config-rules-workshop-eu-west-1/module-4/template.yml) 14 | -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/compliant_test_event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":null,\"configurationItem\":{\"relatedEvents\":[],\"relationships\":[{\"resourceId\":\"vpc-d7a2f4b2\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::VPC\",\"name\":\"Is contained in Vpc\"}],\"configuration\":{\"description\":\"http and https only.\",\"groupName\":\"webserver-lambda\",\"ipPermissions\":[],\"ownerId\":\"123456789012\",\"groupId\":\"sg-1234567\",\"ipPermissionsEgress\":[{\"fromPort\":22,\"ipProtocol\":\"tcp\",\"ipv6Ranges\":[],\"prefixListIds\":[],\"toPort\":22,\"userIdGroupPairs\":[],\"ipv4Ranges\":[{\"cidrIp\":\"1.1.1.1/32\"}],\"ipRanges\":[\"1.1.1.1/32\"]}],\"tags\":[],\"vpcId\":\"vpc-1234567\"},\"supplementaryConfiguration\":{},\"tags\":{},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-06-28T17:47:21.582Z\",\"configurationStateId\":123456778,\"awsAccountId\":\"123456789012\",\"configurationItemStatus\":\"OK\",\"resourceType\":\"AWS::EC2::SecurityGroup\",\"resourceId\":\"sg-1234567\",\"resourceName\":\"compliant-sg\",\"ARN\":\"arn:aws:ec2:us-west-2:123456789012:security-group/sg-123456\",\"awsRegion\":\"us-west-2\",\"availabilityZone\":\"Not Applicable\",\"configurationStateMd5Hash\":\"12312423423542352\",\"resourceCreationTime\":null},\"notificationCreationTime\":\"2017-11-21T00:05:53.150Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{\"ipAddress\":\"1.1.1.1/32\"}", 5 | "resultToken": "TEST_TOKEN", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::123456789012:role/config-role", 8 | "configRuleArn": "arn:aws:config:us-west-2:123456789012:config-rule/config-rule-12345", 9 | "configRuleName": "YourRuleName", 10 | "configRuleId": "config-rule-12345", 11 | "accountId": "123456789012", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/rule.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import logging 4 | 5 | logger = logging.getLogger() 6 | logger.setLevel(logging.INFO) 7 | 8 | APPLICABLE_RESOURCES = ["AWS::EC2::SecurityGroup"] 9 | config = boto3.client("config") 10 | 11 | 12 | def evaluate_compliance(configuration_item, whitelist_ip): 13 | compliance_status = "COMPLIANT" 14 | 15 | if configuration_item["resourceType"] not in APPLICABLE_RESOURCES: 16 | return "NOT_APPLICABLE" 17 | 18 | for perms in configuration_item["configuration"]["ipPermissions"]: 19 | if "toPort" in perms and perms["toPort"] == 22: 20 | for range in perms["ipRanges"]: 21 | if range != whitelist_ip: 22 | compliance_status = "NON_COMPLIANT" 23 | 24 | return compliance_status 25 | 26 | 27 | def lambda_handler(event, context): 28 | logger.info("Event: " + json.dumps(event)) 29 | invoking_event = json.loads(event["invokingEvent"]) 30 | rule_parameters = json.loads(event["ruleParameters"]) 31 | configuration_item = invoking_event["configurationItem"] 32 | result_token = "No token found." 33 | if "resultToken" in event: 34 | result_token = event["resultToken"] 35 | 36 | evaluation = { 37 | "ComplianceResourceType": 38 | configuration_item["resourceType"], 39 | "ComplianceResourceId": 40 | configuration_item["resourceId"], 41 | "ComplianceType": 42 | evaluate_compliance(configuration_item, rule_parameters["ipAddress"]), 43 | "Annotation": 44 | "SSH Access is allowed to not allowed IP addess range", 45 | "OrderingTimestamp": 46 | configuration_item["configurationItemCaptureTime"] 47 | } 48 | if "dryRun" not in event: 49 | config.put_evaluations( 50 | Evaluations=[evaluation], 51 | ResultToken=result_token 52 | ) 53 | 54 | return evaluation['ComplianceType'] 55 | -------------------------------------------------------------------------------- /Workshop-Rules/5-S3-Bucket-Policy-Read-Access/README.md: -------------------------------------------------------------------------------- 1 | # S3 Bucket Policy Protection 2 | Completion of this rule will require you to create a Lambda function and custom Config Rule using the yet-to-be complete code provided in [`rule.py`](./rule.py). The method and process of creating a new Lambda function and new custom Config Rule will mirror Module 1, no additional permissions are required. All that will differ are the code for the Lambda function, and the configuration of the Config Rule. 3 | 4 | ## The Purpose of This Rule 5 | Access control for the objects stored in Amazon S3 buckets can be managed via a bucket policy. Bucket policies allow you to define which identity principals have the ability to perform some or all of the available S3 API operations for that bucket and the data within it. A change to a Bucket policy could change who has access to the data within the bucket, or even make it publicly available (which may be intended for many use cases, like public website assets). **For this scenario, we would like all buckets that allow read access to only provide that access to a specific IAM role with the name: ConfigRulesWorkshopTestRole.** Any buckets that allow read access to Principals other than ConfigWorkshopTestRole are noncompliant. 6 | 7 | ### Hints for Completion 8 | 1. The Step Functions State Machine will create the ConfigRulesWorkshopTestRole as described in the above purpose. Because IAM roles must be uniquely named in each account, if you create this role during your testing, be sure to delete it before executing the State Machine. 9 | 2. Think about all the different S3 actions that would enable object read access to a bucket (http://docs.aws.amazon.com/IAM/latest/UserGuide/list_s3.html). Limit your rule to evaluate Bucket policies, ACLs are out of scope. 10 | 11 | Region| Launch 12 | ------|----- 13 | EU (Ireland) | [![Launch Module 5 in eu-west-1](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/cloudformation-launch-stack-button.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=ConfigRules-Module-5-S3-Bucket-Policy-Whitelist&templateURL=https://s3.amazonaws.com/config-rules-workshop-eu-west-1/module-5/template.yml) 14 | -------------------------------------------------------------------------------- /Workshop-Rules/4-Overlapping-VPC-IP-Ranges/compliant-test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":{\"changedProperties\":{},\"changeType\":\"CREATE\"},\"configurationItem\":{\"relatedEvents\":[\"813ccb8b-3c59-488e-a344-51e5c7abec0b\"],\"relationships\":[{\"resourceId\":\"acl-09459e6f\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::NetworkAcl\",\"name\":\"Contains NetworkAcl\"},{\"resourceId\":\"rtb-b39cecd5\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::RouteTable\",\"name\":\"Contains RouteTable\"},{\"resourceId\":\"sg-123456\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::SecurityGroup\",\"name\":\"Contains SecurityGroup\"}],\"configuration\":{\"cidrBlock\":\"10.32.0.0/16\",\"dhcpOptionsId\":\"dopt-2e7f674c\",\"state\":\"available\",\"vpcId\":\"vpc-123456\",\"instanceTenancy\":\"default\",\"ipv6CidrBlockAssociationSet\":[],\"cidrBlockAssociationSet\":[{\"associationId\":\"vpc-cidr-assoc-87f4a1ef\",\"cidrBlock\":\"10.32.0.0/16\",\"cidrBlockState\":{\"state\":\"associated\",\"statusMessage\":null}}],\"isDefault\":false,\"tags\":[]},\"supplementaryConfiguration\":{},\"tags\":{},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-22T00:14:08.596Z\",\"configurationStateId\":1511309648596,\"awsAccountId\":\"123456789012\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::EC2::VPC\",\"resourceId\":\"vpc-123456\",\"resourceName\":null,\"ARN\":\"arn:aws:ec2:eu-west-1:123456789012:vpc/vpc-123456\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Multiple Availability Zones\",\"configurationStateMd5Hash\":\"17e2a3193302773ed54fa5ee8e5ac2d2\",\"resourceCreationTime\":null},\"notificationCreationTime\":\"2017-11-22T00:14:09.636Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{\"onPremNetworks\":\"10.218.0.0/24,10.218.1.0/24\"}", 5 | "resultToken": "test", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::123456789012:role/service-role/config-role-eu-west-1", 8 | "configRuleArn": "arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-12345", 9 | "configRuleName": "Module-4-Rule", 10 | "configRuleId": "config-rule-utkdqy", 11 | "accountId": "123456789012", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/4-Overlapping-VPC-IP-Ranges/noncompliant-test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":{\"changedProperties\":{},\"changeType\":\"CREATE\"},\"configurationItem\":{\"relatedEvents\":[\"813ccb8b-3c59-488e-a344-51e5c7abec0b\"],\"relationships\":[{\"resourceId\":\"acl-09459e6f\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::NetworkAcl\",\"name\":\"Contains NetworkAcl\"},{\"resourceId\":\"rtb-b39cecd5\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::RouteTable\",\"name\":\"Contains RouteTable\"},{\"resourceId\":\"sg-123456\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::SecurityGroup\",\"name\":\"Contains SecurityGroup\"}],\"configuration\":{\"cidrBlock\":\"10.32.0.0/16\",\"dhcpOptionsId\":\"dopt-2e7f674c\",\"state\":\"available\",\"vpcId\":\"vpc-123456\",\"instanceTenancy\":\"default\",\"ipv6CidrBlockAssociationSet\":[],\"cidrBlockAssociationSet\":[{\"associationId\":\"vpc-cidr-assoc-87f4a1ef\",\"cidrBlock\":\"10.32.0.0/16\",\"cidrBlockState\":{\"state\":\"associated\",\"statusMessage\":null}}],\"isDefault\":false,\"tags\":[]},\"supplementaryConfiguration\":{},\"tags\":{},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-22T00:14:08.596Z\",\"configurationStateId\":1511309648596,\"awsAccountId\":\"123456789012\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::EC2::VPC\",\"resourceId\":\"vpc-123456\",\"resourceName\":null,\"ARN\":\"arn:aws:ec2:eu-west-1:123456789012:vpc/vpc-123456\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Multiple Availability Zones\",\"configurationStateMd5Hash\":\"17e2a3193302773ed54fa5ee8e5ac2d2\",\"resourceCreationTime\":null},\"notificationCreationTime\":\"2017-11-22T00:14:09.636Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{\"onPremNetworks\":\"10.218.0.0/24,10.218.1.0/24\"}", 5 | "resultToken": "test", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::123456789012:role/service-role/config-role-eu-west-1", 8 | "configRuleArn": "arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-12345", 9 | "configRuleName": "Module-4-Rule", 10 | "configRuleId": "config-rule-utkdqy", 11 | "accountId": "123456789012", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/3-Private-VPC-No-IGW-Policy/compliant-test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":{\"changedProperties\":{},\"changeType\":\"CREATE\"},\"configurationItem\":{\"relatedEvents\":[\"f551241d-83b0-409b-a584-aa91894beb35\"],\"relationships\":[{\"resourceId\":\"acl-9178a3f7\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::NetworkAcl\",\"name\":\"Contains NetworkAcl\"},{\"resourceId\":\"rtb-ec80f08a\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::RouteTable\",\"name\":\"Contains RouteTable\"},{\"resourceId\":\"sg-8d0685f6\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::SecurityGroup\",\"name\":\"Contains SecurityGroup\"}],\"configuration\":{\"cidrBlock\":\"10.33.0.0/16\",\"dhcpOptionsId\":\"dopt-2e7f674c\",\"state\":\"available\",\"vpcId\":\"vpc-123455678\",\"instanceTenancy\":\"default\",\"ipv6CidrBlockAssociationSet\":[],\"cidrBlockAssociationSet\":[{\"associationId\":\"vpc-cidr-assoc-a4fbaecc\",\"cidrBlock\":\"10.33.0.0/16\",\"cidrBlockState\":{\"state\":\"associated\",\"statusMessage\":null}}],\"isDefault\":false,\"tags\":[{\"key\":\"private\",\"value\":\"true\"}]},\"supplementaryConfiguration\":{},\"tags\":{\"private\":\"true\"},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-22T00:47:07.943Z\",\"configurationStateId\":1511311627943,\"awsAccountId\":\"123456789012\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::EC2::VPC\",\"resourceId\":\"vpc-123455678\",\"resourceName\":null,\"ARN\":\"arn:aws:ec2:eu-west-1:123456789012:vpc/vpc-123455678\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Multiple Availability Zones\",\"configurationStateMd5Hash\":\"30ecdda01b04714d951412909d2565db\",\"resourceCreationTime\":null},\"notificationCreationTime\":\"2017-11-22T00:47:08.493Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{}", 5 | "resultToken": "test", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::123456789012:role/service-role/config-role-eu-west-1", 8 | "configRuleArn": "arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-123445", 9 | "configRuleName": "vpc-mod-3-rule", 10 | "configRuleId": "config-rule-123445", 11 | "accountId": "123456789012", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/2-S3-Version-Lifecyle-Policies/noncompliant_test_event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version":"1.0", 3 | "invokingEvent":"{\"configurationItemDiff\":null,\"configurationItem\":{\"relatedEvents\":[],\"relationships\":[],\"configuration\":{\"name\":\"test-bucket-12345\",\"owner\":{\"displayName\":\"username\",\"id\":\"26313a221d5c79fe9fce059648986b895e5595fc93b3d8470da3e5e0fc675f54\"},\"creationDate\":\"2017-10-03T03:40:43.000Z\"},\"supplementaryConfiguration\":{\"AccessControlList\":\"{\\\"grantSet\\\":null,\\\"grantList\\\":[{\\\"grantee\\\":{\\\"id\\\":\\\"26313a221d5c79fe9fce059648986b895e5595fc93b3d8470da3e5e0fc675f54\\\",\\\"displayName\\\":null},\\\"permission\\\":\\\"FullControl\\\"}],\\\"owner\\\":{\\\"displayName\\\":null,\\\"id\\\":\\\"26313a221d5c79fe9fce059648986b895e5595fc93b3d8470da3e5e0fc675f54\\\"},\\\"isRequesterCharged\\\":false}\",\"BucketAccelerateConfiguration\":{\"status\":null},\"BucketLoggingConfiguration\":{\"destinationBucketName\":null,\"logFilePrefix\":null},\"BucketNotificationConfiguration\":{\"configurations\":{}},\"BucketPolicy\":{\"policyText\":null},\"BucketVersioningConfiguration\":{\"status\":\"Off\",\"isMfaDeleteEnabled\":null},\"IsRequesterPaysEnabled\":false},\"tags\":{},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-10-03T03:59:31.349Z\",\"configurationStateId\":1507003171349,\"awsAccountId\":\"999999999999\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::S3::Bucket\",\"resourceId\":\"account-config-test\",\"resourceName\":\"test-bucket-12345\",\"ARN\":\"arn:aws:s3:::account-config-test\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Regional\",\"configurationStateMd5Hash\":\"3dcc36405dddacc1a10fba7f7caebd8f\",\"resourceCreationTime\":\"2017-10-03T03:40:43.000Z\"},\"notificationCreationTime\":\"2017-11-16T15:59:15.004Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters":"{}", 5 | "resultToken":"testToken", 6 | "eventLeftScope":false, 7 | "executionRoleArn":"arn:aws:iam::999999999999:role/service-role/config-role-eu-west-1", 8 | "configRuleArn":"arn:aws:config:eu-west-1:999999999999:config-rule/config-rule-cgy1ye", 9 | "configRuleName":"S3-LifecyclePolicy", 10 | "configRuleId":"config-rule-cgy1ye", 11 | "accountId":"999999999999", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/3-Private-VPC-No-IGW-Policy/noncompliant-test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":{\"changedProperties\":{},\"changeType\":\"CREATE\"},\"configurationItem\":{\"relatedEvents\":[\"3d17af67-cf7c-473d-bdae-23e8b9dc09fa\"],\"relationships\":[{\"resourceId\":\"acl-ca6bb0ac\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::NetworkAcl\",\"name\":\"Contains NetworkAcl\"},{\"resourceId\":\"igw-dce41abb\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::InternetGateway\",\"name\":\"Is attached to InternetGateway\"},{\"resourceId\":\"rtb-12345\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::RouteTable\",\"name\":\"Contains RouteTable\"},{\"resourceId\":\"sg-1234456\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::SecurityGroup\",\"name\":\"Contains SecurityGroup\"}],\"configuration\":{\"cidrBlock\":\"10.217.0.0/16\",\"dhcpOptionsId\":\"dopt-2e7f674c\",\"state\":\"available\",\"vpcId\":\"vpc-123445\",\"instanceTenancy\":\"default\",\"ipv6CidrBlockAssociationSet\":[],\"cidrBlockAssociationSet\":[{\"associationId\":\"vpc-cidr-assoc-94faaffc\",\"cidrBlock\":\"10.217.0.0/16\",\"cidrBlockState\":{\"state\":\"associated\",\"statusMessage\":null}}],\"isDefault\":false,\"tags\":[{\"key\":\"private\",\"value\":\"true\"}]},\"supplementaryConfiguration\":{},\"tags\":{\"private\":\"true\"},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-22T00:46:58.684Z\",\"configurationStateId\":1511311618684,\"awsAccountId\":\"123456789012\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::EC2::VPC\",\"resourceId\":\"vpc-123445\",\"resourceName\":null,\"ARN\":\"arn:aws:ec2:eu-west-1:123456789012:vpc/vpc-123445\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Multiple Availability Zones\",\"configurationStateMd5Hash\":\"7918933f2ec0054f6075d097abe74694\",\"resourceCreationTime\":null},\"notificationCreationTime\":\"2017-11-22T00:46:59.585Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{}", 5 | "resultToken": "test", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::123456789012:role/service-role/config-role-eu-west-1", 8 | "configRuleArn": "arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-123445", 9 | "configRuleName": "vpc-mod-3-rule", 10 | "configRuleId": "config-rule-123445", 11 | "accountId": "123456789012", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/2-S3-Version-Lifecyle-Policies/README.md: -------------------------------------------------------------------------------- 1 | # S3 Lifecycle Policy Compliance 2 | Completion of this rule will require you to create a Lambda function and custom Config Rule using the yet-to-be complete code provided in [`rule.py`](./rule.py). The method and process of creating a new Lambda function and new custom Config Rule will mirror Module 1, no additional or different permissions are required. All that will differ are the code for the Lambda function, and the configuration of the Config Rule. 3 | 4 | ## The Purpose of This Rule 5 | While the Config Rule in Module 1 was focused on security/compliance, you can also use Config Rules as a mechanism for enforcing organizational policies that are unrelated to security/compliance. Cost Savings is another worthy pursuit for building automated compliance evaluations with Config Rules. 6 | 7 | This rule focuses on driving cost savings, and data retention with Amazon S3. S3 allows you to create Lifecycle Policies so that the data you store is automatically moved between storage classes. **This rule should ensure that all buckets have a lifecylce policy to migrate older data to Amazon Glacier.** This enables you to realize cost savings while adhering to the data access requirements for the data you've stored. S3 also enables the use of versioning so that previous versions of objects are retained if existing data is deleted or overwritten. This enables additional confidence that data will not be unintentionally deleted or changed, and that previous versions of objects are retained should they need to be retrieved/restored. **This rule should also ensure that all S3 buckets have a versioning policy in place.** 8 | 9 | ### Hints for Completion 10 | 1. Remember to use the provided sample events to test your function rule. ...The test events may also provide a good reference for the evaluations your code should perform. 11 | 2. Take a look at the previous module for how the code was arranged, you might be able to use it as a reference replace the missing code! 12 | 13 | Region| Launch 14 | ------|----- 15 | EU (Ireland) | [![Launch Module 2 in eu-west-1](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/cloudformation-launch-stack-button.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=ConfigRules-Module-2-S3-Bucket-Lifecycle-and-Verisoning&templateURL=https://s3.amazonaws.com/config-rules-workshop-eu-west-1/module-2/template.yml) 16 | -------------------------------------------------------------------------------- /Workshop-Rules/4-Overlapping-VPC-IP-Ranges/rule.py: -------------------------------------------------------------------------------- 1 | # Import libraries - Lambda will require ipaddress to be uploaded 2 | 3 | import json 4 | import ipaddress 5 | import logging 6 | import boto3 7 | 8 | config_service = boto3.client('##CHANGED##') 9 | logger = logging.getLogger() 10 | logger.setLevel(logging.INFO) 11 | 12 | # This function uses the ipaddress library to compre the 'onprem' list with AWS Account VPC's 13 | def cidrcheck(net1, net2): 14 | noOverlaps = True 15 | prem = map(str, net1) 16 | for i in prem: 17 | n1 = ipaddress.IPv4Network(i, strict=False) 18 | n2 = ipaddress.IPv4Network(net2) 19 | if ##CHANGED##.overlaps(##CHANGED##): 20 | logger.info("Found Overlap!") 21 | ##LINE_REMOVED: what variable should be set, indicated that an overlap was found?## 22 | 23 | return noOverlaps 24 | 25 | # Lambda Function Handler filename.handler - 26 | # Creates AWS Config Rule connection and parses event object to find VPC CIDR's 27 | def lambda_handler(event, context): 28 | event_item = json.loads(event['invokingEvent']) 29 | config_item = event_item['configurationItem'] 30 | resource_type = config_item['resourceType'] 31 | 32 | logger.info("Event: " + json.dumps(event)) 33 | 34 | # Make sure config_item is not deleted and of the correct type 35 | if config_item['configurationItemStatus'] == 'ResourceDeleted' or \ 36 | resource_type != '##CHANGED##': 37 | return 38 | 39 | # Setup the Evaluation object and set its variables to the event object 40 | evaluation = { 41 | 'ComplianceResourceType': config_item['resourceType'], 42 | 'ComplianceResourceId': config_item['resourceId'], 43 | 'ComplianceType': 'NON_COMPLIANT', 44 | 'OrderingTimestamp': config_item['configurationItemCaptureTime'] 45 | } 46 | # Execute evaluation 47 | rules_item = json.loads(event['ruleParameters']) 48 | onprem = rules_item['##CHANGED##'].split('##CHANGED##') 49 | cidr = config_item['configuration']['##CHANGED##'] 50 | 51 | result = ##LINED_REMOVED: where are the networks checked for an overlap?## 52 | 53 | if result is True: 54 | evaluation['ComplianceType'] = 'COMPLIANT' 55 | else: 56 | evaluation['ComplianceType'] = 'NON_COMPLIANT' 57 | # Return the evaluation status to the AWS Config Rule service 58 | if "dryRun" not in event: 59 | config_service.put_evaluations( 60 | Evaluations=[evaluation], ResultToken=event['resultToken'] 61 | ) 62 | 63 | return evaluation['ComplianceType'] 64 | -------------------------------------------------------------------------------- /Workshop-Rules/5-S3-Bucket-Policy-Read-Access/rule.py: -------------------------------------------------------------------------------- 1 | import ##CHANGED## 2 | import ##CHANGED## 3 | import logging 4 | 5 | 6 | APPLICABLE_RESOURCES = ["##CHANGED##"] 7 | config = boto3.client("##CHANGED##") 8 | logger = logging.getLogger() 9 | logger.setLevel(logging.INFO) 10 | 11 | def evaluate_compliance(invoking_event, whitelisted_role): 12 | 13 | if invoking_event['configurationItem']['resourceType'] not in APPLICABLE_RESOURCES: 14 | return "##CHANGED##" 15 | 16 | if invoking_event['configurationItem']['configurationItemStatus'] == "ResourceDeleted": 17 | return "##CHANGED##" 18 | 19 | compliance_status = "COMPLIANT" 20 | 21 | configuration_diff = invoking_event['configurationItemDiff'] 22 | account_id = ##LINED_REMOVED: where can this be retrieved from?## 23 | policy_text = ##LINE_REMOVED: where can this be retrieved from?## 24 | 25 | #Convert the string policy above to JSON 26 | b = bytes(policy_text, encoding='ascii') 27 | policy = json.loads(b.decode('unicode-escape')) 28 | logger.info("POLICY: " + json.dumps(policy)) 29 | 30 | if 'Statement' in policy: 31 | for statement in policy['##CHANGED##']: 32 | if 'Action' in statement and 'Principal' in statement: 33 | if ##LINE_REMOVED: does this Action give permission to perform read actions?##: 34 | if 'AWS' not in statement['Principal'] or statement['Principal']['AWS'] != ##LINE_REMOVED: what is the principal value allowed to be?##: 35 | compliance_status = "NON_COMPLIANT" 36 | 37 | return compliance_status 38 | 39 | 40 | def lambda_handler(event, context): 41 | 42 | logger.info("Event: " + json.dumps(event)) 43 | 44 | invoking_event = json.loads(event["invokingEvent"]) 45 | rule_parameters = json.loads(event["ruleParameters"]) 46 | whitelisted_role = rule_parameters["##CHANGED##"] 47 | configuration_item = invoking_event['configurationItem'] 48 | if not invoking_event['##CHANGED##']: 49 | return "Nothing to check, resource didn't change." 50 | 51 | result_token = "No token found." 52 | if "resultToken" in event: 53 | result_token = event["resultToken"] 54 | 55 | 56 | compliance = evaluate_compliance(invoking_event, whitelisted_role) 57 | 58 | evaluation = { 59 | ##LINES_REMOVED: how do we create the evaluation object that Config requires?## 60 | } 61 | 62 | if "dryRun" not in event: 63 | ##LINES_REMOVED: how do we inform config that this evlauation has completed?## 64 | 65 | return evaluation['ComplianceType'] 66 | -------------------------------------------------------------------------------- /Workshop-Rules/3-Private-VPC-No-IGW-Policy/README.md: -------------------------------------------------------------------------------- 1 | # No IGWs for Private VPCs 2 | Completion of this rule will require you to create a Lambda function and custom Config Rule using the yet-to-be complete code provided in [`rule.py`](./rule.py). The method and process of creating a new Lambda function and new custom Config Rule will mirror Module 1. This Lambda function *will* require different permissions in the policy for its IAM role, and it's code requires completion as well. 3 | 4 | ## The Purpose of This Rule 5 | Whether it be to build internal applications whose audiences should always be on a private network, or to reduce the attack surface of an application that stores highly sensitive data, not all applications need access to the Internet. This Config Rule's purpose is to ensure that VPCs that have a tag key equal to `private` do not have an Internet Gateway (IGW) attached to them. If a VPC is found to both contain a tag key of `private` and an IGW is attached, it is noncompliant. 6 | 7 | ### Hints for Completion 8 | 1. Because this rule requires a call to another AWS service for evaluation, **test events provided are inadequate on their own**. They have stubbed/non-existent VPCs listed within them for evaluation. In order for the rule calls to other services to be successful, you will need to create compliant/noncompliant VPCs within the region you are testing (noncompliance means an IGW attached to a VPC tagged with the key `private`). Then replace the false VPC Ids of the provided events with the appropriate/existing VPC Ids for each respective test. 9 | 2. Remember to use the provided sample events to test your function rule. ...The test events may also provide a good reference for the evaluations your code should perform. 10 | 3. While AWS Config provides detailed configuration information for many resources, it may not provide all of the details you need to fully evaluate a resource within the event object passed to your Lambda function. For cases like this, you may want to use the resource information that *is* passed within the event object, and then make request/s to other AWS services to gather more data to make a full evaluation. 11 | 4. When other AWS services need to be called by your Lambda function, remember to take those actions into account when creating an IAM role for your function. 12 | 13 | Region| Launch 14 | ------|----- 15 | EU (Ireland) | [![Launch Module 3 in eu-west-1](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/cloudformation-launch-stack-button.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=ConfigRules-Module-3-No-IGW-For-Private-VPCs&templateURL=https://s3.amazonaws.com/config-rules-workshop-eu-west-1/module-3/template.yml) 16 | -------------------------------------------------------------------------------- /Workshop-Rules/5-S3-Bucket-Policy-Read-Access/compliant-test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":{\"changedProperties\":{},\"changeType\":\"CREATE\"},\"configurationItem\":{\"relatedEvents\":[\"f62662c2-cb9d-4ecc-9c91-352cf9684724\"],\"relationships\":[],\"configuration\":{\"name\":\"config-rules-workshop-compliant-12345\",\"owner\":{\"displayName\":\"xxxxx\",\"id\":\"xxxxxxxxx\"},\"creationDate\":\"2017-11-21T23:57:02.000Z\"},\"supplementaryConfiguration\":{\"AccessControlList\":\"{\\\"grantSet\\\":null,\\\"grantList\\\":[{\\\"grantee\\\":{\\\"id\\\":\\\"e0ec8a08ea9a3df719b874216ea633c8fdcff3fca5a173ae96c7adacd83f119e\\\",\\\"displayName\\\":\\\"xxxxxxx\\\"},\\\"permission\\\":\\\"FullControl\\\"}],\\\"owner\\\":{\\\"displayName\\\":\\\"xxxxxxx\\\",\\\"id\\\":\\\"xxxxxxxx\\\"},\\\"isRequesterCharged\\\":false}\",\"BucketAccelerateConfiguration\":{\"status\":null},\"BucketLifecycleConfiguration\":{\"rules\":[{\"id\":\"Mzg2ZjNlNmQtMGE1MC00ZjAzLTllZjktZGY1ZmQ4N2ZlZGMz\",\"prefix\":\"\",\"status\":\"Enabled\",\"filter\":null,\"expirationInDays\":-1,\"expiredObjectDeleteMarker\":false,\"noncurrentVersionExpirationInDays\":-1,\"expirationDate\":null,\"transitions\":null,\"noncurrentVersionTransitions\":[{\"days\":1,\"storageClass\":\"GLACIER\"}],\"abortIncompleteMultipartUpload\":null}]},\"BucketLoggingConfiguration\":{\"destinationBucketName\":null,\"logFilePrefix\":null},\"BucketNotificationConfiguration\":{\"configurations\":{}},\"BucketPolicy\":{\"policyText\":\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Sid\\\":\\\"\\\",\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":{\\\"AWS\\\":\\\"arn:aws:iam::REPLACE WITH YOUR ACCOUNT ID:role/ConfigRulesWorkshopTestRole\\\"},\\\"Action\\\":\\\"s3:*\\\",\\\"Resource\\\":\\\"arn:aws:s3:::config-rules-workshop-compliant-123455/*\\\"}]}\"},\"BucketVersioningConfiguration\":{\"status\":\"Enabled\",\"isMfaDeleteEnabled\":null},\"IsRequesterPaysEnabled\":false},\"tags\":{},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-21T23:59:13.741Z\",\"configurationStateId\":1511308753741,\"awsAccountId\":\"REPLACE WITH YOUR ACCOUNT ID\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::S3::Bucket\",\"resourceId\":\"config-rules-workshop-compliant-12345\",\"resourceName\":\"config-rules-workshop-compliant-12345\",\"ARN\":\"arn:aws:s3:::config-rules-workshop-compliant-12345\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Regional\",\"configurationStateMd5Hash\":\"07f2ff519f51748e480a028cc65185ad\",\"resourceCreationTime\":\"2017-11-21T23:57:02.000Z\"},\"notificationCreationTime\":\"2017-11-21T23:59:13.807Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{\"whitelistedRole\":\"ConfigRulesWorkshopTestRole\"}", 5 | "resultToken": "test", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::REPLACE WITH YOUR ACCOUNT ID:role/service-role/config-role-eu-west-1", 8 | "configRuleArn": "arn:aws:config:eu-west-1:REPLACE WITH YOUR ACCOUNT ID:config-rule/config-rule-12345", 9 | "configRuleName": "Module5Rule", 10 | "configRuleId": "config-rule-12345", 11 | "accountId": "REPLACE WITH YOUR ACCOUNT ID", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/5-S3-Bucket-Policy-Read-Access/noncompliant-test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":{\"changedProperties\":{},\"changeType\":\"CREATE\"},\"configurationItem\":{\"relatedEvents\":[\"f62662c2-cb9d-4ecc-9c91-352cf9684724\"],\"relationships\":[],\"configuration\":{\"name\":\"config-rules-workshop-compliant-12345\",\"owner\":{\"displayName\":\"xxxxx\",\"id\":\"xxxxxxxxx\"},\"creationDate\":\"2017-11-21T23:57:02.000Z\"},\"supplementaryConfiguration\":{\"AccessControlList\":\"{\\\"grantSet\\\":null,\\\"grantList\\\":[{\\\"grantee\\\":{\\\"id\\\":\\\"e0ec8a08ea9a3df719b874216ea633c8fdcff3fca5a173ae96c7adacd83f119e\\\",\\\"displayName\\\":\\\"xxxxxxx\\\"},\\\"permission\\\":\\\"FullControl\\\"}],\\\"owner\\\":{\\\"displayName\\\":\\\"xxxxxxx\\\",\\\"id\\\":\\\"xxxxxxxx\\\"},\\\"isRequesterCharged\\\":false}\",\"BucketAccelerateConfiguration\":{\"status\":null},\"BucketLifecycleConfiguration\":{\"rules\":[{\"id\":\"Mzg2ZjNlNmQtMGE1MC00ZjAzLTllZjktZGY1ZmQ4N2ZlZGMz\",\"prefix\":\"\",\"status\":\"Enabled\",\"filter\":null,\"expirationInDays\":-1,\"expiredObjectDeleteMarker\":false,\"noncurrentVersionExpirationInDays\":-1,\"expirationDate\":null,\"transitions\":null,\"noncurrentVersionTransitions\":[{\"days\":1,\"storageClass\":\"GLACIER\"}],\"abortIncompleteMultipartUpload\":null}]},\"BucketLoggingConfiguration\":{\"destinationBucketName\":null,\"logFilePrefix\":null},\"BucketNotificationConfiguration\":{\"configurations\":{}},\"BucketPolicy\":{\"policyText\":\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Sid\\\":\\\"\\\",\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":{\\\"AWS\\\":\\\"arn:aws:iam::REPLACE WITH YOUR ACCOUNT ID:role/ConfigRulesWorkshopTestRole\\\"},\\\"Action\\\":\\\"s3:*\\\",\\\"Resource\\\":\\\"arn:aws:s3:::config-rules-workshop-compliant-123455/*\\\"}]}\"},\"BucketVersioningConfiguration\":{\"status\":\"Enabled\",\"isMfaDeleteEnabled\":null},\"IsRequesterPaysEnabled\":false},\"tags\":{},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-21T23:59:13.741Z\",\"configurationStateId\":1511308753741,\"awsAccountId\":\"REPLACE WITH YOUR ACCOUNT ID\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::S3::Bucket\",\"resourceId\":\"config-rules-workshop-compliant-12345\",\"resourceName\":\"config-rules-workshop-compliant-12345\",\"ARN\":\"arn:aws:s3:::config-rules-workshop-compliant-12345\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Regional\",\"configurationStateMd5Hash\":\"07f2ff519f51748e480a028cc65185ad\",\"resourceCreationTime\":\"2017-11-21T23:57:02.000Z\"},\"notificationCreationTime\":\"2017-11-21T23:59:13.807Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{\"whitelistedRole\":\"ConfigRulesWorkshopTestRole\"}", 5 | "resultToken": "test", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::REPLACE WITH YOUR ACCOUNT ID:role/service-role/config-role-eu-west-1", 8 | "configRuleArn": "arn:aws:config:eu-west-1:REPLACE WITH YOUR ACCOUNT ID:config-rule/config-rule-12345", 9 | "configRuleName": "Module5Rule", 10 | "configRuleId": "config-rule-12345", 11 | "accountId": "REPLACE WITH YOUR ACCOUNT ID", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/2-S3-Version-Lifecyle-Policies/rule.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import json 3 | import logging 4 | 5 | log = logging.getLogger() 6 | log.setLevel(logging.DEBUG) 7 | APPLICABLE_RESOURCES = ["AWS::S3::Bucket"] 8 | config = boto3.client('config') 9 | 10 | 11 | def evaluate_compliance(configuration_item): 12 | if configuration_item["resourceType"] not in APPLICABLE_RESOURCES: 13 | return { 14 | "compliance_type": "NOT_APPLICABLE", 15 | "annotation": "The rule doesn't apply to resources of type " + 16 | configuration_item["resourceType"] + "." 17 | } 18 | 19 | if configuration_item['configurationItemStatus'] == "ResourceDeleted": 20 | return { 21 | "compliance_type": "NOT_APPLICABLE", 22 | "annotation": "The configurationItem was deleted " + 23 | "and therefore cannot be validated" 24 | } 25 | 26 | bucket_verConfig = configuration_item["##CHANGED##"].get("##CHANGED##") 27 | bucket_lifeConfig = configuration_item["##CHANGED##"].get("##CHANGED##") 28 | 29 | if bucket_verConfig is None: 30 | return { 31 | "compliance_type": "NON_COMPLIANT", 32 | "annotation": 'Bucket does not contain a Versioning Configuration.' 33 | } 34 | else: 35 | if bucket_verConfig['##CHANGED##'] == "Off": 36 | return { 37 | "compliance_type": "NON_COMPLIANT", 38 | "annotation": 'Bucket Versioning is disabled.' 39 | } 40 | 41 | if bucket_lifeConfig is None: 42 | return { 43 | "compliance_type": "NON_COMPLIANT", 44 | "annotation": 'Bucket does not contain a Lifecycle Management Policy' 45 | } 46 | 47 | if (bucket_lifeConfig['rules'][0]['noncurrentVersionTransitions'][0]['days'] > 0) and \ 48 | (bucket_lifeConfig['rules'][0]['noncurrentVersionTransitions'][0]['storageClass'] == "##CHANGED##"): 49 | return { 50 | "compliance_type": "COMPLIANT", 51 | "annotation": 'Bucket Versioning is enabled and Lifecycle policy is set to archive older versions to Glacier' 52 | } 53 | else: 54 | return { 55 | "compliance_type": "NON_COMPLIANT", 56 | "annotation": 'Bucket Lifecycle policy is not configured to specification.' 57 | } 58 | 59 | 60 | def lambda_handler(event, context): 61 | log.debug('Event %s', event) 62 | invoking_event = json.loads(event['##CHANGED##']) 63 | configuration_item = invoking_event['##CHANGED##'] 64 | compliance = ##REMOVED## 65 | evaluation = { 66 | 'ComplianceResourceType': invoking_event['configurationItem']['resourceType'], 67 | 'ComplianceResourceId': invoking_event['configurationItem']['resourceId'], 68 | 'ComplianceType': compliance["compliance_type"], 69 | "Annotation": compliance["annotation"], 70 | 'OrderingTimestamp': invoking_event['configurationItem']['configurationItemCaptureTime'] 71 | } 72 | 73 | log.debug('===== Compliance Status: %s', json.dumps(evaluation)) 74 | if "dryRun" not in event: 75 | config.put_evaluations( 76 | Evaluations=[evaluation], 77 | ResultToken=event['resultToken'] 78 | ) 79 | 80 | return evaluation['ComplianceType'] 81 | -------------------------------------------------------------------------------- /Workshop-Rules/3-Private-VPC-No-IGW-Policy/rule.py: -------------------------------------------------------------------------------- 1 | # Import libraries - Lambda will require ipaddress to be uploaded 2 | 3 | import json 4 | import logging 5 | import boto3 6 | 7 | config_service = boto3.client('config') 8 | ec2_service = boto3.client('##CHANGED##'); 9 | 10 | logger = logging.getLogger() 11 | logger.setLevel(logging.INFO) 12 | 13 | # This is where it's determined whether the resource is compliant or not. 14 | def evaluate_compliance(configuration_item): 15 | logger.info('CONFIGURATION: ' + json.dumps(configuration_item['configuration'])) 16 | 17 | vpc_id = configuration_item['configuration']['##CHANGED##'] 18 | logger.info('VPC_ID: ' + vpc_id) 19 | 20 | tags = configuration_item['configuration']['tags'] 21 | logger.info('TAGS: ' + json.dumps(tags)) 22 | 23 | ##checks if the list of tags includes a tag with a key set to private 24 | tags_private = list(filter((lambda x: x['key'] == '##CHANGED##'), tags)) 25 | logger.info('TAGS_PRIVATE: ' + json.dumps(tags_private)) 26 | 27 | if tags_private: 28 | tag_private = tags_private[0] 29 | logger.info('TAG_PRIVATE: ' + json.dumps(tag_private)) 30 | 31 | if tag_private['value'] == 'true': 32 | response = ec2_service.##CHANGED: what ec2 boto3 operation needs to be called to gather existing IGWs?##( 33 | Filters = [ 34 | { 35 | 'Name': 'attachment.vpc-id', 36 | 'Values': [ ##CHANGED: what parameter will filter the service response to just check if IGWs are attached to the VPC being evaluated?## ] 37 | } 38 | ] 39 | ) 40 | logger.info('response: ' + json.dumps(response)) 41 | 42 | ##check if the VPC does have an IGW attached. 43 | if response['##CHANGED: the presence of what non-empty member in the response will indicate if an IGW is attached?##']: 44 | return False 45 | 46 | logger.info('RESULT: True') 47 | return True 48 | 49 | # Lambda Function Handler filename.handler - 50 | # Creates AWS Config Rule connection and parses event object to find VPC CIDR's 51 | def lambda_handler(event, context): 52 | 53 | logger.info("Event: " + json.dumps(event)) 54 | 55 | event_item = json.loads(event['invokingEvent']) 56 | config_item = event_item['configurationItem'] 57 | resource_type = config_item['resourceType'] 58 | 59 | logger.info(json.dumps(event_item)) 60 | 61 | 62 | # Make sure config_item is not deleted and of the correct type 63 | if config_item['configurationItemStatus'] == 'ResourceDeleted' or \ 64 | resource_type != 'AWS::EC2::VPC': 65 | return "NOT_APPLICABLE" 66 | 67 | # Setup the Evaluation object and set its variables to the event object 68 | evaluation = { 69 | 'ComplianceResourceType': config_item['resourceType'], 70 | 'ComplianceResourceId': config_item['resourceId'], 71 | 'ComplianceType': 'NON_COMPLIANT', 72 | 'OrderingTimestamp': config_item['configurationItemCaptureTime'] 73 | } 74 | # Execute evaluation 75 | result = evaluate_compliance(config_item) 76 | 77 | if result is True: 78 | evaluation['ComplianceType'] = '##CHANGED##' 79 | else: 80 | evaluation['ComplianceType'] = '##CHANGED##' 81 | # Return the evaluation status to the AWS Config Rule service 82 | if "dryRun" not in event: 83 | config_service.put_evaluations( 84 | Evaluations=[##CHANGED##], ResultToken=event['resultToken'] 85 | ) 86 | return evaluation['ComplianceType'] 87 | -------------------------------------------------------------------------------- /Workshop-Rules/2-S3-Version-Lifecyle-Policies/compliant_test_event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version":"1.0", 3 | "invokingEvent":"{\"configurationItemDiff\":{\"changedProperties\":{\"SupplementaryConfiguration.BucketVersioningConfiguration.Status\":{\"previousValue\":\"Off\",\"updatedValue\":\"Enabled\",\"changeType\":\"UPDATE\"},\"SupplementaryConfiguration.BucketLifecycleConfiguration\":{\"previousValue\":null,\"updatedValue\":{\"rules\":[{\"id\":\"M2JlYmE2NWUtMmU3ZS00ZWY2LWJiOWQtY2Y5MGZlY2I4NWJh\",\"prefix\":null,\"status\":\"Enabled\",\"filter\":{\"predicate\":{\"type\":\"LifecyclePrefixPredicate\",\"prefix\":\"\"}},\"expirationInDays\":-1,\"expiredObjectDeleteMarker\":false,\"noncurrentVersionExpirationInDays\":-1,\"expirationDate\":null,\"transitions\":null,\"noncurrentVersionTransitions\":[{\"days\":1,\"storageClass\":\"GLACIER\"}],\"abortIncompleteMultipartUpload\":null}]},\"changeType\":\"CREATE\"}},\"changeType\":\"UPDATE\"},\"configurationItem\":{\"relatedEvents\":[\"0132ecf5-395d-4441-a7d0-db909632f89a\"],\"relationships\":[],\"configuration\":{\"name\":\"account-test-cfn-template\",\"owner\":{\"displayName\":\"username\",\"id\":\"26313a221d5c79fe9fce059648986b895e5595fc93b3d8470da3e5e0fc675f54\"},\"creationDate\":\"2017-11-16T17:26:32.000Z\"},\"supplementaryConfiguration\":{\"AccessControlList\":\"{\\\"grantSet\\\":null,\\\"grantList\\\":[{\\\"grantee\\\":{\\\"id\\\":\\\"26313a221d5c79fe9fce059648986b895e5595fc93b3d8470da3e5e0fc675f54\\\",\\\"displayName\\\":null},\\\"permission\\\":\\\"FullControl\\\"}],\\\"owner\\\":{\\\"displayName\\\":null,\\\"id\\\":\\\"26313a221d5c79fe9fce059648986b895e5595fc93b3d8470da3e5e0fc675f54\\\"},\\\"isRequesterCharged\\\":false}\",\"BucketAccelerateConfiguration\":{\"status\":null},\"BucketLifecycleConfiguration\":{\"rules\":[{\"id\":\"M2JlYmE2NWUtMmU3ZS00ZWY2LWJiOWQtY2Y5MGZlY2I4NWJh\",\"prefix\":null,\"status\":\"Enabled\",\"filter\":{\"predicate\":{\"type\":\"LifecyclePrefixPredicate\",\"prefix\":\"\"}},\"expirationInDays\":-1,\"expiredObjectDeleteMarker\":false,\"noncurrentVersionExpirationInDays\":-1,\"expirationDate\":null,\"transitions\":null,\"noncurrentVersionTransitions\":[{\"days\":1,\"storageClass\":\"GLACIER\"}],\"abortIncompleteMultipartUpload\":null}]},\"BucketLoggingConfiguration\":{\"destinationBucketName\":null,\"logFilePrefix\":null},\"BucketNotificationConfiguration\":{\"configurations\":{}},\"BucketPolicy\":{\"policyText\":null},\"BucketTaggingConfiguration\":{\"tagSets\":[{\"tags\":{\"aws:cloudformation:stack-name\":\"CreateMyS3Bucket\",\"aws:cloudformation:logical-id\":\"NewS3Bucket\",\"aws:cloudformation:stack-id\":\"arn:aws:cloudformation:eu-west-1:999999999999:stack/CreateMyS3Bucket/47201cc0-caf3-11e7-afcb-50faf8c48cf2\"}}]},\"BucketVersioningConfiguration\":{\"status\":\"Enabled\",\"isMfaDeleteEnabled\":null},\"IsRequesterPaysEnabled\":false},\"tags\":{\"aws:cloudformation:stack-name\":\"CreateMyS3Bucket\",\"aws:cloudformation:logical-id\":\"NewS3Bucket\",\"aws:cloudformation:stack-id\":\"arn:aws:cloudformation:eu-west-1:999999999999:stack/CreateMyS3Bucket/47201cc0-caf3-11e7-afcb-50faf8c48cf2\"},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-16T17:56:27.135Z\",\"configurationStateId\":1510854987135,\"awsAccountId\":\"999999999999\",\"configurationItemStatus\":\"OK\",\"resourceType\":\"AWS::S3::Bucket\",\"resourceId\":\"account-test-cfn-template\",\"resourceName\":\"test-bucket-name-12345\",\"ARN\":\"arn:aws:s3:::test-bucket-name-12345\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Regional\",\"configurationStateMd5Hash\":\"b09a66f8bdf11f86329dbd021f830b3e\",\"resourceCreationTime\":\"2017-11-16T17:26:32.000Z\"},\"notificationCreationTime\":\"2017-11-16T17:56:27.215Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters":"{}", 5 | "resultToken":"TestToken", 6 | "eventLeftScope":false, 7 | "executionRoleArn":"arn:aws:iam::999999999999:role/service-role/config-role-eu-west-1", 8 | "configRuleArn":"arn:aws:config:eu-west-1:999999999999:config-rule/config-rule-12345", 9 | "configRuleName":"S3-LifecyclePolicy", 10 | "configRuleId":"config-rule-12345", 11 | "accountId":"999999999999", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/noncompliant_test_event.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "invokingEvent": "{\"configurationItemDiff\":{\"changedProperties\":{},\"changeType\":\"CREATE\"},\"configurationItem\":{\"relatedEvents\":[\"14f26631-54ab-4bb0-b774-31f0f858b738\"],\"relationships\":[{\"resourceId\":\"vpc-1234567\",\"resourceName\":null,\"resourceType\":\"AWS::EC2::VPC\",\"name\":\"Is contained in Vpc\"}],\"configuration\":{\"description\":\"This SG allows SSH to the world!\",\"groupName\":\"NON_COMPLIANT_SG_JYOSI\",\"ipPermissions\":[{\"fromPort\":22,\"ipProtocol\":\"tcp\",\"ipv6Ranges\":[],\"prefixListIds\":[],\"toPort\":22,\"userIdGroupPairs\":[],\"ipv4Ranges\":[{\"cidrIp\":\"0.0.0.0/0\"}],\"ipRanges\":[\"0.0.0.0/0\"]}],\"ownerId\":\"123456789012\",\"groupId\":\"sg-1231231\",\"ipPermissionsEgress\":[{\"ipProtocol\":\"-1\",\"ipv6Ranges\":[],\"prefixListIds\":[],\"userIdGroupPairs\":[],\"ipv4Ranges\":[{\"cidrIp\":\"0.0.0.0/0\"}],\"ipRanges\":[\"0.0.0.0/0\"]}],\"tags\":[],\"vpcId\":\"vpc-1234567\"},\"supplementaryConfiguration\":{},\"tags\":{},\"configurationItemVersion\":\"1.2\",\"configurationItemCaptureTime\":\"2017-11-25T03:40:28.907Z\",\"configurationStateId\":1511581228907,\"awsAccountId\":\"123456789012\",\"configurationItemStatus\":\"ResourceDiscovered\",\"resourceType\":\"AWS::EC2::SecurityGroup\",\"resourceId\":\"sg-1231231\",\"resourceName\":\"NON_COMPLIANT_SG_JYOSI\",\"ARN\":\"arn:aws:ec2:eu-west-1:123456789012:security-group/sg-1231231\",\"awsRegion\":\"eu-west-1\",\"availabilityZone\":\"Not Applicable\",\"configurationStateMd5Hash\":\"df0564a84fedb268cb951e55a8c84c03\",\"resourceCreationTime\":null},\"notificationCreationTime\":\"2017-11-25T03:40:29.368Z\",\"messageType\":\"ConfigurationItemChangeNotification\",\"recordVersion\":\"1.2\"}", 4 | "ruleParameters": "{\"ipAddress\":\"1.1.1.1/32\"}", 5 | "resultToken": "eyJlbmNyeXB0ZWREYXRhIjpbNSw5NCw0MiwxMDUsLTc5LC0xMDAsLTEwMSwxMTQsMTE0LDEyLDIwLDc4LC01LDEyNiwxMTYsLTEyMywyNiw0OCw4MSwtMTIsLTEyNCwtMjYsLTgsMzksMTI0LDQsMTA1LDU2LDEyNCwzNiwtOTgsLTE5LC0zOSwtMTksLTUyLDEwMywtMTIxLC03MCwxMDMsNiwtMzgsLTgxLDExMywxNCwtMzAsMiwtNTEsLTEzLDEyMSwtMTIsODksNjEsLTkyLC02OSwtNzIsLTMyLC0yNywtMTI0LDEyNywtMTIwLDEwNywtOTUsNzcsLTU4LC0zMSwtNjAsLTExMCwtODUsNDUsLTYsMTIxLDQ5LDM4LC0yNiwtMTA0LC0xMDMsLTEwOSwyMiw3MCwxMywtNzEsNTYsMywzNSwtMTA5LDQsMTAzLC03OCwtNzQsMCwxMDksMTEzLC05NywtMTAsMzksLTg2LDYyLDQ5LDQwLC0zNywtNDIsMTAxLDI3LDQ2LDYxLDEwOCwzMCw1NywtODcsMTA3LDcwLC01MywtMTI0LDQ1LDM5LC03NSw0OCwtNDAsLTY0LDcxLDExMiwxMjEsNTcsLTU3LC05MSw1LC02OCw0MSwtMTUsLTUzLDExOCwtNTUsNDgsNiwtOTQsLTQ1LC04MiwtMTEwLDExOCwxMTksODAsOTYsLTgxLDg0LDk3LDY0LDEwNCwtMTE4LC00LDMzLC0yNCwzMiwtNjYsNjgsMjcsLTM3LDcwLDU3LC02MywxMjAsOSwtMTIyLDUwLDkyLDEwMSwxMDcsLTQ3LC05Miw1OCwtMTEsMTEsNzMsLTIzLDc3LDMwLDU2LDUxLC04MiwxNiwzMywtNTksLTg4LDI1LC0xNiw1Myw1NCwtMzAsNTEsLTEwNyw5Nyw4NSwxMTAsLTEyNiwxMSwtNzksLTI0LDMxLC02OCwyMSwtMTA1LDIxLDEwNiwyMSwwLDc1LC00NSw1NywtNywtMTExLDkyLDMsLTI4LDg2LDgzLDExNiwtNjAsLTEsLTg4LDU1LC03MSwtNjQsLTQ5LC01NiwzNSwtMTIyLDcsMzIsLTc2LC0xMDUsNjcsLTY4LC0xMiw5OSwtODYsODEsLTc2LDMyLDEwNywyMSwzNiwtMjcsNTYsLTIzLDM4LC0xMTQsNDIsOTAsLTM4LC02MiwtMzAsLTQ3LDQxLDU1LDMwLC0xOSwtMzEsLTcwLC01NCwtODEsNDEsLTExMSwyMCwtNDgsODQsMjgsLTUyLDEyLDIwLDg3LDgxLC0xMjcsLTc5LC0xMDUsLTExOCwtNTQsMTE5LDg5LDUsLTY1LDM4LDgzLDE2LDEwOCwxNSwxMDYsMzIsOTksLTU4LDIsMTcsMiwtOTUsMTE2LC02NCwtNDYsLTMyLC01LDkzLDg3LC0yOSwzLC0zLDEyNSwyLDE4LC00NiwtMTcsLTIyLDE5LDkyLDEwMiw0OSwtOTQsMTEyLDYxLC0zOSw1MiwtNzcsNjAsNjQsLTEyMCwtODIsLTQ2LC00NCwtOTUsLTE2LDEwNywtNTUsMzIsLTEwNiwtNDgsMTA0LC0zLC0zMywtNSwtNjIsLTY2LC05OCwtMjksMjMsNCwtNTYsLTExOSw2OSwtODMsNSwyNyw5NCwtNDcsLTE2LC0xMDgsMTksLTQsNzIsNzEsLTU2LDY1LC0xMDEsLTEsLTM5LDc3LC0xMTEsLTIyLDUzLC04MywtNDYsODUsLTc3LDEwMSwtMTAyLDEsLTkzLDEyMCwyNywtMTIsLTIxLC05LDUyLDM1LDQ4LC0xMCwtODAsLTcxLDEyNCw5NiwtNDEsMTEyLC05OSwtMSwtODIsLTExOSwtMTA0LDEyMCw3NSwtNCw1Nyw5OSwtNTksLTEyMSwtOSwxMjYsNSwtNzIsLTIzLC0zNCwyNCwxMDksLTc4LC0zOCwtODQsNjIsLTg0LDkxLDE2LDYyLDEyLDU3LC0xMjUsOTcsMzgsOTQsLTk4LDEwMywtOTgsODEsLTc5LC05LC0xMTksNzMsLTUxLC0xMjUsLTIxLDExMCwtMTEsLTg1LDY4LC0xMjMsLTM4LC0xMTMsLTEyMywtMjksMSw4NSw3MSwxMjUsMTMsNjIsNDcsLTQzLDUxLDI0LC01OSw2MiwtNzUsMzQsNzksLTEwMyw1MywtMTIsLTc3LDExMSwtNTgsMSwzMCwtMTIwLDEyNCwtMTA1LDM3LC0zMiw4MywtMTgsLTU3LDQ0LC05NiwxMCwtNzIsLTExOSwtMzIsLTc0LC03MywxMDgsLTk2LDI4LDMzLDY2LC00MSwtMTI0LC03OSwtOTUsLTUsOTEsMTE2LDgsMzMsNTAsLTY4LDQ0LC0xMTcsNTksNiwtOTAsMjMsLTExOCw2LDUyLDE4XSwibWF0ZXJpYWxTZXRTZXJpYWxOdW1iZXIiOjEsIml2UGFyYW1ldGVyU3BlYyI6eyJpdiI6WzMxLC0xMCwxMTcsLTEyNiwtNDAsMTIzLC01Myw4OSwtMTA4LDc0LC0xMTgsMzAsLTcxLDExOSw2OSwxOF19fQ==", 6 | "eventLeftScope": false, 7 | "executionRoleArn": "arn:aws:iam::123456789012:role/service-role/config-role-eu-west-1", 8 | "configRuleArn": "arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-18uhud", 9 | "configRuleName": "SecurityGroupCheck", 10 | "configRuleId": "config-rule-3242423", 11 | "accountId": "123456789012", 12 | "dryRun": true 13 | } 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Making Things Right With AWS Lambda and AWS Config Rules 2 | 3 | ![Config Rules RULES](/Images/Config-Header.png) 4 | 5 | ## View the Leaderboard - https://amzn.to/aws-config-rules-workshop 6 | 7 | This repository contains five partially completed AWS Lambda functions, written in Python, to be completed and used as AWS Config Rules when attending the “Making Things Right With AWS Lambda and AWS Config Rules” workshop. 8 | 9 | As part of the workshop, you will work in teams to complete the Lambda functions provided, and create AWS Config Rules with the completed functions so that they operate as described and appropriately mark AWS resources as Compliant or NonCompliant. 10 | 11 | ## Prerequisites 12 | Each attendee must have the following in order to participate: 13 | 14 | ### 1. An AWS Account 15 | Each participant must work within their own AWS account, with Admin privileges (you will be utilizing several different services while creating and testing your Config Rules, include creation of new IAM Roles and Policies). 16 | 17 | Participants working on the same Config Rules Workshop team will complete rules within their own separate AWS accounts. 18 | 19 | ### 2. A Config Rules Workshop Leaderboard Account 20 | We have created a Leaderboard Web Application where you can register and compete against the other teams attending your workshop. You will need to register with the leaderboard in order to test that your completed Config Rules are operating as described, and to earn your team points! 21 | 22 | Find and register for the Workshop leaderboard [**here**](https://amzn.to/aws-config-rules-workshop) 23 | 24 | Once registered, Create or Join a Team with the group of workshop attendees you will be cooperating with to complete all of your custom AWS Config Rules. You are welcome to work on your own team if you prefer. But in order to earn points, you must still Create a Team, even if you are the team's only member. 25 | 26 | ## How it Works 27 | 28 | ### Repository Contents 29 | Within the [**Workshop Rules**](/Workshop-Rules) directory, you will find the content required to complete the workshop. There is no requirement to complete the modules in order, but Module 1 contains an introduction and overview for both AWS Config Rules and step-by-step instructions for earning points as you complete modules. We recommend you begin with Module 1 before proceeding. The modules generally increase in difficulty, Module 1 containing a fully-written Lambda function, and Module 5 requiring the most code to be complete. 30 | 31 | Within each Workshop Module, you will find the following 3 files: 32 | 1. **rule.py** - This is a partially completed Lambda function that has been written to serve as a Config rule once completed. The README within the directory will describe the intended purpose of the function and provide hints and links to documentation to point you towards completion. Within `rule.py`, from Module 2 onwards, you will find snippets and lines of code that have been marked as `##CHANGED##` or `##LINE_REMOVED##`. You will need to replace those values or lines of code with the correct values or logic in order for the rule to behave appropriately. **Some of the removal comments include hints about what's missing.** 33 | 2. **compliant_test_event.json** - A json object that can be used within the Lambda console as a test event to see if your code will successfully have marked the event as COMPLIANT. An added parameter has been appended to the object `dryRun=true` which is then again referenced within the completed function code to allow for more testing without AWS Config needing to be called, like would occur with a non-test event. 34 | 3. **noncompliant_test_event.json** - A json object that can be used within the Lambda console as a test event to see if your code will successfully have marked the event as NON_COMPLIANT. 35 | 36 | ### Testing Your Rule (earning points!) 37 | After you have tested your Config Rule to your satisfaction for each module, you will find a button located within each Module directory to launch a CloudFormation stack. This stack will create all of the resources required to test and assess the correctness of the Config Rule and Lambda function you've created. Each assessment occurs as an **Execution** via an AWS Step Functions State Machine that is created by the CloudFormation template for that module. Simply visit the [Step Functions console](https://eu-west-1.console.aws.amazon.com/states/), select the created state machine for the module, and then choose **New Execution**: 38 | ![New Exexcution](/Images/New-Execution.png) 39 | 40 | For the *Execution Input*, visit the [**Config Workshop Leaderboard**](https://amzn.to/aws-config-rules-workshop/), and after you have **Created or Joined a Team**, choose the **Copy JWT** button: 41 | ![Copy JWT](/Images/Copy-JWT.png) 42 | 43 | If you do not join a team on the Leaderboard, you will not receive points! Take your copied JWT input, and replace the default State Machine input with all that's been copied as the input to the State Machine Execution: 44 | ![Pasted JWT](/Images/JWT-Pasted.png) 45 | 46 | The execution will take 5-10 minutes to complete, and it's path through the state machine will indicate if your Config Rule has met the requirements and if any points have been scored for your team! A completed execution will look like the below (failure will result in a red failure state): 47 | ![State Machine Step Graph](/Images/SFN-Execution-Map.png) 48 | 49 | Each individual on your team can only receive points once for each rule. But your team *can* receive points for the same rule as different team members complete each Module - **so help your team members complete their rules as well!** 50 | 51 | 52 | ## License 53 | 54 | This library is licensed under the Apache 2.0 License. 55 | -------------------------------------------------------------------------------- /Workshop-Rules/1-Introduction-to-Config-Rules/README.md: -------------------------------------------------------------------------------- 1 | # Creating your first custom rule with AWS Config 2 | For module one of this workshop, we will walk you through creating a custom rule in AWS Config, with all of the code already written for you. Then, we will show you how to get credit for creating this rule to earn points on the Config Rules Workshop Leaderboard. The subsequent modules will have far less instruction, and it will be up to you to learn from this first Config Rule to complete the remaining rules! 3 | 4 | ## The Purpose of This Rule 5 | This rule is intended to ensure that all SSH access granted via security groups is entirely locked down to a single /32 IP address (1.1.1.1/32 for this hypothetical exercise). An organization may want to have a rule similar to this to ensure that all SSH traffic is originating from a bastion host or gateway device within their known and controlled network. Any security groups that allow SSH access to an IP address or IP range other than 1.1.1.1/32 should be evaluated as Noncompliant. 6 | 7 | ## Create a Lambda Function 8 | Each Config rule that you create and manage is an AWS Lambda function that contains the logic for evaluating resource configurations tracked and notified through AWS Config. All of the code that we have provided for this module (in [`rule.py`](./rule.py)) represents a complete Lambda function to evaluate security group configurations according to the rule we have described above, in Python 3.6. In order to create a Lambda function for this code to be executed, follow these steps: 9 | 10 | 1. Visit the [AWS Lambda console](https://eu-west-1.console.aws.amazon.com/lambda/home?region=eu-west-1). 11 | 12 | 2. Select **Create Function** 13 | 14 | 3. Select **Author from Scratch** 15 | 16 | 4. For **Name** choose any descriptive name for this function, like *ConfigRules-CheckSecurityGroup*, or similar. For **Role** select, *Create new role from template(s)*. For **Role Name**, choose any descriptive name for this role, like *ConfigRules-CheckSecurityGroup-Role*. For **Policy templates** choose, *AWS Config Rules permissions*. This will grant the role the basic permissions that all Lambda functions require (to create and send logs to CloudWatch Logs), and permissions to notify AWS Config of new compliance evaluation results. 17 | 18 | 5. Choose **Create Function** 19 | 20 | 6. Within the Lambda function Code Editor, modify the **Runtime** to be *Python 3.6*. The remainder of the configuration can remain as default. 21 | 22 | 7. Copy all of the code within [**rule.py**](./rule.py) and paste it in the Code Editor within the Lambda console, replacing all the previous contents. 23 | 24 | 8. Click **Save and Test** 25 | 26 | 9. You will be prompted to create a test event that will be used to invoke your Lambda function, to test it's logic. Copy the contents of [**compliant_test_event.json**](./compliant_test_event.json) or [**noncompliant_test_event.json**](./noncompliant_test_event.json) and paste it within the Test Event editor, replacing any of the Event Templates chosen. Name your event something descriptive, and **Create**. 27 | 28 | 10. Your Lambda function will execute, and return a response of either COMPLIANT or NONCOMPLIANT. If your rule returns the appropriate response to both dryrun events, things are working as expected! 29 | 30 | Next we will enable AWS Config and create your first Config Rule so that this Lambda function is executed whenever configuration changes occur for your security groups. 31 | 32 | ## Enabling AWS Config 33 | If you have never used the AWS Config Service, you will first need to enable it. Follow [these steps to enable AWS Config](http://docs.aws.amazon.com/config/latest/developerguide/gs-console.html), be sure you enable config within the appropriate region for this workshop: [eu-west-1/Ireland](https://eu-west-1.console.aws.amazon.com/config/home?region=eu-west-1). 34 | 35 | ## Creating a Config Rule 36 | 1. On the AWS Config console home page, choose **Rules**, then **+Add Rule**: 37 | ![Add Rule](Images/Add-Rule.png) 38 | 39 | 2. Here, you'll see many available Config Rules that AWS has created and will manage for you, called Managed Rules. For this workshop we will be creating Custom Rules. Choose **+Custom Rule**: 40 | ![Add Custom Rule](Images/Add-Custom-Rule.png) 41 | 42 | 3. Name your Config Rule something descriptive like, *SecurityGroupSSHWhitelistRule*, and give it a description. For **Lambda Function ARN**, copy the ARN that is visible within the Lambda console for the Lambda function you created above, and paste the full ARN here. It should have the form of *arn:aws:lambda:aws-region-1:xxxxxxxxxxxx:function:FUNCTION_NAME*: 43 | ![Rule Config](Images/Rule-Basic-Config.png) 44 | 45 | 4. Next, you have the option of either having this rule be evaluated as changes occur to AWS resources (*Configuration changes*) or on a schedule (*Periodic*). For this workshop, all of the rules with be triggered by **Configuration changes**, so choose that option. For configuration change triggered rules, you have the ability to scope event triggers to either resources of a particular type change (*Resources*), when any resources that share a specified tag change (*Tags*) or when AWS Config records the change of any resource (*Any*). For this workshop, our scope will be **Resources**. 46 | 5. You then will select for which type of AWS resources should the configuration changes be sent to your Config rule for evaluation. This first module's rule evaluates Security Groups. So select **Security Groups**. When writing your own rules in the future, you may not care to have your Config rule evaluate every single resource of a particular type. AWS Config allows you to specify a Resource identifier if you'd like the rule to only execute for that single resource, and not all others of the same type. For this workshop, leave *Resource identifier* blank: 47 | ![Rule Trigger](Images/Rule-Trigger-Config.png) 48 | 49 | 6. AWS Config has the ability to pass configuration parameters to your Lambda function along with each invocation event. They will arrive as key:value pairs within the event object as part of the *RuleParameters* attribute. For this first example rule, our Lambda function makes use of one parameter - **ipAddress**. This represents the single /32 IP address that as treated as the allowed IP address for SSH traffic to security groups in your account. So create one Rule parameter with the key **ipAddress** and a value of **1.1.1.1/32**. Keep in mind that the key name is case-sensitive: 50 | ![Rule Parameters](Images/Rule-Parameters.png) 51 | 52 | 7. Choose **Save** 53 | 54 | 8. Next, you will see your new Config Rule listed on the Config Rules dashboard. Here you'll see a summary view of all existing Config rules within your account. Click on your rule, and you are taken to the dashboard for your new Config Rule, where you're able to edit it later, view the compliance status for each of the applicable resources, and more. If your Lambda function was created successfully, you will be able to begin seeing any security groups that you have existing within this region appear and declared either Compliant or Noncompliant. 55 | 56 | ## Scoring! 57 | After you have tested your Config Rule to your satisfaction for each module, you will find a button located within each Module directory, to launch a CloudFormation stack. This stack will create all of the resources required to test and assess the correctness of the Config Rule and Lambda function you've created. Each assessment occurs as an **Execution** via an AWS Step Functions State Machine that is created by the CloudFormation template for that module. 58 | 59 | 1. Click the button below to launch the template, leaving all settings as default (checking boxes on the **Review** page to acknowledge the stack will create IAM resources, and choosing the **Create Change Set** button so that the Serverless Application Model template will be transformed into a CloudFormation template): 60 | ![Cloudformation Choices](Images/Cloudformation.png) 61 | 62 | 63 | Region| Launch 64 | ------|----- 65 | EU (Ireland) | [![Launch Module 1 in eu-west-1](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/cloudformation-launch-stack-button.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=ConfigRules-Module-1-Security-Groups&templateURL=https://s3.amazonaws.com/config-rules-workshop-eu-west-1/module-1/template.yml) 66 | 67 | 2. After the stack has been created, visit the Step Functions console in the region you have created the stack, select the created state machine for the module, and then choose **New Execution**: 68 | ![New Exexcution](/Images/New-Execution.png) 69 | 70 | 3. For the Execution Input, visit the [**Config Workshop Leaderboard**](https://amzn.to/aws-config-rules-workshop), and after you have Created or Joined a team, choose the **Copy JWT** button: 71 | ![Copy JWT](/Images/Copy-JWT.png) 72 | 73 | 4. Take what you've just copied and paste it to replace the default State Machine input for the state machine created for this Module: 74 | ![Pasted JWT](/Images/JWT-Pasted.png) 75 | 76 | 5. Then choose **Start Execution**. 77 | 78 | 6. The execution will take 5-10 minutes to complete, and it's path through the state machine will indicate if your Config Rule has met the requirements and if any points have been scored for your team! 79 | ![State Machine Step Graph](/Images/SFN-Execution-Map.png) 80 | 81 | ### Earn Points Together 82 | You can only get credit for the same rule once, as an individual team member. But your team *will* receive points for the same rule as different team members complete each Module - **so help your team members complete their rules as well!** 83 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------