# License: Copyright 2021 Amazon Web Services, Inc. or its affiliates.
# All Rights Reserved.

# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#    http://aws.amazon.com/apache2.0/
# or in the "license" file accompanying this file.

# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.

# If the PCI DSS fails to enable, due to a race condition on new AWS Accounts created in your AWS Organization,
# add this resource to the template that enables the PCI DSS standard.

AWSTemplateFormatVersion: "2010-09-09"
Description: "Security Hub - Invoke Lambda that enables the PCI DSS standard"

Resources:
  EventRule:
    Type: 'AWS::Events::Rule'
    Properties:
      Name: enable-pci-standard
      Description: CloudWatch Event Rule that detects creation of Security Hub to enable PCI standard
      State: ENABLED
      Targets:
        -
          Arn:
            Fn::GetAtt:
              - SHLambdaFunctionEB
              - 'Arn'
          Id: "target-id-sh-pci"
      EventPattern:
        detail-type:
          - AWS API Call via CloudTrail
        detail:
          eventSource:
            - securityhub.amazonaws.com
          eventName:
            - EnableSecurityHub
            
  SHLambdaFunctionEB:
    Type: 'AWS::Lambda::Function'
    Properties:
      Code:
        ZipFile: |
          import sys,json,boto3,os

          def lambda_handler(event,context):
            region = os.environ['AWS_REGION']
            sh = boto3.client('securityhub')
            #Change it to the desired standard to enable
            standardArn=f"arn:aws:securityhub:{region}::standards/pci-dss/v/3.2.1"
            print(standardArn)
            standards_subscription_request = [{'StandardsArn': standardArn}]
            try:                
              sh.batch_enable_standards(StandardsSubscriptionRequests=standards_subscription_request)
              print("Security Hub standard enabled")
            except Exception as ex:
              print("failed executing actions: " + str(ex))
      Handler: index.lambda_handler
      MemorySize: 128
      Role:
        'Fn::GetAtt':
          - SHLambdaRole
          - Arn
      Runtime: "python3.7"
      Timeout: 300

  SHLambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: 
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
        - 'arn:aws:iam::aws:policy/AWSSecurityHubReadOnlyAccess'
      Policies:
        - PolicyName: iam-sh-enable-pci-standard
          PolicyDocument:
            Statement:
              - Effect: Allow
                Action:
                  - securityhub:BatchEnableStandards
                Resource: "*"