AWSTemplateFormatVersion: 2010-09-09
Description: >-
  Create a read-only cross account role that authorizes access for CloudGuard
  Dome9.
Metadata:
  Version: 2.0.0
Parameters:
  CloudGuardAwsAccountId:
    Description: CloudGuard instance AWS AccountId that is requiring external trust
    Type: String
  RoleExternalTrustSecret:
    Description: CloudGuard generated unique id for assuming external trust
    Type: String
  UniqueSuffix:
    Description: An optional suffix for all resources
    Type: String
    Default: ''
    MaxLength: 19
  UseAwsReadOnlyPolicy:
    Description: >-
      When enabled, CloudGuard uses the AWS ReadOnlyAccess policy that grants
      CloudGuard permissions to support new services in the future
    Type: String
    AllowedValues:
      - Enable
      - Disable
    Default: Enable
Conditions:
  UseReadOnlyPolicy: !Equals 
    - !Ref UseAwsReadOnlyPolicy
    - Enable
Resources:
  CrossAccountRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub CloudGuard-Connect-RO-role${UniqueSuffix}
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub arn:${AWS::Partition}:iam::${CloudGuardAwsAccountId}:root
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref RoleExternalTrustSecret
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/SecurityAudit
        - !If 
          - UseReadOnlyPolicy
          - arn:aws:iam::aws:policy/ReadOnlyAccess
          - !Ref AWS::NoValue
  CrossAccountReadOnlyPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub CloudGuard-Connect-RO-policy${UniqueSuffix}
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: CloudGuardReadOnly
            Action:
              - fms:ListTagsForResource
              - fms:GetAdminScope
              - fms:GetPolicy
              - fms:ListAdminAccountsForOrganization
              - forecast:DescribeDataset
              - forecast:DescribeAutoPredictor
              - forecast:DescribePredictor
              - forecast:ListDatasetGroups
              - forecast:ListExplainabilities
              - forecast:ListForecasts
              - forecast:ListMonitors
              - forecast:ListPredictors
              - forecast:ListTagsForResource
              - appfabric:ListAppBundles
              - appfabric:GetAppBundle
              - appfabric:ListTagsForResource
              - lightsail:GetRelationalDatabases
              - lightsail:GetRelationalDatabaseParameters
              - lightsail:GetLoadBalancerTlsCertificates
              - lightsail:GetDomains
              - lightsail:GetDistributions
              - batch:DescribeJobQueues
              - appflow:ListConnectors
              - apigateway:GET
              - athena:GetQueryExecution
              - budgets:ViewBudget
              - cassandra:Select
              - codeartifact:ListDomains
              - codeartifact:DescribeDomain
              - codeartifact:ListTagsForResource
              - codeartifact:DescribeRepository
              - compute-optimizer:GetRecommendationSummaries
              - macie2:DescribeBuckets
              - macie2:GetMacieSession
              - macie2:GetFindingStatistics
              - macie2:ListAutomatedDiscoveryAccounts
              - verifiedpermissions:ListPolicyStores
              - verifiedpermissions:GetPolicyStore
              - elasticfilesystem:Describe*
              - cloudhsm:DescribeClusters
              - cloudhsm:DescribeBackups
              - glacier:ListTagsForVault
              - bedrock:ListAgents
              - bedrock:GetAgent
              - bedrock:ListKnowledgeBases
              - bedrock:GetKnowledgeBase
              - glue:GetConnections
              - glue:GetMLTransforms
              - healthlake:ListTagsForResource
              - devops-guru:DescribeServiceIntegration
              - kinesis:List*
              - kinesis:Describe*
              - kinesisvideo:Describe*
              - kinesisvideo:List*
              - logs:Get*
              - logs:FilterLogEvents
              - logs:ListLogDeliveries
              - lex:ListTagsForResource
              - codebuild:ListBuilds
              - codebuild:BatchGetBuilds
              - codepipeline:ListWebhooks
              - memorydb:DescribeACLs
              - memorydb:DescribeParameters
              - memorydb:DescribeSnapshots
              - memorydb:DescribeUsers
              - memorydb:ListTags
              - personalize:ListTagsForResource
              - s3:List*
              - ses:ListEmailIdentities
              - sns:ListPlatformApplications
              - transcribe:Get*
              - transcribe:List*
              - translate:GetTerminology
              - appstream:DescribeUsageReportSubscriptions
              - aps:ListWorkspaces
              - aps:DescribeWorkspace
              - aps:DescribeLoggingConfiguration
              - cloudformation:ListTypes
              - cloudformation:DescribeType
              - cloudformation:BatchDescribeTypeConfigurations
              - amplify:ListApps
              - serverlessrepo:GetApplication
              - simspaceweaver:ListSimulations
              - simspaceweaver:ListTagsForResource
              - simspaceweaver:DescribeSimulation
              - grafana:DescribeWorkspace
              - mediaconvert:ListJobs
              - mediaconvert:ListPresets
              - mediaconvert:ListQueues
              - mediaconvert:ListTagsForResource
              - mediapackage:ListChannels
              - mediastore:ListTagsForResource
              - mediatailor:ListChannels
              - mediatailor:GetChannelPolicy
              - mediatailor:ListPlaybackConfigurations
              - mediatailor:ListSourceLocations
              - mediapackage:ListHarvestJobs
              - dataexchange:ListTagsForResource
              - dataexchange:ListEventActions
              - dataexchange:ListJobs
              - datazone:ListDomains
              - datazone:ListTagsForResource
              - elastictranscoder:ListPresets
              - medialive:ListInputs
              - medialive:ListMultiplexes
              - medialive:ListReservations
              - medialive:ListInputSecurityGroups
              - drs:DescribeJobs
              - drs:DescribeJobLogItems
              - drs:DescribeSourceServers
              - drs:DescribeRecoverySnapshots
              - drs:DescribeSourceNetworks
              - drs:DescribeRecoveryInstances
              - drs:GetFailbackReplicationConfiguration
              - drs:DescribeReplicationConfigurationTemplates
              - drs:DescribeLaunchConfigurationTemplates
              - timestream:ListBatchLoadTasks
              - timestream:ListDatabases
              - timestream:ListTables
              - timestream:ListTagsForResource
              - timestream:DescribeEndpoints
              - timestream:ListScheduledQueries
              - signer:ListTagsForResource
              - signer:ListSigningJobs
              - signer:ListSigningPlatforms
              - signer:ListSigningProfiles
              - storagegateway:DescribeSMBFileShares
              - ds:ListTagsForResource
              - support:DescribeCases
              - support:DescribeSeverityLevels
              - outposts:ListOutposts
              - waf-regional:ListLoggingConfigurations
              - wafv2:GetIPSet
              - finspace:ListTagsForResource
              - lakeformation:GetDataLakeSettings
              - lakeformation:ListResources
              - cognito-idp:ListResourcesForWebACL
              - apprunner:ListAssociatedServicesForWebAcl
              - ce:GetAnomalyMonitors
              - account:GetContactInformation
              - wellarchitected:ListWorkloads
              - polly:ListSpeechSynthesisTasks
              - wellarchitected:GetWorkload
              - elasticmapreduce:ListStudios
              - macie2:GetAutomatedDiscoveryConfiguration
              - redshift-serverless:ListNamespaces
              - qldb:ListTagsForResource
              - auditmanager:GetAssessment
              - codecommit:GetApprovalRuleTemplate
              - backup:ListBackupPlans
              - codeguru-security:ListTagsForResource
              - codeguru-security:ListScans
              - codeguru-security:GetScan
              - cleanrooms:ListMemberships
              - cleanrooms:ListTagsForResource
              - route53-recovery-control-config:ListControlPanels
              - route53-recovery-control-config:ListRoutingControls
              - route53-recovery-control-config:ListTagsForResource
              - payment-cryptography:ListKeys
              - payment-cryptography:ListTagsForResource
              - servicediscovery:ListServices
              - servicediscovery:ListTagsForResource
              - servicediscovery:ListNamespaces
              - artifact:ListReports
              - comprehendmedical:ListEntitiesDetectionV2Jobs
              - networkmanager:ListCoreNetworks
              - networkmanager:ListAttachments
              - networkmanager:GetCoreNetwork
              - kendra:DescribeDataSource
              - eks:ListAddons
              - eks:DescribeAddon
              - omics:ListAnnotationStores
              - omics:ListTagsForResource
              - fis:ListExperiments
              - fis:GetExperiment
              - fis:ListExperimentTemplates
              - fis:GetExperimentTemplate
              - appstream:DescribeDirectoryConfigs
              - scn:ListInstances
              - scn:ListTagsForResource
              - support:DescribeTrustedAdvisorCheckResult
              - support:DescribeTrustedAdvisorChecks
              - textract:ListAdapters
              - textract:ListAdapterVersions
              - textract:GetAdapter
              - textract:GetAdapterVersion
            Effect: Allow
            Resource: '*'
          - Sid: CloudGuardDeny
            Effect: Deny
            Action:
              - glacier:GetJobOutput
              - s3:GetObjectTorrent
              - dynamodb:BatchGet*
              - dynamodb:PartiQLSelect
              - dynamodb:Query
              - dynamodb:Scan
              - dynamodb:Get*
              - qldb:GetBlock
              - qldb:GetDigest
              - qldb:GetRevision
              - sdb:Select*
            Resource: '*'
          - Sid: ElasticbeanstalkConfigurationSettingsPermission
            Action:
              - s3:GetObject
            Effect: Allow
            Resource: !Sub arn:${AWS::Partition}:s3:::elasticbeanstalk-env-resources-??*?/*
      Roles:
        - !Ref CrossAccountRole
  CrossAccountReadOnlyPolicy2:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub CloudGuard-Connect-RO-policy-2-${UniqueSuffix}
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: CloudGuardReadOnly
            Action:
              - m2:ListEnvironments
              - m2:GetEnvironment
              - m2:ListApplications
              - m2:GetApplication
              - aoss:BatchGetCollection
              - aoss:ListSecurityPolicies
              - aoss:ListSecurityConfigs
              - aoss:ListAccessPolicies
              - aoss:ListTagsForResource
              - aoss:ListCollections
              - glue:GetDatabases
              - resiliencehub:ListApps
              - resiliencehub:ListTagsForResource
              - iot:DescribeInput
              - iot:ListTagsForResource
              - mgn:DescribeReplicationConfigurationTemplates
              - appflow:DescribeFlow
              - bedrock:ListGuardrails
              - bedrock:GetGuardrail
              - ec2:GetSnapshotBlockPublicAccessState
              - ec2:GetImageBlockPublicAccessState
              - ec2:GetEbsEncryptionByDefault
            Effect: Allow
            Resource: '*'
      Roles:
        - !Ref CrossAccountRole
Outputs:
  CrossAccountRoleArn:
    Description: The CrossAccount Role Arn
    Value: !GetAtt CrossAccountRole.Arn
