######################################################################## # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 ######################################################################## AWSTemplateFormatVersion: 2010-09-09 Description: This template creates a custom resource Lambda to delegate administration and configure Detective within an AWS Organization - 'detective_org' solution in the repo, https://github.com/aws-samples/aws-security-reference-architecture-examples (sra-1ssgnse80) Metadata: SRA: Version: 1.0 Order: 3 AWS::CloudFormation::Interface: ParameterGroups: - Label: default: General Properties Parameters: - pSRASolutionName - pSRAStagingS3BucketName - pSRAAlarmEmail - pGuarddutyEnabledForMoreThan48Hours - Label: default: Lambda Function Properties Parameters: - pDetectiveOrgLambdaRoleName - pDetectiveOrgLambdaFunctionName - pOrganizationId - Label: default: Custom Resource Properties Parameters: - pDatasourcePackages - pDetectiveConfigurationRoleName - pDelegatedAdminAccountId - pControlTowerRegionsOnly - pEnabledRegions - Label: default: General Lambda Function Properties Parameters: - pCreateLambdaLogGroup - pLambdaLogGroupRetention - pLambdaLogGroupKmsKey - pLambdaLogLevel - Label: default: EventBridge Rule Properties Parameters: - pComplianceFrequency - pControlTowerLifeCycleRuleName - pEventRuleRoleName ParameterLabels: pComplianceFrequency: default: Frequency to Check for Organizational Compliance pControlTowerLifeCycleRuleName: default: Control Tower Lifecycle Rule Name pControlTowerRegionsOnly: default: Control Tower Regions Only pCreateLambdaLogGroup: default: Create Lambda Log Group pDatasourcePackages: default: (Optional) Datasource packages to start pDelegatedAdminAccountId: default: Delegated Admin Account ID pEnabledRegions: default: (Optional) Enabled Regions pGuarddutyEnabledForMoreThan48Hours: default: Guardduty Enabled More Than 48 Hours pEventRuleRoleName: default: Event Rule Role Name pLambdaLogGroupKmsKey: default: (Optional) Lambda Logs KMS Key pLambdaLogGroupRetention: default: Lambda Log Group Retention pLambdaLogLevel: default: Lambda Log Level pOrganizationId: default: Organization ID pSRAAlarmEmail: default: (Optional) SRA Alarm Email pSRASolutionName: default: SRA Solution Name pSRAStagingS3BucketName: default: SRA Staging S3 Bucket Name pDetectiveOrgLambdaFunctionName: default: Lambda Function Name pDetectiveOrgLambdaRoleName: default: Lambda Role Name pDetectiveConfigurationRoleName: default: Detective Configuration Role Name Parameters: pComplianceFrequency: ConstraintDescription: Compliance Frequency must be a number between 1 and 30, inclusive. Default: 7 Description: Frequency (in days between 1 and 30, default is 7) to check organizational compliance MinValue: 1 MaxValue: 30 Type: Number pControlTowerLifeCycleRuleName: AllowedPattern: '^[\w.-]{1,64}$' ConstraintDescription: Max 64 alphanumeric and underscore characters. Also special characters supported [., -] Default: sra-detective-org-trigger Description: The name of the AWS Control Tower Life Cycle Rule. Type: String pControlTowerRegionsOnly: AllowedValues: [true, false] Default: true Description: Only enable in the Control Tower governed regions Type: String pCreateLambdaLogGroup: AllowedValues: ['true', 'false'] Default: 'false' Description: Indicates whether a CloudWatch Log Group should be explicitly created for the Lambda function, to allow for setting a Log Retention and/or KMS Key for encryption. Type: String pDatasourcePackages: AllowedValues: [EKS_AUDIT, ASFF_SECURITYHUB_FINDING] Default: EKS_AUDIT, ASFF_SECURITYHUB_FINDING Description: Optional datasources used to populate the behavior graph Type: CommaDelimitedList pDelegatedAdminAccountId: AllowedPattern: '^\d{12}$' ConstraintDescription: Must be 12 digits Description: Delegated administrator account ID Type: String pEnabledRegions: AllowedPattern: '^$|^([a-z0-9-]{1,64})$|^(([a-z0-9-]{1,64},)*[a-z0-9-]{1,64})$' ConstraintDescription: Only lowercase letters, numbers, and hyphens ('-') allowed. (e.g. us-east-1) Additional AWS regions can be provided, separated by commas. (e.g. us-east-1,ap-southeast-2) Description: (Optional) Enabled regions (AWS regions, separated by commas). Leave blank to enable all regions. Type: String pEventRuleRoleName: AllowedPattern: '^[\w+=,.@-]{1,64}$' ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [+, =, ., @, -]. Default: sra-detective-global-events Description: Event rule role name for putting events on the home region event bus Type: String pGuarddutyEnabledForMoreThan48Hours: AllowedValues: ['true', 'false'] Default: 'false' Description: Has Guardduty been enabled in the Organization for more than 48 hours? Type: String pDetectiveOrgLambdaFunctionName: AllowedPattern: '^[\w-]{0,64}$' ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [_, -] Default: sra-detective-org Description: Lambda function name Type: String pDetectiveOrgLambdaRoleName: AllowedPattern: '^[\w+=,.@-]{1,64}$' ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [+, =, ., @, -] Default: sra-detective-org-lambda Description: Detective configuration Lambda role name Type: String pDetectiveConfigurationRoleName: AllowedPattern: '^[\w+=,.@-]{1,64}$' ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [+, =, ., @, -] Default: sra-detective-configuration Description: Detective Configuration role to assume in the delegated administrator account Type: String pLambdaLogGroupKmsKey: AllowedPattern: '^$|^arn:(aws[a-zA-Z-]*){1}:kms:[a-z0-9-]+:\d{12}:key\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' ConstraintDescription: 'Key ARN example: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab' Description: (Optional) KMS Key ARN to use for encrypting the Lambda logs data. If empty, encryption is enabled with CloudWatch Logs managing the server-side encryption keys. Type: String pLambdaLogGroupRetention: AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653] Default: 14 Description: Specifies the number of days you want to retain log events Type: String pLambdaLogLevel: AllowedValues: [INFO, ERROR, DEBUG] Default: INFO Description: Lambda Function Logging Level Type: String pOrganizationId: AllowedPattern: '^o-[a-z0-9]{10,32}$' ConstraintDescription: The Organization ID must be a 12 character string starting with o- and followed by 10 lower case alphanumeric characters Description: AWS Organizations ID Type: String pSRAAlarmEmail: AllowedPattern: '^$|^([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$' ConstraintDescription: Must be a valid email address. Description: (Optional) Email address for receiving DLQ alarms Type: String pSRASolutionName: AllowedValues: [sra-detective-org] Default: sra-detective-org Description: The SRA solution name. The default value is the folder name of the solution Type: String pSRAStagingS3BucketName: AllowedPattern: '^(?=^.{3,63}$)(?!.*[.-]{2})(?!.*[--]{2})(?!^(?:(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(?!$)|$)){4}$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)' ConstraintDescription: SRA Staging S3 bucket name can include numbers, lowercase letters, uppercase letters, and hyphens (-). It cannot start or end with a hyphen (-). Description: SRA Staging S3 bucket name for the artifacts relevant to solution. (e.g., lambda zips, CloudFormation templates) S3 bucket name can include numbers, lowercase letters, uppercase letters, and hyphens (-). It cannot start or end with a hyphen (-). Type: String Conditions: cComplianceFrequencySingleDay: !Equals [!Ref pComplianceFrequency, 1] cCreateDLQAlarm: !Not [!Equals [!Ref pSRAAlarmEmail, '']] cCreateLambdaLogGroup: !Equals [!Ref pCreateLambdaLogGroup, 'true'] cUseGraviton: !Or - !Equals [!Ref 'AWS::Region', ap-northeast-1] - !Equals [!Ref 'AWS::Region', ap-south-1] - !Equals [!Ref 'AWS::Region', ap-southeast-1] - !Equals [!Ref 'AWS::Region', ap-southeast-2] - !Equals [!Ref 'AWS::Region', eu-central-1] - !Equals [!Ref 'AWS::Region', eu-west-1] - !Equals [!Ref 'AWS::Region', eu-west-2] - !Equals [!Ref 'AWS::Region', us-east-1] - !Equals [!Ref 'AWS::Region', us-east-2] - !Equals [!Ref 'AWS::Region', us-west-2] cUseKmsKey: !Not [!Equals [!Ref pLambdaLogGroupKmsKey, '']] cNotGlobalRegionUsEast1: !Not [!Equals [!Ref 'AWS::Region', us-east-1]] Resources: rDetectiveOrgLambdaLogGroup: Type: AWS::Logs::LogGroup Condition: cCreateLambdaLogGroup DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: LogGroupName: !Sub /aws/lambda/${pDetectiveOrgLambdaFunctionName} KmsKeyId: !If - cUseKmsKey - !Ref pLambdaLogGroupKmsKey - !Ref AWS::NoValue RetentionInDays: !Ref pLambdaLogGroupRetention rDetectiveOrgLambdaRole: Type: AWS::IAM::Role Metadata: cfn_nag: rules_to_suppress: - id: W11 reason: Actions require wildcard in resource - id: W28 reason: The role name is defined checkov: skip: - id: CKV_AWS_111 comment: IAM write actions require wildcard in resource Properties: RoleName: !Ref pDetectiveOrgLambdaRoleName AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Action: sts:AssumeRole Effect: Allow Principal: Service: - lambda.amazonaws.com Path: '/' Policies: - PolicyName: sra-detective-org-policy-cloudformation PolicyDocument: Version: 2012-10-17 Statement: - Sid: CloudFormation Effect: Allow Action: cloudformation:ListStackInstances Resource: !Sub arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stackset/AWSControlTowerBP-* - PolicyName: sra-detective-org-policy PolicyDocument: Version: 2012-10-17 Statement: - Sid: DetectiveAccess Effect: Allow Action: - detective:EnableOrganizationAdminAccount - detective:DisableOrganizationAdminAccount - detective:ListOrganizationAdminAccount Resource: '*' - PolicyName: sra-detective-org-policy-iam PolicyDocument: Version: 2012-10-17 Statement: - Sid: AssumeRole Effect: Allow Action: sts:AssumeRole Condition: StringEquals: aws:PrincipalOrgId: !Ref pOrganizationId Resource: - !Sub arn:${AWS::Partition}:iam::*:role/${pDetectiveConfigurationRoleName} - Sid: AllowReadIamActions Effect: Allow Action: iam:GetRole Resource: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/* - Sid: AllowCreateServiceLinkedRole Effect: Allow Action: iam:CreateServiceLinkedRole Condition: StringLike: iam:AWSServiceName: detective.amazonaws.com Resource: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/aws-service-role/detective.amazonaws.com/AWSServiceRoleForDetective - Sid: AllowPolicyActions Effect: Allow Action: iam:PutRolePolicy Resource: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/aws-service-role/detective.amazonaws.com/AWSServiceRoleForDetective - Sid: AllowDeleteServiceLinkedRole Effect: Allow Action: iam:DeleteServiceLinkedRole Resource: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/aws-service-role/detective.amazonaws.com/AWSServiceRoleForDetective - PolicyName: sra-detective-org-policy-logs PolicyDocument: Version: 2012-10-17 Statement: - Sid: CreateLogGroupAndEvents Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: !Sub arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${pDetectiveOrgLambdaFunctionName}:log-stream:* - PolicyName: sra-detective-org-policy-organizations PolicyDocument: Version: 2012-10-17 Statement: - Sid: OrganizationsReadAccess Effect: Allow Action: - organizations:DescribeOrganization - organizations:ListAWSServiceAccessForOrganization - organizations:ListAccounts - organizations:ListDelegatedAdministrators Resource: '*' - Sid: AWSServiceAccess Effect: Allow Action: - organizations:DisableAWSServiceAccess - organizations:EnableAWSServiceAccess Condition: StringLikeIfExists: organizations:ServicePrincipal: detective.amazonaws.com Resource: '*' - Sid: RegisterDeregisterDelegatedAdministrator Effect: Allow Action: - organizations:DeregisterDelegatedAdministrator - organizations:RegisterDelegatedAdministrator Resource: '*' - PolicyName: sra-detective-org-policy-sqs PolicyDocument: Version: 2012-10-17 Statement: - Sid: SQSSendMessage Effect: Allow Action: sqs:SendMessage Resource: !GetAtt rDetectiveOrgDLQ.Arn Tags: - Key: sra-solution Value: !Ref pSRASolutionName rDetectiveOrgLambdaFunction: Type: AWS::Lambda::Function Metadata: cfn_nag: rules_to_suppress: - id: W58 reason: CloudWatch access provided by the attached IAM role - id: W89 reason: Lambda is not deployed within a VPC - id: W92 reason: Lambda does not need reserved concurrent executions. checkov: skip: - id: CKV_AWS_115 comment: Lambda does not need reserved concurrent executions. - id: CKV_AWS_117 comment: Lambda does not need to communicate with VPC resources. - id: CKV_AWS_173 comment: Environment variables are not sensitive. Properties: FunctionName: !Ref pDetectiveOrgLambdaFunctionName Description: configure Detective for the Organization Architectures: !If - cUseGraviton - [arm64] - !Ref AWS::NoValue Handler: app.lambda_handler Role: !GetAtt rDetectiveOrgLambdaRole.Arn MemorySize: 512 Runtime: python3.9 Timeout: 900 Code: S3Bucket: !Ref pSRAStagingS3BucketName S3Key: !Sub ${pSRASolutionName}/lambda_code/${pSRASolutionName}.zip Layers: - !Ref rDetectiveOrgLambdaLayer DeadLetterConfig: TargetArn: !GetAtt rDetectiveOrgDLQ.Arn Environment: Variables: LOG_LEVEL: !Ref pLambdaLogLevel AWS_PARTITION: !Ref AWS::Partition CONFIGURATION_ROLE_NAME: !Ref pDetectiveConfigurationRoleName CONTROL_TOWER_REGIONS_ONLY: !Ref pControlTowerRegionsOnly DATASOURCE_PACKAGES: !Join - ',' - !Ref pDatasourcePackages DELEGATED_ADMIN_ACCOUNT_ID: !Ref pDelegatedAdminAccountId ENABLED_REGIONS: !Ref pEnabledRegions GUARDDUTY_ENABLED_FOR_MORE_THAN_48_HOURS: !Ref pGuarddutyEnabledForMoreThan48Hours MANAGEMENT_ACCOUNT_ID: !Ref AWS::AccountId Tags: - Key: sra-solution Value: !Ref pSRASolutionName rDetectiveOrgLambdaLayer: Type: AWS::Lambda::LayerVersion Properties: Content: S3Bucket: !Ref pSRAStagingS3BucketName S3Key: !Sub ${pSRASolutionName}/layer_code/${pSRASolutionName}-layer.zip Description: Boto3 version 1.26.24 layer to enable newer API of detective LayerName: !Sub ${pDetectiveOrgLambdaFunctionName}-updated-boto3-layer rDetectiveOrgLambdaCustomResource: Type: Custom::LambdaCustomResource Version: '1.0' Properties: ServiceToken: !GetAtt rDetectiveOrgLambdaFunction.Arn CONFIGURATION_ROLE_NAME: !Ref pDetectiveConfigurationRoleName CONTROL_TOWER_REGIONS_ONLY: !Ref pControlTowerRegionsOnly DELEGATED_ADMIN_ACCOUNT_ID: !Ref pDelegatedAdminAccountId DATASOURCE_PACKAGES: !Join - ',' - !Ref pDatasourcePackages ENABLED_REGIONS: !Ref pEnabledRegions rDetectiveOrgDLQ: Type: AWS::SQS::Queue Properties: KmsMasterKeyId: alias/aws/sqs QueueName: !Sub ${pSRASolutionName}-dlq Tags: - Key: sra-solution Value: !Ref pSRASolutionName MessageRetentionPeriod: 345600 DeletionPolicy: Delete UpdateReplacePolicy: Delete rDetectiveOrgDLQPolicy: Type: AWS::SQS::QueuePolicy Properties: Queues: - !Ref rDetectiveOrgDLQ PolicyDocument: Statement: - Action: SQS:SendMessage Condition: ArnEquals: aws:SourceArn: - !GetAtt rDetectiveOrgLambdaFunction.Arn Effect: Allow Principal: Service: events.amazonaws.com Resource: - !GetAtt rDetectiveOrgDLQ.Arn rDetectiveOrgDLQAlarmTopic: Condition: cCreateDLQAlarm Type: AWS::SNS::Topic Properties: DisplayName: !Sub ${pSRASolutionName}-dlq-alarm KmsMasterKeyId: !Sub arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:alias/aws/sns TopicName: !Sub ${pSRASolutionName}-dlq-alarm Subscription: - Endpoint: !Ref pSRAAlarmEmail Protocol: email Tags: - Key: sra-solution Value: !Ref pSRASolutionName rDetectiveOrgDLQAlarm: Condition: cCreateDLQAlarm Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: SRA DLQ alarm if the queue depth is 1 Namespace: AWS/SQS MetricName: ApproximateNumberOfMessagesVisible Dimensions: - Name: QueueName Value: !GetAtt rDetectiveOrgDLQ.QueueName Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: 1 ComparisonOperator: GreaterThanThreshold AlarmActions: - !Ref rDetectiveOrgDLQAlarmTopic InsufficientDataActions: - !Ref rDetectiveOrgDLQAlarmTopic rPermissionForScheduledComplianceRuleToInvokeLambda: Type: AWS::Lambda::Permission Properties: FunctionName: !GetAtt rDetectiveOrgLambdaFunction.Arn Action: lambda:InvokeFunction Principal: events.amazonaws.com SourceArn: !GetAtt rScheduledComplianceRule.Arn rScheduledComplianceRule: Type: AWS::Events::Rule Properties: Name: !Sub ${pControlTowerLifeCycleRuleName}-organization-compliance Description: SRA Detective Trigger for scheduled organization compliance ScheduleExpression: !If - cComplianceFrequencySingleDay - !Sub rate(${pComplianceFrequency} day) - !Sub rate(${pComplianceFrequency} days) State: ENABLED Targets: - Arn: !GetAtt rDetectiveOrgLambdaFunction.Arn Id: !Ref pDetectiveOrgLambdaFunctionName rCrossRegionEventRuleRole: Type: AWS::IAM::Role Condition: cNotGlobalRegionUsEast1 Metadata: cfn_nag: rules_to_suppress: - id: W28 reason: Specific role name provided Properties: RoleName: !Ref pEventRuleRoleName AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: sts:AssumeRole Principal: Service: - events.amazonaws.com Policies: - PolicyName: sra-account-alternate-contacts-policy-events PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: events:PutEvents Resource: !Sub arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/default Outputs: oDetectiveOrgLambdaFunctionArn: Description: SRA Detective Lambda Function ARN Value: !GetAtt rDetectiveOrgLambdaFunction.Arn oDetectiveOrgLambdaLogGroupArn: Condition: cCreateLambdaLogGroup Description: SRA Detective Lambda Log Group ARN Value: !GetAtt rDetectiveOrgLambdaLogGroup.Arn oDetectiveOrgLambdaRoleArn: Description: SRA Detective Lambda Role ARN Value: !GetAtt rDetectiveOrgLambdaRole.Arn