Description: AWS Security Hub PCI Remediations Security Hub Custom Actions AWSTemplateFormatVersion: "2010-09-09" # @author Kanishk Mahajan # ## License: ## This code is made available under the MIT-0 license. See the LICENSE file. Parameters: EmailAddress: Description: Email Address for notifications for PCI.CW.1 Type: String Default: admin@example.com DeliveryChannelExists: Description: >- Choose 'true' if Delivery Channel is already provisioned Type: String Default: 'true' AllowedValues: ['false', 'true'] Conditions: CreateDeliveryChannel: !Equals [ !Ref DeliveryChannelExists, 'false' ] Resources: # SNS topic for CloudWatch Alarm Notifications AlarmNotificationTopic: Type: 'AWS::SNS::Topic' Properties: DisplayName: AlarmNotificationTopic TopicName: AlarmNotificationTopic # Email Subscription for SNS topic AlarmEmailSubscription: Type: 'AWS::SNS::Subscription' Properties: Protocol: email Endpoint: !Ref EmailAddress TopicArn: !Ref AlarmNotificationTopic # CloudTrail CloudWatch Log Group CloudTrailLogGroup: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub DefaultLogGroup-PCI-${AWS::Region} RetentionInDays: 1827 CreateSecurityHubCustomActionTargetLambda: Type: AWS::Lambda::Function Properties: FunctionName: CreateSecurityHubCustomActionTargetLambda Description: Custom resource to create an action target in Security Hub Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt CreateSecurityHubCustomActionTargetLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import cfnresponse import os def lambda_handler(event, context): try: properties = event['ResourceProperties'] region = os.environ['AWS_REGION'] client = boto3.client('securityhub', region_name=region) responseData = {} if event['RequestType'] == 'Create': response = client.create_action_target( Name=properties['Name'], Description=properties['Description'], Id=properties['Id'] ) responseData['Arn'] = response['ActionTargetArn'] elif event['RequestType'] == 'Delete': account_id = context.invoked_function_arn.split(":")[4] client.delete_action_target( ActionTargetArn=f"arn:aws:securityhub:{region}:{account_id}:action/custom/{properties['Id']}" ) cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData) except Exception as e: print(e) cfnresponse.send(event, context, cfnresponse.FAILED, {}) CreateSecurityHubCustomActionTargetLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: CreateActionTarget-LambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - securityhub:CreateActionTarget - securityhub:DeleteActionTarget Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # [PCI.Config.1] Enable AWS Config ConfigurationRecorder: Condition: CreateDeliveryChannel Type: 'AWS::Config::ConfigurationRecorder' Properties: RoleARN: 'Fn::GetAtt': - IamRoleForAwsConfig - Arn RecordingGroup: AllSupported: true IncludeGlobalResourceTypes: true DeliveryChannel: Condition: CreateDeliveryChannel Type: AWS::Config::DeliveryChannel Properties: ConfigSnapshotDeliveryProperties: DeliveryFrequency: One_Hour S3BucketName: !Ref 'S3BucketForAwsConfig' S3BucketForAwsConfig: Condition: CreateDeliveryChannel Type: 'AWS::S3::Bucket' Properties: {} IamRoleForAwsConfig: Condition: CreateDeliveryChannel Type: 'AWS::IAM::Role' Properties: ManagedPolicyArns: - 'arn:aws:iam::aws:policy/service-role/AWSConfigRole' AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Sid: '' Effect: Allow Principal: Service: config.amazonaws.com Action: 'sts:AssumeRole' Policies: - PolicyName: allow-access-to-config-s3-bucket PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - 's3:PutObject' Resource: - 'Fn::Join': - '' - - 'Fn::GetAtt': - S3BucketForAwsConfig - Arn - /* Condition: StringLike: 's3:x-amz-acl': bucket-owner-full-control - Effect: Allow Action: - 's3:GetBucketAcl' Resource: 'Fn::GetAtt': - S3BucketForAwsConfig - Arn #PCI S3.1 S3BucketPublicWriteProhibitedRule: Type: AWS::Events::Rule Properties: Name: S3BucketPublicWriteProhibitedRule Description: "PCI.S3.1 - S3 Buckets should prohibit public write access" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt S3BucketPublicWriteActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "S3BucketPublicWriteRemediationLambda" - "Arn" Id: "PCIS31" S3BucketPublicWriteActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIS31 Description: S3 Public Write Event from Security Hub Id: PCIS31 S3BucketPublicWriteRemediationLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "S3BucketPublicWriteRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "S3BucketPublicWriteProhibitedRule" - "Arn" S3BucketPublicWriteRemediationLambda: Type: AWS::Lambda::Function DependsOn: S3RemediationLambdaRole Properties: FunctionName: S3BucketPublicWriteRemediationLambda Description: PCI S3.1 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt S3RemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): S3BucketArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) Id = str(event['detail']['findings'][0]['Id']) S3BucketName = S3BucketArn.replace("arn:aws:s3:::", "") ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='AWS-DisableS3BucketPublicReadWrite', DocumentVersion='1', # default Parameters={ 'S3BucketName': [ S3BucketName ] } ) except Exception as e: print(e) print("SSM automation execution error") raise S3RemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: S3RemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - s3:GetBucketAcl - s3:GetBucketPolicy - s3:PutBucketAcl - s3:PutBucketPolicy - s3:PutBucketPublicAccessBlock - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI S3.2 S3BucketPublicReadProhibitedRule: Type: AWS::Events::Rule Properties: Name: S3BucketPublicReadProhibitedRule Description: "PCI.S3.2 - S3 Buckets should prohibit public read access" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt S3BucketPublicReadActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "S3BucketPublicReadRemediationLambda" - "Arn" Id: "PCIS32" S3BucketPublicReadActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIS32 Description: S3 Public Write Event from Security Hub Id: PCIS32 S3BucketPublicReadRemediationLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "S3BucketPublicReadRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "S3BucketPublicReadProhibitedRule" - "Arn" S3BucketPublicReadRemediationLambda: Type: AWS::Lambda::Function DependsOn: S3RemediationLambdaRole Properties: FunctionName: S3BucketPublicReadRemediationLambda Description: PCI S3.2 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt S3RemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): S3BucketArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) Id = str(event['detail']['findings'][0]['Id']) S3BucketName = S3BucketArn.replace("arn:aws:s3:::", "") ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='AWS-DisableS3BucketPublicReadWrite', DocumentVersion='1', # default Parameters={ 'S3BucketName': [ S3BucketName ] } ) except Exception as e: print(e) print("SSM automation execution error") raise S3RemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: S3RemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - s3:GetBucketAcl - s3:GetBucketPolicy - s3:PutBucketAcl - s3:PutBucketPolicy - s3:PutBucketPublicAccessBlock - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI CW.1 RootAccountLoginsAlarm: Type: AWS::CloudWatch::Alarm DependsOn: - NoMfaConsoleLoginsAlarm Properties: AlarmName: PCI-Root Activity AlarmDescription: Alarm if a 'root' user uses the account MetricName: RootUserEventCount Namespace: LogMetrics Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: 1 TreatMissingData: notBreaching AlarmActions: - !Ref AlarmNotificationTopic ComparisonOperator: GreaterThanOrEqualToThreshold RootAccountLoginsFilter: Type: AWS::Logs::MetricFilter Properties: LogGroupName: !Ref CloudTrailLogGroup FilterPattern: |- { $.userIdentity.type = "Root" && $.userIdentity.invokedBy NOT EXISTS && $.eventType != "AwsServiceEvent" } MetricTransformations: - MetricValue: '1' MetricNamespace: LogMetrics MetricName: RootUserEventCount NoMfaConsoleLoginsAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: PCI-Console Signin Without MFA AlarmDescription: Alarm if there is a Management Console sign-in without MFA MetricName: ConsoleSigninWithoutMFA Namespace: LogMetrics Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: 1 TreatMissingData: notBreaching AlarmActions: - !Ref AlarmNotificationTopic ComparisonOperator: GreaterThanOrEqualToThreshold NoMfaConsoleLoginsFilter: Type: AWS::Logs::MetricFilter Properties: LogGroupName: !Ref CloudTrailLogGroup FilterPattern: |- { ($.eventName = "ConsoleLogin") && ($.additionalEventData.MFAUsed != "Yes") } MetricTransformations: - MetricValue: '1' MetricNamespace: LogMetrics MetricName: ConsoleSigninWithoutMFA #PCI CloudTrail.1 CloudTrailEncryptionEnabledRule: Type: AWS::Events::Rule Properties: Name: CloudTrailEncryptionEnabledRule Description: "PCI.CloudTrail.1 – Ensure CloudTrail logs are encrypted at rest using AWS KMS CMKs" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt CloudTrailEncryptionEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "CloudTrailEncryptionEnabledLambda" - "Arn" Id: "PCICloudTrail1" CloudTrailEncryptionEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCICloudTrail1 Description: PCI.CloudTrail.1 Event from Security Hub Id: PCICloudTrail1 CloudTrailEncryptionEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "CloudTrailEncryptionEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "CloudTrailEncryptionEnabledRule" - "Arn" CloudTrailEncryptionEnabledLambda: Type: AWS::Lambda::Function DependsOn: CloudTrailEncryptionEnabledLambdaRole Properties: FunctionName: CloudTrailEncryptionEnabledLambda Description: PCI CloudTrail.1 Remediation Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt CloudTrailEncryptionEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: CloudTrailLogGroupArn : !ImportValue CloudTrailLogGroupArn CloudWatchRoleArn : !ImportValue CloudWatchRoleArn KMSKeyArn: !ImportValue KMSKeyArn Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): TrailArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) TrailArn_1 = TrailArn.split(':')[-1] TrailName = TrailArn_1.replace("trail/","") Id = str(event['detail']['findings'][0]['Id']) CloudTrailLogGroupArn = os.environ['CloudTrailLogGroupArn'] CloudWatchRoleArn = os.environ['CloudWatchRoleArn'] KMSKeyArn = os.environ['KMSKeyArn'] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCICloudTrail1Automation', DocumentVersion='1', # default Parameters={ 'TrailName': [ TrailName ], 'CloudTrailLogGroupArn': [ CloudTrailLogGroupArn ], 'CloudWatchRoleArn': [ CloudWatchRoleArn ], 'KMSKeyArn': [ KMSKeyArn ] } ) except Exception as e: print(e) print("SSM automation execution error") raise CloudTrailEncryptionEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: CloudTrailEncryptionEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - kms:* - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI.KMS.1 CMKBackingKeyRotationRule: Type: AWS::Events::Rule Properties: Name: CMKBackingKeyRotationRule Description: "PCI.KMS.1 – Ensure rotation for customer created CMKs is enabled" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt CMKBackingKeyRotationActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "CMKBackingKeyRotationLambda" - "Arn" Id: "PCIKMS1" CMKBackingKeyRotationActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIKMS1 Description: PCI KMS.1 Event from Security Hub Id: PCIKMS1 CMKBackingKeyRotationPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "CMKBackingKeyRotationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "CMKBackingKeyRotationRule" - "Arn" CMKBackingKeyRotationLambda: Type: AWS::Lambda::Function DependsOn: CMKBackingKeyRotationLambdaRole Properties: FunctionName: CMKBackingKeyRotationLambda Description: PCI KMS.1 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt CMKBackingKeyRotationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): KMSKeyArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) KMSKeyId_1 = KMSKeyArn.split(':')[-1] KMSKeyId = KMSKeyId_1.replace("key/","") Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIKMS1Automation', DocumentVersion='1', # default Parameters={ 'KMSKeyArn': [ KMSKeyId ] } ) except Exception as e: print(e) print("SSM automation execution error") raise CMKBackingKeyRotationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: CMKBackingKeyRotationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI.EC2.3 RemoveUnusedEC2SecurityGroupsRule: Type: AWS::Events::Rule Properties: Name: RemoveUnusedEC2SecurityGroupsRule Description: "PCI.EC2.3 – Unused EC2 Security Groups should be removed" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt RemoveUnusedEC2GroupsActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "RemoveUnusedEC2GroupsRemediationLambda" - "Arn" Id: "PCIEC23" RemoveUnusedEC2GroupsActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIEC23 Description: PCI.EC2.3 Event from Security Hub Id: PCIEC23 RemoveUnusedEC2GroupsLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "RemoveUnusedEC2GroupsRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "RemoveUnusedEC2SecurityGroupsRule" - "Arn" RemoveUnusedEC2GroupsRemediationLambda: Type: AWS::Lambda::Function DependsOn: RemoveUnusedEC2GroupsRemediationLambdaRole Properties: FunctionName: RemoveUnusedEC2GroupsRemediationLambda Description: PCI.EC2.3 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt RemoveUnusedEC2GroupsRemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): securitygroup = str(event['detail']['findings'][0]['Resources'][0]['Details']['AwsEc2SecurityGroup']['GroupId']) Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIEC23Automation', DocumentVersion='1', # default Parameters={ 'groupId': [ securitygroup] } ) except Exception as e: print(e) print("SSM automation execution error") raise RemoveUnusedEC2GroupsRemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: RemoveUnusedEC2GroupsRemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - ec2:DescribeSecurityGroupReferences - ec2:DescribeSecurityGroups - ec2:UpdateSecurityGroupRuleDescriptionsEgress - ec2:UpdateSecurityGroupRuleDescriptionsIngress - ec2:RevokeSecurityGroupIngress - ec2:RevokeSecurityGroupEgress - ec2:* - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI.EC2.2 VPCDefaultSecurityGroupsRule: Type: AWS::Events::Rule Properties: Name: VPCDefaultSecurityGroupsRule Description: "PCI.EC2.2 VPC default security group should prohibit inbound and outbound traffic" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt VPCDefaultGroupsActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "VPCDefaultGroupsRemediationLambda" - "Arn" Id: "PCIEC22" VPCDefaultGroupsActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIEC22 Description: PCI.EC2.2 Event from Security Hub Id: PCIEC22 VPCDefaultGroupsLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "VPCDefaultGroupsRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "VPCDefaultSecurityGroupsRule" - "Arn" VPCDefaultGroupsRemediationLambda: Type: AWS::Lambda::Function DependsOn: VPCDefaultGroupsRemediationLambdaRole Properties: FunctionName: VPCDefaultGroupsRemediationLambda Description: PCI.EC2.2 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt VPCDefaultGroupsRemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): securitygroup = str(event['detail']['findings'][0]['Resources'][0]['Details']['AwsEc2SecurityGroup']['GroupId']) Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') IpAddressToBlock = '0.0.0.0/0' try: response = ssm.start_automation_execution( DocumentName='PCIEC22Automation', DocumentVersion='1', # default Parameters={ 'groupId': [ securitygroup], 'IpAddressToBlock': [IpAddressToBlock] } ) except Exception as e: print(e) print("SSM automation execution error") raise VPCDefaultGroupsRemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: VPCDefaultGroupsRemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - ec2:DescribeSecurityGroupReferences - ec2:DescribeSecurityGroups - ec2:UpdateSecurityGroupRuleDescriptionsEgress - ec2:UpdateSecurityGroupRuleDescriptionsIngress - ec2:RevokeSecurityGroupIngress - ec2:RevokeSecurityGroupEgress - ec2:* - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI EC2.5 RestrictEC2SecurityGroupsRule: Type: AWS::Events::Rule Properties: Name: RestrictEC2SecurityGroupsRule Description: "PCI.EC2.5 Restrict EC2 Security Groups for SSH and RDP Access" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt RestrictEC2GroupsActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "RestrictEC2GroupsRemediationLambda" - "Arn" Id: "PCIEC25" RestrictEC2GroupsActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIEC25 Description: PCI.EC2.5 Event from Security Hub Id: PCIEC25 RestrictEC2GroupsLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "RestrictEC2GroupsRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "RestrictEC2SecurityGroupsRule" - "Arn" RestrictEC2GroupsRemediationLambda: Type: AWS::Lambda::Function DependsOn: RestrictEC2GroupsRemediationLambdaRole Properties: FunctionName: RestrictEC2GroupsRemediationLambda Description: PCI.EC2.5 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt RestrictEC2GroupsRemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): securitygroup = str(event['detail']['findings'][0]['Resources'][0]['Details']['AwsEc2SecurityGroup']['GroupId']) Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') IpAddressToBlock = '0.0.0.0/0' try: response = ssm.start_automation_execution( DocumentName='PCIEC22Automation', DocumentVersion='1', # default Parameters={ 'groupId': [ securitygroup], 'IpAddressToBlock': [IpAddressToBlock] } ) except Exception as e: print(e) print("SSM automation execution error") raise RestrictEC2GroupsRemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: RestrictEC2GroupsRemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - ec2:DescribeSecurityGroupReferences - ec2:DescribeSecurityGroups - ec2:UpdateSecurityGroupRuleDescriptionsEgress - ec2:UpdateSecurityGroupRuleDescriptionsIngress - ec2:RevokeSecurityGroupIngress - ec2:RevokeSecurityGroupEgress - ec2:* - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI.AutoScaling.1 AutoScalingELBHealthCheckRule: Type: AWS::Events::Rule Properties: Name: AutoScalingELBHealthCheckRule Description: "[PCI.AutoScaling.1] Auto scaling groups associated with a load balancer should use health checks" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt AutoScalingELBHealthCheckActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "AutoScalingELBHealthCheckRemediationLambda" - "Arn" Id: "PCIAutoScaling1" AutoScalingELBHealthCheckActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIAutoScaling1 Description: "PCI.AutoScaling.1 Event from Security Hub" Id: PCIAutoScaling1 AutoScalingELBHealthCheckLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "AutoScalingELBHealthCheckRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "AutoScalingELBHealthCheckRule" - "Arn" AutoScalingELBHealthCheckRemediationLambda: Type: AWS::Lambda::Function DependsOn: AutoScalingELBHealthCheckRemediationLambdaRole Properties: FunctionName: AutoScalingELBHealthCheckRemediationLambda Description: PCI.AutoScaling.1 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt AutoScalingELBHealthCheckRemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): ASGId = str(event['detail']['findings'][0]['Resources'][0]['Id']) ASGId_1 = ASGId.split(':')[-1] ASGGroupName = ASGId_1.replace("autoScalingGroupName/","") ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIAutoScaling1Automation', DocumentVersion='1', # default Parameters={ 'ASGGroupName': [ ASGGroupName] } ) except Exception as e: print(e) print("SSM automation execution error") raise AutoScalingELBHealthCheckRemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: AutoScalingELBHealthCheckRemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - ec2:DescribeSecurityGroupReferences - ec2:DescribeSecurityGroups - ec2:UpdateSecurityGroupRuleDescriptionsEgress - ec2:UpdateSecurityGroupRuleDescriptionsIngress - ec2:RevokeSecurityGroupIngress - ec2:RevokeSecurityGroupEgress - ec2:* - autoscaling:* - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI.CodeBuild.2 CodeBuildEnvVariablesRule: Type: AWS::Events::Rule Properties: Name: CodeBuildEnvVariablesRule Description: "[PCI.CodeBuild.2] CodeBuild project environment variables should not contain clear text credentials" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt CodeBuildEnvVariablesRuleActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "CodeBuildEnvVariablesRuleRemediationLambda" - "Arn" Id: "PCICodeBuild2" CodeBuildEnvVariablesRuleActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCICodeBuild2 Description: PCI.CodeBuild.2 Event from Security Hub Id: PCICodeBuild2 CodeBuildEnvVariablesRuleLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "CodeBuildEnvVariablesRuleRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "CodeBuildEnvVariablesRule" - "Arn" CodeBuildEnvVariablesRuleRemediationLambda: Type: AWS::Lambda::Function DependsOn: CodeBuildEnvVariablesRuleRemediationLambdaRole Properties: FunctionName: CodeBuildEnvVariablesRuleRemediationLambda Description: PCI.CodeBuild.2 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt CodeBuildEnvVariablesRuleRemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): codebuildprojectArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) codebuildprojectArn_1 = codebuildprojectArn.split(':')[-1] codebuildproject = codebuildprojectArn_1.replace("project/","") Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCICodeBuild2Automation', DocumentVersion='1', # default Parameters={ 'projectName': [ codebuildproject] } ) except Exception as e: print(e) print("SSM automation execution error") raise CodeBuildEnvVariablesRuleRemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: CodeBuildEnvVariablesRuleRemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - ec2:DescribeSecurityGroupReferences - ec2:DescribeSecurityGroups - ec2:UpdateSecurityGroupRuleDescriptionsEgress - ec2:UpdateSecurityGroupRuleDescriptionsIngress - ec2:RevokeSecurityGroupIngress - ec2:RevokeSecurityGroupEgress - ec2:* - codebuild:* - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI.EC2.4 ReleaseEIPRule: Type: AWS::Events::Rule Properties: Name: ReleaseEIPRule Description: "PCI.EC2.4 Unused EC2 EIPs should be removed" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt ReleaseEIPRuleActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "ReleaseEIPRuleRemediationLambda" - "Arn" Id: "PCIEC24" ReleaseEIPRuleActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIEC24 Description: PCI.EC2.4 Event from Security Hub Id: PCIEC24 ReleaseEIPRuleLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "ReleaseEIPRuleRemediationLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "ReleaseEIPRule" - "Arn" ReleaseEIPRuleRemediationLambda: Type: AWS::Lambda::Function DependsOn: ReleaseEIPRuleRemediationLambdaRole Properties: FunctionName: ReleaseEIPRuleRemediationLambda Description: PCI.EC2.4 Remediation using AWS SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt ReleaseEIPRuleRemediationLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): AllocationArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) AllocationArn_1 = AllocationArn.split(':')[-1] AllocationId = AllocationArn_1.replace("eip-allocation/","") ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='AWS-ReleaseElasticIP', DocumentVersion='1', # default Parameters={ 'AllocationId': [ AllocationId] } ) except Exception as e: print(e) print("SSM automation execution error") raise ReleaseEIPRuleRemediationLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: ReleaseEIPRuleRemediationLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - ec2:DescribeSecurityGroupReferences - ec2:DescribeSecurityGroups - ec2:UpdateSecurityGroupRuleDescriptionsEgress - ec2:UpdateSecurityGroupRuleDescriptionsIngress - ec2:RevokeSecurityGroupIngress - ec2:RevokeSecurityGroupEgress - ec2:* - iam:PassRole - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI.CloudTrail.4 CloudTrailCloudWatchLogsEnabledRule: Type: AWS::Events::Rule Properties: Name: CloudTrailCloudWatchLogsEnabledRule Description: "PCI.CloudTrail.4 – Ensure CloudTrail trails are integrated with Amazon CloudWatch Logs" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt CloudTrailCloudWatchLogsActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "CloudTrailCloudWatchLogsLambda" - "Arn" Id: "PCICloudTrail4" CloudTrailCloudWatchLogsActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCICloudTrail4 Description: PCI.CloudTrail.4 Event from Security Hub Id: PCICloudTrail4 CloudTrailCloudWatchLogsEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "CloudTrailCloudWatchLogsLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "CloudTrailCloudWatchLogsEnabledRule" - "Arn" CloudTrailCloudWatchLogsLambda: Type: AWS::Lambda::Function DependsOn: CloudTrailCloudWatchLogsLambdaRole Properties: FunctionName: CloudTrailCloudWatchLogsLambda Description: PCI.CloudTrail.4 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt CloudTrailCloudWatchLogsLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: CloudTrailLogGroupArn : !ImportValue CloudTrailLogGroupArn CloudWatchRoleArn : !ImportValue CloudWatchRoleArn Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): TrailArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) TrailArn_1 = TrailArn.split(':')[-1] TrailName = TrailArn_1.replace("trail/","") Id = str(event['detail']['findings'][0]['Id']) CloudTrailLogGroupArn = os.environ['CloudTrailLogGroupArn'] CloudWatchRoleArn = os.environ['CloudWatchRoleArn'] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCICloudTrail4Automation', DocumentVersion='1', # default Parameters={ 'TrailName': [ TrailName ], 'CloudTrailLogGroupArn': [ CloudTrailLogGroupArn ], 'CloudWatchRoleArn': [ CloudWatchRoleArn ] } ) except Exception as e: print(e) print("SSM automation execution error") raise CloudTrailCloudWatchLogsLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: CloudTrailCloudWatchLogsLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI.CloudTrail.2 CloudTrailEnabledRule: Type: AWS::Events::Rule Properties: Name: CloudTrailEnabledRule Description: "PCI.CloudTrail.2 – Ensure CloudTrail is enabled in all regions" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt CloudTrailEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "CloudTrailEnabledLambda" - "Arn" Id: "PCICloudTrail2" CloudTrailEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCICloudTrail2 Description: PCI.CloudTrail.2 Event from Security Hub Id: PCICloudTrail2 CloudTrailEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "CloudTrailEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "CloudTrailEnabledRule" - "Arn" CloudTrailEnabledLambda: Type: AWS::Lambda::Function DependsOn: CloudTrailEnabledLambdaRole Properties: FunctionName: CloudTrailEnabledLambda Description: CIS 2.1 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt CloudTrailEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: S3BucketName : !ImportValue PCIS3CloudTrailBucket TrailName : !ImportValue PCICloudTrail Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): TrailName = os.environ['TrailName'] S3BucketName = os.environ['S3BucketName'] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='AWS-EnableCloudTrail', DocumentVersion='1', # default Parameters={ 'TrailName': [ TrailName ], 'S3BucketName': [ S3BucketName] } ) except Exception as e: print(e) print("SSM automation execution error") raise CloudTrailEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: CloudTrailEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - cloudtrail:* - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI.CloudTrail.3 CloudTrailLogFileValidationEnabledRule: Type: AWS::Events::Rule Properties: Name: CloudTrailLogFileValidationEnabledRule Description: "PCI.CloudTrail.3 – Ensure CloudTrail log file validation is enabled" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt CloudTrailLogFileValidationEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "CloudTrailLogFileValidationEnabledLambda" - "Arn" Id: "PCICloudTrail3" CloudTrailLogFileValidationEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCICloudTrail3 Description: PCI.CloudTrail.3 Event from Security Hub Id: PCICloudTrail3 CloudTrailLogFileValidationEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "CloudTrailLogFileValidationEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "CloudTrailLogFileValidationEnabledRule" - "Arn" CloudTrailLogFileValidationEnabledLambda: Type: AWS::Lambda::Function DependsOn: CloudTrailLogFileValidationEnabledLambdaRole Properties: FunctionName: CloudTrailLogFileValidationEnabledLambda Description: CIS 2.2 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt CloudTrailLogFileValidationEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: CloudTrailLogGroupArn : !ImportValue CloudTrailLogGroupArn CloudWatchRoleArn : !ImportValue CloudWatchRoleArn Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): TrailArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) TrailArn_1 = TrailArn.split(':')[-1] TrailName = TrailArn_1.replace("trail/","") Id = str(event['detail']['findings'][0]['Id']) CloudTrailLogGroupArn = os.environ['CloudTrailLogGroupArn'] CloudWatchRoleArn = os.environ['CloudWatchRoleArn'] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCICloudTrail3Automation', DocumentVersion='1', # default Parameters={ 'TrailName': [ TrailName ], 'CloudTrailLogGroupArn': [ CloudTrailLogGroupArn ], 'CloudWatchRoleArn': [ CloudWatchRoleArn ] } ) except Exception as e: print(e) print("SSM automation execution error") raise CloudTrailLogFileValidationEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: CloudTrailLogFileValidationEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI IAM 4 IAMPasswordPolicyEnabledRule: Type: AWS::Events::Rule Properties: Name: IAMPasswordPolicyEnabledRule Description: "PCI IAM 4" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt IAMPasswordPolicyEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "IAMPasswordPolicyEnabledLambda" - "Arn" Id: "PCIIAM4" IAMPasswordPolicyEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIIAM4 Description: PCI IAM 4 Events from Security Hub Id: PCIIAM4 IAMPasswordPolicyEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "IAMPasswordPolicyEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "IAMPasswordPolicyEnabledRule" - "Arn" IAMPasswordPolicyEnabledLambda: Type: AWS::Lambda::Function DependsOn: IAMPasswordPolicyEnabledLambdaRole Properties: FunctionName: IAMPasswordPolicyEnabledLambda Description: PCI IAM 4 Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt IAMPasswordPolicyEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIIAM4Automation', DocumentVersion='1', # default ) except Exception as e: print(e) print("SSM automation execution error") raise IAMPasswordPolicyEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: IAMPasswordPolicyEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData - iam:* Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI.IAM.1 DeactivateRootIAMAccessKeyEnabledRule: Type: AWS::Events::Rule Properties: Name: DeactivateRootIAMAccessKeyEnabledRule Description: "PCI.IAM.1 – Deactivate Root Account Access Key" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt DeactivateRootIAMAccessKeyEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "DeactivateRootIAMAccessKeyEnabledLambda" - "Arn" Id: "PCIIAM1" DeactivateRootIAMAccessKeyEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIIAM1 Description: PCI.IAM.1 Events from Security Hub Id: PCIIAM1 DeactivateRootIAMAccessKeyEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "DeactivateRootIAMAccessKeyEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "DeactivateRootIAMAccessKeyEnabledRule" - "Arn" DeactivateRootIAMAccessKeyEnabledLambda: Type: AWS::Lambda::Function DependsOn: DeactivateRootIAMAccessKeyEnabledLambdaRole Properties: FunctionName: DeactivateRootIAMAccessKeyEnabledLambda Description: PCI.IAM.1 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt DeactivateRootIAMAccessKeyEnabledLambdaRole.Arn Runtime: python3.6 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): userArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) username = userArn.split(':')[-1] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIIAM1Automation', DocumentVersion='1', # default Parameters={ 'username': [ username ] } ) except Exception as e: print(e) print("SSM automation execution error") raise DeactivateRootIAMAccessKeyEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: DeactivateRootIAMAccessKeyEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData - iam:* Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #PCI.IAM.2 IAMUserPolicyDetachEnabledRule: Type: AWS::Events::Rule Properties: Name: IAMUserPolicyDetachEnabledRule Description: "PCI.IAM.2 – Ensure IAM policies are attached only to groups or roles" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt IAMUserPolicyDetachEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "IAMUserPolicyDetachEnabledLambda" - "Arn" Id: "PCIIAM2" IAMUserPolicyDetachEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIIAM2 Description: PCI.IAM.2 Events from Security Hub Id: PCIIAM2 IAMUserPolicyDetachEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "IAMUserPolicyDetachEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "IAMUserPolicyDetachEnabledRule" - "Arn" IAMUserPolicyDetachEnabledLambda: Type: AWS::Lambda::Function DependsOn: IAMUserPolicyDetachEnabledLambdaRole Properties: FunctionName: IAMUserPolicyDetachEnabledLambda Description: PCI.IAM.2 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt IAMUserPolicyDetachEnabledLambdaRole.Arn Runtime: python3.6 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): userArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) userArn_1 = userArn.split(':')[-1] username = userArn_1.replace("user/","") Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIIAM2Automation', DocumentVersion='1', # default Parameters={ 'username': [ username ], 'findingid': [Id] } ) except Exception as e: print(e) print("SSM automation execution error") raise IAMUserPolicyDetachEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: IAMUserPolicyDetachEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData - iam:* Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI.IAM.3 IAMFullAdminPolicyDetachEnabledRule: Type: AWS::Events::Rule Properties: Name: IAMFullAdminPolicyDetachEnabledRule Description: "PCI.IAM.3 – Ensure IAM policies are attached only to groups or roles" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt IAMFullAdminPolicyDetachEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "IAMFullAdminPolicyDetachEnabledLambda" - "Arn" Id: "PCIIAM3" IAMFullAdminPolicyDetachEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIIAM3 Description: PCI.IAM.3 Events from Security Hub Id: PCIIAM3 IAMFullAdminPolicyDetachEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "IAMFullAdminPolicyDetachEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "IAMFullAdminPolicyDetachEnabledRule" - "Arn" IAMFullAdminPolicyDetachEnabledLambda: Type: AWS::Lambda::Function DependsOn: IAMFullAdminPolicyDetachEnabledLambdaRole Properties: FunctionName: IAMFullAdminPolicyDetachEnabledLambda Description: PCI.IAM.3 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt IAMFullAdminPolicyDetachEnabledLambdaRole.Arn Runtime: python3.6 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): userArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) userArn_1 = userArn.split(':')[-1] username = userArn_1.replace("user/","") ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIIAM3Automation', DocumentVersion='1', # default Parameters={ 'username': [ username ] } ) except Exception as e: print(e) print("SSM automation execution error") raise IAMFullAdminPolicyDetachEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: IAMFullAdminPolicyDetachEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData - iam:* Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # PCI.S3.4 S3BucketServerSideEncryptionEnabledRule: Type: AWS::Events::Rule Properties: Name: S3BucketServerSideEncryptionEnabledRule Description: "PCI S3.4 – Ensure server side encryption is enabled on S3 buckets" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt S3BucketServerSideEncryptionEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "S3BucketServerSideEncryptionEnabledLambda" - "Arn" Id: "PCIS34" S3BucketServerSideEncryptionEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIS34 Description: PCI S3.4 Event from Security Hub Id: PCIS34 S3BucketServerSideEncryptionEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "S3BucketServerSideEncryptionEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "S3BucketServerSideEncryptionEnabledRule" - "Arn" S3BucketServerSideEncryptionEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: S3BucketServerSideEncryptionEnabledLambda Description: PCI S3.4 Remediation using Custom SSM Document Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt S3BucketServerSideEncryptionEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): S3BucketArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) Id = str(event['detail']['findings'][0]['Id']) S3BucketName = S3BucketArn.replace("arn:aws:s3:::", "") SSEAlgorithm = 'AES256' ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='AWS-EnableS3BucketEncryption', DocumentVersion='1', # default Parameters={ 'BucketName': [ S3BucketName ], 'SSEAlgorithm': [SSEAlgorithm] } ) except Exception as e: print(e) print("SSM automation execution error") raise S3BucketServerSideEncryptionEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: S3BucketServerSideEncryptionEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole - s3:* - kms:* Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #[PCI.S3.3] S3ReplicationEnabledRule: Type: AWS::Events::Rule Properties: Name: S3ReplicationEnabledRule Description: "[PCI.S3.3] S3 buckets should have cross-region replication enabled" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt S3ReplicationEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "S3ReplicationEnabledLambda" - "Arn" Id: "PCIS33" S3ReplicationEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIS33 Description: PCI S3.3 S3 buckets should have cross-region replication enabled Id: PCIS33 S3ReplicationEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "S3ReplicationEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "S3ReplicationEnabledRule" - "Arn" S3ReplicationEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: S3ReplicationEnabledLambda Description: PCI S3.3 S3 buckets should have cross-region replication enabled Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt S3ReplicationEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: DestinationBucketName : !ImportValue S3ReplicationBucketFullName S3IAMReplicationRole : !ImportValue S3BucketReplicationRoleArn Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): S3BucketArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) SourceBucketName = S3BucketArn.replace("arn:aws:s3:::", "") DestinationBucketName = os.environ['DestinationBucketName'] S3IAMReplicationRole = os.environ['S3IAMReplicationRole'] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIS33Automation', DocumentVersion='1', # default Parameters={ 'S3IAMReplicationRole': [ S3IAMReplicationRole ], 'SourceBucketName': [ SourceBucketName], 'DestinationBucketName': [DestinationBucketName] } ) except Exception as e: print(e) print("SSM automation execution error") raise S3ReplicationEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: S3ReplicationEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole - s3:* Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #[PCI.SSM.1] SSMBaselinePatchComplianceEnabledRule: Type: AWS::Events::Rule Properties: Name: SSMBaselinePatchComplianceEnabledRule Description: "[PCI.SSM.1] Amazon EC2 instances managed by Systems Manager should have a patch compliance status of COMPLIANT after a patch installation" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt SSMBaselinePatchComplianceEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "SSMBaselinePatchComplianceEnabledLambda" - "Arn" Id: "PCISSM1" SSMBaselinePatchComplianceEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCISSM1 Description: "[PCI.SSM.1] Amazon EC2 instances managed by Systems Manager should have a patch compliance status of COMPLIANT after a patch installation" Id: PCISSM1 SSMBaselinePatchComplianceEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "SSMBaselinePatchComplianceEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "SSMBaselinePatchComplianceEnabledRule" - "Arn" SSMBaselinePatchComplianceEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: SSMBaselinePatchComplianceEnabledLambda Description: "[PCI.SSM.1] Amazon EC2 instances managed by Systems Manager should have a patch compliance status of COMPLIANT after a patch installation" Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt SSMBaselinePatchComplianceEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): SSMInstanceArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) SSMInstanceArn_1 = SSMInstanceArn.split('::')[-1] InstanceId = SSMInstanceArn_1.replace("ManagedInstanceInventory/","") ssm = boto3.client('ssm') try: response = ssm.send_command( InstanceIds=[ InstanceId ], DocumentName='AWS-RunPatchBaseline', DocumentVersion='1', TimeoutSeconds=360, Comment='RunPatchBaseline Invoked in response to Security Hub finding', Parameters={ 'Operation': [ 'Install' ] }, CloudWatchOutputConfig={ 'CloudWatchOutputEnabled': True } ) except Exception as e: print(e) print("SSM automation execution error") raise SSMBaselinePatchComplianceEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: SSMBaselinePatchComplianceEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - ssm:* - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole - ec2:* Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #[PCI.Lambda.1] RestrictPublicAccessLambdaEnabledRule: Type: AWS::Events::Rule Properties: Name: RestrictPublicAccessLambdaEnabledRule Description: "[PCI.Lambda.1] Lambda functions should prohibit public access" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt RestrictPublicAccessLambdaEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "RestrictPublicAccessLambdaEnabledLambda" - "Arn" Id: "PCILambda1" RestrictPublicAccessLambdaEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCILambda1 Description: "[PCI.Lambda.1] Lambda functions should prohibit public access" Id: PCILambda1 RestrictPublicAccessLambdaEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "RestrictPublicAccessLambdaEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "RestrictPublicAccessLambdaEnabledRule" - "Arn" RestrictPublicAccessLambdaEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: RestrictPublicAccessLambdaEnabledLambda Description: "[PCI.Lambda.1] Lambda functions should prohibit public access" Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt RestrictPublicAccessLambdaEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: accountID : !Ref 'AWS::AccountId' Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): functionname = str(event['detail']['findings'][0]['Resources'][0]['Details']['AwsLambdaFunction']['FunctionName']) Id = str(event['detail']['findings'][0]['Id']) accountID = os.environ['accountID'] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCILambda1Automation', DocumentVersion='1', # default Parameters={ 'functionname': [ functionname ], 'accountID': [accountID] } ) except Exception as e: print(e) print("SSM automation execution error") raise RestrictPublicAccessLambdaEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: RestrictPublicAccessLambdaEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole - lambda:* Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #[PCI.Lambda.2] RestrictLambdaVPCLambdaEnabledRule: Type: AWS::Events::Rule Properties: Name: RestrictLambdaVPCLambdaEnabledRule Description: "[PCI.Lambda.2] Lambda functions should be in a VPC" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt RestrictLambdaVPCLambdaEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "RestrictLambdaVPCLambdaEnabledLambda" - "Arn" Id: "PCILambda2" RestrictLambdaVPCLambdaEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCILambda2 Description: "[PCI.Lambda.2] Lambda functions should be in a VPC" Id: PCILambda2 RestrictLambdaVPCLambdaEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "RestrictLambdaVPCLambdaEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "RestrictLambdaVPCLambdaEnabledRule" - "Arn" RestrictLambdaVPCLambdaEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: RestrictLambdaVPCLambdaEnabledLambda Description: "[PCI.Lambda.2] Lambda functions should be in a VPC" Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt RestrictLambdaVPCLambdaEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: securitygroupid : !ImportValue securitygroup1 subnet1id : !ImportValue subnet1 subnet2id : !ImportValue subnet2 rolearn: !ImportValue RestrictLambdaVPCRoleArn Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): functionname = str(event['detail']['findings'][0]['Resources'][0]['Details']['AwsLambdaFunction']['FunctionName']) Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') rolearn = os.environ['rolearn'] securitygroupid = os.environ['securitygroupid'] subnet1id = os.environ['subnet1id'] subnet2id = os.environ['subnet2id'] try: response = ssm.start_automation_execution( DocumentName='PCILambda2Automation', DocumentVersion='1', # default Parameters={ 'functionname': [functionname], 'rolearn': [rolearn], 'subnet1id': [subnet1id], 'subnet2id': [subnet2id], 'securitygroupid': [ securitygroupid] } ) except Exception as e: print(e) print("SSM automation execution error") raise RestrictLambdaVPCLambdaEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: RestrictLambdaVPCLambdaEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole - lambda:* - ec2:* Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #[PCI.RDS.2] RDSNonPublicInstanceEnabledRule: Type: AWS::Events::Rule Properties: Name: RDSNonPublicInstanceEnabledRule Description: "[PCI.RDS.2] RDS instances should prohibit public access" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt RDSNonPublicInstanceEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "RDSNonPublicInstanceEnabledLambda" - "Arn" Id: "PCIRDS2" RDSNonPublicInstanceEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIRDS2 Description: "[PCI.RDS.2] RDS instances should prohibit public access" Id: PCIRDS2 RDSNonPublicInstanceEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "RDSNonPublicInstanceEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "RDSNonPublicInstanceEnabledRule" - "Arn" RDSNonPublicInstanceEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: RDSNonPublicInstanceEnabledLambda Description: "[PCI.RDS.2] RDS instances should prohibit public access" Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt RDSNonPublicInstanceEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): dbinstanceArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) dbinstanceId = dbinstanceArn.split(':')[-1] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIRDS2Automation', DocumentVersion='1', # default Parameters={ 'dbinstanceId': [ dbinstanceId ] } ) except Exception as e: print(e) print("SSM automation execution error") raise RDSNonPublicInstanceEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: RDSNonPublicInstanceEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #[PCI.Redshift.1] RedshiftNonPublicClusterEnabledRule: Type: AWS::Events::Rule Properties: Name: RedshiftNonPublicClusterEnabledRule Description: "[PCI.Redshift.1] Amazon Redshift clusters should prohibit public access" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt RedshiftNonPublicClusterEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "RedshiftNonPublicClusterEnabledLambda" - "Arn" Id: "PCIRedshift1" RedshiftNonPublicClusterEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIRedshift1 Description: "[PCI.Redshift.1] Amazon Redshift clusters should prohibit public access" Id: PCIRedshift1 RedshiftNonPublicClusterEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "RedshiftNonPublicClusterEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "RedshiftNonPublicClusterEnabledRule" - "Arn" RedshiftNonPublicClusterEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: RedshiftNonPublicClusterEnabledLambda Description: "[PCI.Redshift.1] Amazon Redshift clusters should prohibit public access" Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt RedshiftNonPublicClusterEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): clusterArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) clusterId = clusterArn.split(':')[-1] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIRedshift1Automation', DocumentVersion='1', # default Parameters={ 'clusterId': [ clusterId ] } ) except Exception as e: print(e) print("SSM automation execution error") raise RedshiftNonPublicClusterEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: RedshiftNonPublicClusterEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # [PCI.RDS.1] RDSPublicNonRestoreSnapshotEnabledRule: Type: AWS::Events::Rule Properties: Name: RDSPublicNonRestoreSnapshotEnabledRule Description: "[PCI.RDS.1] RDS snapshots should prohibit public access" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt RDSPublicNonRestoreSnapshotEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "RDSPublicNonRestoreSnapshotEnabledLambda" - "Arn" Id: "PCIRDS1" RDSPublicNonRestoreSnapshotEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIRDS1 Description: "[PCI.RDS.1] RDS snapshots should prohibit public access" Id: PCIRDS1 RDSPublicNonRestoreSnapshotEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "RDSPublicNonRestoreSnapshotEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "RDSPublicNonRestoreSnapshotEnabledRule" - "Arn" RDSPublicNonRestoreSnapshotEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: RDSPublicNonRestoreSnapshotEnabledLambda Description: "[PCI.RDS.1] RDS snapshots should prohibit public access" Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt RDSPublicNonRestoreSnapshotEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): snapshotArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) snapshotType = str(event['detail']['findings'][0]['Resources'][0]['Type']) snapshotId = snapshotArn.split(':')[-1] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIRDS1Automation', DocumentVersion='1', # default Parameters={ 'snapshotId': [snapshotId], 'snapshotType': [snapshotType] } ) except Exception as e: print(e) print("SSM automation execution error") raise RDSPublicNonRestoreSnapshotEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: RDSPublicNonRestoreSnapshotEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole #[PCI.EC2.6] VPCFlowLogsEnabledRule: Type: AWS::Events::Rule Properties: Name: VPCFlowLogsEnabledRule Description: "PCI EC2.6 – Ensure VPC flow logging is enabled in all VPCs" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt VPCFlowLogsEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "VPCFlowLogsEnabledLambda" - "Arn" Id: "PCIEC26" VPCFlowLogsEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIEC26 Description: PCIEC26 Id: PCIEC26 VPCFlowLogsEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "VPCFlowLogsEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "VPCFlowLogsEnabledRule" - "Arn" VPCFlowLogsEnabledLambda: Type: AWS::Lambda::Function DependsOn: VPCFlowLogsEnabledLambdaRole Properties: FunctionName: VPCFlowLogsEnabledLambda Description: PCI EC2.6 Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt VPCFlowLogsEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Environment: Variables: CloudWatchLogGroupArn : !ImportValue FlowLogsCloudWatchLogGroupArn CloudWatchLogGroupName : !ImportValue FlowLogsCloudWatchLogs FlowLogRoleArn : !ImportValue FlowLogsRoleArn Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): VpcArn = str(event['detail']['findings'][0]['Resources'][0]['Id']) VpcId_1 = VpcArn.split(':')[-1] VpcId = VpcId_1.replace("vpc/","") Id = str(event['detail']['findings'][0]['Id']) CloudWatchLogGroupArn = os.environ['CloudWatchLogGroupArn'] CloudWatchLogGroupName = os.environ['CloudWatchLogGroupName'] FlowLogRoleArn = os.environ['FlowLogRoleArn'] ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIEC26Automation', DocumentVersion='1', # default Parameters={ 'FlowLogRoleArn': [ FlowLogRoleArn ], 'CloudWatchLogGroupArn': [ CloudWatchLogGroupArn ], 'CloudWatchLogGroupName': [ CloudWatchLogGroupName ], 'VpcId': [ VpcId ] } ) except Exception as e: print(e) print("SSM automation execution error") raise VPCFlowLogsEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: VPCFlowLogsEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole - ec2:* Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole # [PCI.EC2.1] EBSPublicNonRestoreSnapshotEnabledRule: Type: AWS::Events::Rule Properties: Name: EBSPublicNonRestoreSnapshotEnabledRule Description: "[PCI.EC2.1] Amazon EBS snapshots should not be publicly restorable" EventPattern: source: - aws.securityhub detail-type: - Security Hub Findings - Custom Action resources: - !GetAtt EBSPublicNonRestoreSnapshotEnabledActionTarget.Arn State: "ENABLED" Targets: - Arn: Fn::GetAtt: - "EBSPublicNonRestoreSnapshotEnabledLambda" - "Arn" Id: "PCIEC2.1" EBSPublicNonRestoreSnapshotEnabledActionTarget: Type: Custom::ActionTarget Version: 1.0 Properties: ServiceToken: !GetAtt CreateSecurityHubCustomActionTargetLambda.Arn Name: PCIEC21 Description: "[PCI.EC2.1] Amazon EBS snapshots should not be publicly restorable" Id: PCIEC21 EBSPublicNonRestoreSnapshotEnabledPermission: Type: AWS::Lambda::Permission Properties: FunctionName: Ref: "EBSPublicNonRestoreSnapshotEnabledLambda" Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: Fn::GetAtt: - "EBSPublicNonRestoreSnapshotEnabledRule" - "Arn" EBSPublicNonRestoreSnapshotEnabledLambda: Type: AWS::Lambda::Function Properties: FunctionName: EBSPublicNonRestoreSnapshotEnabledLambda Description: "[PCI.EC2.1] Amazon EBS snapshots should not be publicly restorable" Handler: index.lambda_handler MemorySize: 256 Role: !GetAtt EBSPublicNonRestoreSnapshotEnabledLambdaRole.Arn Runtime: python3.7 Timeout: 60 Code: ZipFile: | import boto3 import json import os def lambda_handler(event, context): snapshotId = str(event['detail']['findings'][0]['Resources'][0]['Details']['AwsEc2Volume']['SnapshotId']) Id = str(event['detail']['findings'][0]['Id']) ssm = boto3.client('ssm') try: response = ssm.start_automation_execution( DocumentName='PCIEC21Automation', DocumentVersion='1', # default Parameters={ 'snapshotId': [ snapshotId ] } ) except Exception as e: print(e) print("SSM automation execution error") raise EBSPublicNonRestoreSnapshotEnabledLambdaRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: EBSPublicNonRestoreSnapshotEnabledLambdaPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - cloudwatch:PutMetricData Resource: '*' - Effect: Allow Action: - ssm:StartAutomationExecution - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents - logs:DescribeLogGroups - iam:PassRole - ec2:* Resource: '*' - Effect: Allow Action: - cloudtrail:UpdateTrail - securityhub:UpdateFindings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: { Service: lambda.amazonaws.com } Action: - sts:AssumeRole