AWSTemplateFormatVersion: 2010-09-09
Parameters:
  CustomActionArnParameter:
    Type: String
    Description: >-
      (Optional) The ARN for a Security Hub custom action.  If provided, only
      findings selected under this custom action will be sent to Phantom.
Conditions:
  CustomActionArnParameterProvided: !Not 
    - !Equals 
      - !Ref CustomActionArnParameter
      - ''
Resources:
  securityHubCWERule:
    Type: 'AWS::Events::Rule'
    DependsOn: phantomSQSReadQueue
    Properties:
      Description: SecurityHub Event Rule
      EventPattern:
        source:
          - aws.securityhub
        resources: !If 
          - CustomActionArnParameterProvided
          - - !Ref CustomActionArnParameter
          - !Ref 'AWS::NoValue'
      State: ENABLED
      Targets:
        - Arn: !GetAtt 
            - phantomSQSReadQueue
            - Arn
          Id: SecurityHubTopic
    Metadata:
      Comment: >-
        Create a Cloud Watch Event rule for forwarding Security Hub alerts into
        an SQS Queue.  Use a conditional statement to only apply the 'Resource'
        filtering if a user supplied the optional parameter to specify a
        customer action ARN.  These ARN's are produced by creating a 'custom
        action' from the Security Hub Settings page
  phantomSQSReadQueue:
    Type: 'AWS::SQS::Queue'
    Properties: {}
    Metadata:
      Comment: >-
        Create a SQS queue to store all or selected Security Hub alerts.  The
        Phantom Security Hub app will use this queue to ingest alerts
  phantomSQSReadQueuePolicy:
    Type: 'AWS::SQS::QueuePolicy'
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Sid: TrustCWEToSendEventsToPhantomSQS
            Action: 'sqs:SendMessage'
            Resource: !GetAtt 
              - phantomSQSReadQueue
              - Arn
            Condition:
              ArnEquals:
                'aws:SourceArn': !GetAtt 
                  - securityHubCWERule
                  - Arn
      Queues:
        - !Ref phantomSQSReadQueue
    Metadata:
      Comment: >-
        Create a SQS queue policy.  This policy is required to ensure the SQS
        queue can receive input from Cloud Watch Events
Outputs:
  securityHubToPhantomSQSURL:
    Description: >-
      SQS URL used by Phantom to ingest Security Hub Findings from your account.  This will be needed to setup your Phantom Security Hub app.
    Value: !Ref phantomSQSReadQueue