AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Parameters:
  DataCenter:
    Description: The Data Center your CloudGuard account is being run on
    Type: String
    Default: 'USA'
    AllowedValues:
      - Australia
      - Canada
      - Europe
      - India
      - Singapore
      - USA
  EmailAddress:
    Description: OPTIONAL - Email address to send output logs to
    Type: String
    Default: ''
  OutputMode:
    Description: Output Mode - can be as text or as JSON
    Type: String
    Default: JSON
    AllowedValues:
      - text
      - JSON
  sendLogs:
    Description: Send logs to Dome9
    Type: String
    Default: True
    AllowedValues:
      - True
      - False
  DeploymentMode:
    Description: Deployment Mode - can be single or multi
    Type: String
    Default: single
    AllowedValues:
      - single
      - multi

Conditions:
  CreateSubscriber: !Not [!Equals [!Ref EmailAddress, ""]]
  IsDcAustralia: !Equals
    - !Ref DataCenter
    - Australia
  IsDcCanada: !Equals
    - !Ref DataCenter
    - Canada
  IsDcEurope: !Equals
    - !Ref DataCenter
    - Europe
  IsDcIndia: !Equals
    - !Ref DataCenter
    - India
  IsDcSingapore: !Equals
    - !Ref DataCenter
    - Singapore
  IsDcUsa: !Equals
    - !Ref DataCenter
    - USA

Resources:
  InputTopic:
    Type: "AWS::SNS::Topic"
    Properties:
      DisplayName: 'd9-findings'
      TopicName: 'd9-findings'

  InputTopicPolicy:
    Type: AWS::SNS::TopicPolicy
    Properties:
      PolicyDocument:
        Id: D9DeliveryPolicy
        Version: '2012-10-17'
        Statement:
          - Sid: D9DeliveryPolicy
            Effect: Allow
            Principal:
              AWS:
                !If [ IsDcUsa, 'arn:aws:iam::634729597623:root',
                !If [ IsDcIndia, 'arn:aws:iam::578204784313:root',
                !If [ IsDcAustralia, 'arn:aws:iam::434316140879:root',
                !If [ IsDcSingapore, 'arn:aws:iam::597850136722:root',
                !If [ IsDcEurope, 'arn:aws:iam::723885542676:root',
                !If [ IsDcCanada, 'arn:aws:iam::431603698195:root', !Ref "AWS::NoValue"]]]]]]
            Action: sns:Publish
            Resource: !Ref InputTopic
      Topics:
        - !Ref InputTopic

  OutputTopic:
    Type: "AWS::SNS::Topic"
    Properties:
      DisplayName: 'remediationOutput'
      TopicName: 'remediationOutput'

  OutputTopicSubscription:
    Type: AWS::SNS::Subscription
    Condition: CreateSubscriber
    Properties:
      Endpoint: !Ref EmailAddress
      Protocol: email
      TopicArn: !Ref OutputTopic

  RemediationFunction:
    Type: "AWS::Serverless::Function"
    Properties:
      FunctionName: Dome9CloudBots
      Description: 'Auto-remediation actions from Dome9 events'
      CodeUri:
        Bucket: !Join [ '' , [ 'dome9cloudbotsemplates' , !Join [ '', !Split [ "-" , !Ref "AWS::Region" ] ] ] ]
        Key: 71-985e6ced512d302be340b4cf51a6d12a78e780eb.zip
      Runtime: python3.9
      Timeout: 120 # Most will be under 8 seconds, but delete IGW needs to wait for the instances to be off before detaching from the VPC. This takes a bunch of time.
      Tracing: Active
      Handler: index.lambda_handler
      Policies:
        - Version: '2012-10-17' # Custom Policy Document
          Statement:
            - Effect: Allow
              Action:
                - acm:DeleteCertificate # For acm_delete_certificate
                - cloudtrail:LookupEvents - #For look_up function in bot_utils
                - cloudtrail:CreateTrail # For create_cloudtrail
                - cloudtrail:LookupEvents # for bots_utils.py
                - cloudtrail:StartLogging # For create_cloudtrail
                - cloudtrail:UpdateTrail # For cloudtrail_send_to_cloudwatch
                - cloudtrail:LookupEvents # For bots that need the event for additional information
                - cloudwatch:PutMetricAlarm # For cloudtrail_send_to_cloudwatch
                - config:PutConfigurationRecorder # For config_enable
                - config:PutDeliveryChannel # For config_enable
                - config:StartConfigurationRecorder # For config_enable
                - ecr-public:BatchDeleteImage # for delete_image_from_ecs_repo
                - ec2:AssociateIamInstanceProfile # For ec2_attach_instance_role
                - ec2:AuthorizeSecurityGroupEgress # For sg_single_rule_delete
                - ec2:AuthorizeSecurityGroupIngress # For sg_single_rule_delete
                - ec2:CreateFlowLogs # For vpc_turn_on_flow_logs
                - ec2:CreateSecurityGroup # For instance_quarantine
                - ec2:CreateSnapshot # For ec2_create_snapshot
                - ec2:CreateTags # For ec2_tag_instance
                - ec2:DeleteSecurityGroup # For sg_delete
                - ec2:DeleteInternetGateway # For igw_delete
                - ec2:DetachInternetGateway # For igw_delete
                - ec2:DescribeAddresses # For ec2_release_eips
                - ec2:DescribeSecurityGroups # For instance_quarantine
                - ec2:DescribeSecurityGroupsRules # for intelligence_sg_rules_delete_by_scope
                - ec2:DescribeInstances # For igw_delete
                - ec2:DisassociateAddress # For ec2_release_eips
                - ec2:ModifyImageAttribute # For ami_set_to_private
                - ec2:ModifyInstanceAttribute # For instance_quarantine
                - ec2:MonitorInstances # For ec2_enable_detailed_monitoring
                - ec2:ReplaceNetworkAclEntry # For acl revert modification bot
                - ec2:CreateNetworkAclEntry # For acl revert modification bot
                - ec2:DeleteNetworkAclEntry # For acl revert modification bot
                - ec2:ReplaceNetworkAclAssociation # For bot isolate vpc
                - ec2:DescribeVpcs # For bot isolate vpc
                - ec2:CreateNetworkAcl # For bot isolate vpc 
                - ec2:ModifyVpcAttribute # For bot isolate vpc 
                - ec2:DescribeNetworkAcls # For bot isolate vpc        
                - ec2:DeleteNetworkAcl #For acl delete bot
                - ec2:DeleteVpc # For vpc_delete
                - ec2:ReleaseAddress # For ec2_release_eips
                - ec2:DeleteKeyPair # For ec2_delete_key_pair
                - ec2:RevokeSecurityGroupEgress # For sg_rules_delete
                - ec2:RevokeSecurityGroupIngress # For sg_rules_delete
                - ec2:StopInstances # For ec2_stop_instance
                - ec2:TerminateInstances # For ec2_terminate_instance
                - ec2:DescribeRegions # To get all regions
                - ecs:UpdateContainerInstancesState #For Ecs stop bot and reboot bot
                - ecs:DescribeTaskDefinition #For Ecs stop bot and reboot bot
                - ecs:ListTasks #For Ecs stop bot and reboot bot
                - ecs:StopTask #For Ecs stop bot and reboot bot
                - ecs:DescribeTasks #For Ecs stop bot and reboot bot
                - ecs:ListClusters #For Ecs stop bot and reboot bot
                - kms:DescribeKey # for sns_enforce_sse & sqs_enforce_sse
                - kms:EnableKeyRotation # For kms_enable_rotation
                - iam:AttachRolePolicy # For ec2_update_instance_role and others
                - iam:AttachUserPolicy # For iam_quarantine_user
                - iam:CreatePolicy 
                - iam:CreateRole # For vpc_turn_on_flow_logs and iam_role_clone_with_non_enumerable_name
                - iam:DetachGroupPolicy # for iam_detach_policy
                - iam:DetachRolePolicy # for iam_detach_policy
                - iam:DetachUserPolicy # for iam_detach_policy
                - iam:DeletePolicy # for iam_user_delete_inline_policies
                - iam:DeleteAccessKey # for the delete_access_key
                - iam:GetPolicy # for iam_detach_policy
                - iam:ListEntitiesForPolicy # for iam_detach_policy
                - iam:DeleteGroupPolicy # for iam_group_delete_inline_policy
                - iam:ListUsers # For bot isolate vpc 
                - iam:ListInstanceProfilesForRole # For ec2_detach_instance_role
                - iam:ListGroupPolicies # for iam_group_delete_inline_policy
                - iam:RemoveRoleFromInstanceProfile # For ec2_detach_instance_role
                - iam:PassRole # Effective 28 April, 2018, AWS users who call CreateFlowLogs will be required to have the IAM PassRole permission[1].
                - iam:UpdateAccessKey # for the revoke_access_key
                - iam:UpdateAccountPasswordPolicy # For IAM_turn_on_password_policy
                - iam:UpdateLoginProfile # For iam_user_force_password_change
                - iam:RemoveUserFromGroup # For iam_user_detach
                - lambda:UpdateFunctionConfiguration # For lambda_detach_external_layer
                - lambda:GetFunction # For lambda_detach_external_layer
                - lambda:GetLayerVersion # For lambda_detach_external_layer
                - iam:ListPolicyVersions # For iam_delete_default_policy_version
                - iam:SetDefaultPolicyVersion # For iam_delete_default_policy_version
                - iam:DeletePolicyVersion # For iam_delete_default_policy_version
                - iam:GetRole # For iam_role_clone_with_non_enumerable_name
                - iam:ListRolePolicies # For iam_role_clone_with_non_enumerable_name
                - iam:ListAttachedRolePolicies # For iam_role_clone_with_non_enumerable_name
                - iam:TagRole # For iam_role_clone_with_non_enumerable_name
                - iam:PutRolePolicy # For iam_role_clone_with_non_enumerable_name
                - iam:GenerateCredentialReport # For iam_generate_credential_report
                - logs:PutMetricFilter # For cloudwatch_create_metric_filter
                - logs:CreateLogGroup # For cloudtrail_send_to_cloudwatch
                - rds:ModifyDBInstance # For rds_quarantine_instance
                - ssm:ModifyDocumentPermission # For ssm_document_set_private
                - s3:CreateBucket # For create_cloudtrail
                - s3:DeleteBucket # For s3_delete_bucket
                - s3:DeleteBucketPolicy # For s3_delete_permissions
                - s3:DeleteBucketWebsite # for s3_disable_static_website_hosting
                - s3:GetBucketAcl # For s3_delete_permissions
                - s3:GetBucketPolicy # For s3_delete_permissions
                - s3:GetObject
                - s3:HeadBucket # For s3_enable_logging
                - s3:PutBucketAcl # For s3_delete_permissions
                - s3:PutBucketLogging # For s3_enable_logging
                - s3:PutBucketPolicy # For create_cloudtrail
                - s3:PutBucketVersioning # For s3_enable_versioning
                - s3:PutEncryptionConfiguration # For s3_enable_encryption
                - s3:PutObject # For create_cloudtrail
                - s3:PutPublicAccessBlock # Required for bot s3_block_all_public_access.py
                - sns:Publish # For exporting the logs from CS2
                - sns:CreateTopic # For cloudwatch_create_metric_filter
                - sns:Subscribe # For cloudwatch_create_metric_filter
                - sns:DeleteTopic # For sns_topic_delete
                - sns:SetTopicAttributes # For sns_enforce_sse
                - sns:ListSubscriptionsByTopic # For cloudwatch_create_metric_filter
                - sqs:SetQueueAttributes # For sqs_enforce_sse
                - sqs:CreateQueue # For sqs_configure_dlq
                - sqs:GetQueueAttributes # For sqs_configure_dlq
                - sqs:ListDeadLetterSourceQueues # For sqs_configure_dlq
                - sts:GetCallerIdentity # For checking what account this is running in
                - sts:AssumeRole # For multi_account
                - lambda:PutFunctionConcurrency # For lambda disable
                - lambda:TagResource # For lambda_tag
                - elasticloadbalancing:ModifyLoadBalancerAttributes # For load_balancer_enable_access_logs
                - network-firewall:UpdateLoggingConfiguration # For network_firewall_enable_logging
                - logs:ListLogDeliveries # For network_firewall_enable_logging
                - logs:CreateLogDelivery # For network_firewall_enable_logging
                - logs:GetLogDelivery # For network_firewall_enable_logging
                - iam:CreateServiceLinkedRole # For network_firewall_enable_logging
                - firehose:TagDeliveryStream # For network_firewall_enable_logging (in order to send logs to a delivery stream)
                - iam:DeleteRolePolicy # For ecs_role_detach_inline_policy
                - iam:DeleteLoginProfile # For iam_user_disable_console_password
                - kms:EnableKey # For kms_cmk_enable_key
                - kms:CancelKeyDeletion # For kms_cmk_enable_key
                - secretsmanager:UpdateSecret # For secretsmanager_enable_encryption
                - kms:GenerateDataKey # For secretsmanager_enable_encryption
                - kms:Decrypt # For secretsmanager_enable_encryption
                - route53domains:EnableDomainAutoRenew # For route53domain_enable_auto_renew
                - route53domains:EnableDomainTransferLock # For route53domain_enable_transfer_lock

              Resource: '*'
            - Effect: Allow
              Action: 'ssm:GetParameter'
              Resource:  {"Fn::Sub": "arn:aws:ssm:us-east-1::parameter/aws/service/global-infrastructure/regions/*"}
      Environment:
        Variables:
          SNS_TOPIC_ARN: !Ref OutputTopic
          ACCOUNT_MODE: !Ref DeploymentMode
          OUTPUT_TYPE: !Ref OutputMode
          SEND_LOGS_TO_DOME9: !Ref sendLogs
      Events:
        d9Findings:
          Type: SNS
          Properties:
            Topic: !Ref InputTopic


Outputs:
  InputTopicARN:
    Description: 'ARN that Dome9 sends events to'
    Value: !Ref InputTopic
  OutputTopicARN:
    Description: 'ARN for the export logs topic'
    Value: !Ref OutputTopic


